问:
how to pass data from servlet to android application
```<code>I have a form in android upon submit im inserting it into database using servlet i have to show to user that form was inserted successfully. this is my application

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.ArrayList;

/**
 *
 * @author trainee
 */
public class form extends HttpServlet {

String name;
String password;
Connection con = null;
Statement stmt = null;
/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */

        /* TODO output your page here
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet form</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet form at " + request.getContextPath () + "</h1>");
        out.println("</body>");
        out.println("</html>");
        */

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

   try
  {

  }

  catch(Exception ex)
  {

  }
}

/**
 * Handles the HTTP <code>POST</code> method.
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
  try
  {
     Class.forName("com.mysql.jdbc.Driver");
     con =DriverManager.getConnection ("jdbc:mysql://localhost:3306/Login","root", "");
     String nn=request.getParameter("name");
     String pass=request.getParameter("pass");
     String email=request.getParameter("email");
     stmt=con.createStatement();
     String query="insert into users values('"+nn+"','"+pass+"','"+email+"');";
     int v=stmt.executeUpdate(query);
     ArrayList<String> arr=new ArrayList<String>();
     arr.add("inserted");

System.out.println("sent response back...");

  }
  catch(Exception ex)
  {

  }

}

/**
 * Returns a short description of the servlet.
 * @return a String containing servlet description
 */
@Override
public String getServletInfo() {
    return "Short description";
}// </editor-fold>

}
</code>```

this is my android application

```<code>package org.me.loginandroid;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.*;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.apache.http.client.methods.HttpGet;

public class MainActivity extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button btn1 = (Button) findViewById(R.id.submit);
        btn1.setOnClickListener(listener_login);
    }
    private OnClickListener listener_login = new OnClickListener() {

        boolean check = false;

        public void onClick(View v) {
            EditText emailText = (EditText) findViewById(R.id.email);
            EditText passText = (EditText) findViewById(R.id.password);
            EditText nameText = (EditText) findViewById(R.id.uname);

            String name = nameText.getText().toString();
            String email = (emailText.getText().toString());
            String pass = (passText.getText().toString());

            String result = "";
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("name", name));
            nameValuePairs.add(new BasicNameValuePair("pass", pass));
            nameValuePairs.add(new BasicNameValuePair("email", email));

            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://10.0.2.2:8084/Login/form");
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                InputStream is = entity.getContent();

                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                result = sb.toString();
                TextView lbl = (TextView) findViewById(R.id.lbl);
                lbl.setText(result);
            } catch (Exception e) {
                TextView tv = (TextView) findViewById(R.id.err);
                tv.setText("Error parsing data " + e.toString());
                System.out.println("Error parsing data " + e.toString());
            }
            //parse json data
            try {
                boolean check=false;
               ArrayList<String> arrays=new ArrayList<String>();
               for(int i=0;i<arrays.size();i++)
               {
                   if(arrays.get(i).equals("Inserted"))
                   {
                        check=true;
                   }
                   else
                   {
                   }
               }
               if(check)
               {
                   Intent myintent = new Intent(MainActivity.this, welcome.class);
                   startActivity(myintent);
               }
               else
               {
                    TextView tv = (TextView) findViewById(R.id.err);
                    tv.setText("Data was not inserted properly");
               }

            } catch (Exception e) {
                //setContentView(R.layout.notify);
                TextView tv = (TextView) findViewById(R.id.err);
                tv.setText(e.toString());
                System.out.println("log_tag" + "Error parsing data ");

            }
        }
    };
}
</code>```

答:
you can get data from servlet to andriod application through json format.
Please go through this

    http://wiebe-elsinga.com/blog/?p=405 link to get an idea of how to call Servlet from andriod application and get the response
back in json format.

call to Servlet from Andriod

```<code>  private InputStream callService(String text) {
          InputStream in = null;
           SERVLET_URL = http://wizkid.com/web/updateServlet";
          try {
               URL url = new URL(SERVLET_URL);
               URLConnection conn = url.openConnection();

               HttpURLConnection httpConn = (HttpURLConnection) conn;
               httpConn.setRequestMethod("POST");
               httpConn.setDoInput(true);
               httpConn.setDoOutput(true);
               httpConn.connect();

               DataOutputStream dataStream = new DataOutputStream(conn
                         .getOutputStream());

               dataStream.writeBytes(text);
               dataStream.flush();
               dataStream.close();

               int responseCode = httpConn.getResponseCode();
               if (responseCode == HttpURLConnection.HTTP_OK) {
                    in = httpConn.getInputStream();
               }
          } catch (Exception ex) {
               display("Error: Not not connect");
          }
          return in;
     }
</code>```

// Get Data from Server to andriod

```<code>   private String getResultFromServlet(String text) {
          String result = "";

          InputStream in = callService(text);
          if (in != null) {
               JSONObject jsonResponse;
               try {
                    jsonResponse = new JSONObject(convertStreamToString(in));
                    result = jsonResponse.getString("output");
               } catch (JSONException e) {
                    result = "Error: JSON Object couldn't be made";
               }
          } else {
               result = "Error: Service not returning result";
          }
          return result;
     }
</code>```

Body:
I have a form in android upon submit im inserting it into database using servlet i have to show to user that form was inserted successfully. this is my application

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.ArrayList;

/**
 *
 * @author trainee
 */
public class form extends HttpServlet {

String name;
String password;
Connection con = null;
Statement stmt = null;
/**
 * Processes requests for both HTTP GET and POST methods.
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */

        /* TODO output your page here
        out.println("");
        out.println("");
        out.println("<title>Servlet form</title>");
        out.println("");
        out.println("");
        out.println("
Servlet form at " + request.getContextPath () + "
");
        out.println("");
        out.println("");
        */

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

   try
  {

  }

  catch(Exception ex)
  {

  }
}

/**
 * Handles the HTTP POST method.
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
  try
  {
     Class.forName("com.mysql.jdbc.Driver");
     con =DriverManager.getConnection ("jdbc:mysql://localhost:3306/Login","root", "");
     String nn=request.getParameter("name");
     String pass=request.getParameter("pass");
     String email=request.getParameter("email");
     stmt=con.createStatement();
     String query="insert into users values('"+nn+"','"+pass+"','"+email+"');";
     int v=stmt.executeUpdate(query);
     ArrayList<String> arr=new ArrayList<String>();
     arr.add("inserted");

System.out.println("sent response back...");

  }
  catch(Exception ex)
  {

  }

}

/**
 * Returns a short description of the servlet.
 * @return a String containing servlet description
 */
@Override
public String getServletInfo() {
    return "Short description";
}// </editor-fold>

}

this is my android application

package org.me.loginandroid;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.*;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.apache.http.client.methods.HttpGet;

public class MainActivity extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button btn1 = (Button) findViewById(R.id.submit);
        btn1.setOnClickListener(listener_login);
    }
    private OnClickListener listener_login = new OnClickListener() {

        boolean check = false;

        public void onClick(View v) {
            EditText emailText = (EditText) findViewById(R.id.email);
            EditText passText = (EditText) findViewById(R.id.password);
            EditText nameText = (EditText) findViewById(R.id.uname);

            String name = nameText.getText().toString();
            String email = (emailText.getText().toString());
            String pass = (passText.getText().toString());

            String result = "";
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("name", name));
            nameValuePairs.add(new BasicNameValuePair("pass", pass));
            nameValuePairs.add(new BasicNameValuePair("email", email));

            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://10.0.2.2:8084/Login/form");
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                InputStream is = entity.getContent();

                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                result = sb.toString();
                TextView lbl = (TextView) findViewById(R.id.lbl);
                lbl.setText(result);
            } catch (Exception e) {
                TextView tv = (TextView) findViewById(R.id.err);
                tv.setText("Error parsing data " + e.toString());
                System.out.println("Error parsing data " + e.toString());
            }
            //parse json data
            try {
                boolean check=false;
               ArrayList<String> arrays=new ArrayList<String>();
               for(int i=0;i<arrays.size();i++)
               {
                   if(arrays.get(i).equals("Inserted"))
                   {
                        check=true;
                   }
                   else
                   {
                   }
               }
               if(check)
               {
                   Intent myintent = new Intent(MainActivity.this, welcome.class);
                   startActivity(myintent);
               }
               else
               {
                    TextView tv = (TextView) findViewById(R.id.err);
                    tv.setText("Data was not inserted properly");
               }

            } catch (Exception e) {
                //setContentView(R.layout.notify);
                TextView tv = (TextView) findViewById(R.id.err);
                tv.setText(e.toString());
                System.out.println("log_tag" + "Error parsing data ");

            }
        }
    };
}

Body:
you can get data from servlet to andriod application through json format.
Please go through this

    http://wiebe-elsinga.com/blog/?p=405 link to get an idea of how to call Servlet from andriod application and get the response
back in json format.

call to Servlet from Andriod

  private InputStream callService(String text) {
          InputStream in = null;
           SERVLET_URL = http://wizkid.com/web/updateServlet";
          try {
               URL url = new URL(SERVLET_URL);
               URLConnection conn = url.openConnection();

               HttpURLConnection httpConn = (HttpURLConnection) conn;
               httpConn.setRequestMethod("POST");
               httpConn.setDoInput(true);
               httpConn.setDoOutput(true);
               httpConn.connect();

               DataOutputStream dataStream = new DataOutputStream(conn
                         .getOutputStream());

               dataStream.writeBytes(text);
               dataStream.flush();
               dataStream.close();

               int responseCode = httpConn.getResponseCode();
               if (responseCode == HttpURLConnection.HTTP_OK) {
                    in = httpConn.getInputStream();
               }
          } catch (Exception ex) {
               display("Error: Not not connect");
          }
          return in;
     }

// Get Data from Server to andriod

   private String getResultFromServlet(String text) {
          String result = "";

          InputStream in = callService(text);
          if (in != null) {
               JSONObject jsonResponse;
               try {
                    jsonResponse = new JSONObject(convertStreamToString(in));
                    result = jsonResponse.getString("output");
               } catch (JSONException e) {
                    result = "Error: JSON Object couldn't be made";
               }
          } else {
               result = "Error: Service not returning result";
          }
          return result;
     }


来源: stackexchange

问:
My header stays fixed, but my body still scrolls through it
If i put a high z-index on the header, that part works beautifully, but then none of the links in the other divs are clickable! I am overlooking something simple, and I can't see it. I can include other bits of my css - just not even sure where to look now.

Header before scrolling and rolling up:

Header rolled up but with content showing through it:

HTML:

FROM THE HEADER FILE

```<code><nav class="navbar navbar-default wh_header"
     xmlns="http://www.w3.org/1999/xhtml"
     xmlns:whc="http://www.oxygenxml.com/webhelp/components">
    <div class="container">
        <div class="wh_header_flex_container">
            <div class="wh_logo_and_publication_title_container">
                <div class="wh_logo_and_publication_title">
                    <whc:include_html href="${webhelp.fragment.before.logo_and_title}"/>
                    <!--
                            This component will be generated when the next parameters are specified in the transformation scenario:
                            'webhelp.logo.image' and 'webhelp.logo.image.target.url'.
                            See: http://oxygenxml.com/doc/versions/17.1/ug-editor/#topics/dita_webhelp_output.html.
                    -->
                    <whc:webhelp_logo class="hidden-xs"/>
                    <whc:webhelp_publication_title/>
                    <whc:include_html href="${webhelp.fragment.after.logo_and_title}"/>
                </div>

             <div class="print index">
                 <whc:webhelp_breadcrumb/>
                 <whc:webhelp_search_input/>
                 <whc:webhelp_print_link class="print"/>
                <whc:webhelp_indexterms_link/>
             </div>

                <!-- The menu button for mobile devices is copied in the output only when the 'webhelp.show.top.menu' parameter is set to 'yes' -->
                <button type="button" data-target=".wh_top_menu_and_indexterms_link" id="wh_menu_mobile_button" data-toggle="collapse" class="navbar-toggle collapsed wh_toggle_button">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
            </div>

            <div class="wh_top_menu_and_indexterms_link collapse navbar-collapse">
                <whc:include_html href="${webhelp.fragment.before.top_menu}"/>
                <whc:webhelp_top_menu />
                <!-- <whc:webhelp_indexterms_link/> -->
                <whc:include_html href="${webhelp.fragment.after.top_menu}"/>
            </div>
        </div>

  </div>
</nav>
</code>```

FROM THE BODY OF THE TOPIC FILE

```<code><body class="wh_topic_page" data-spy="scroll" data-target="#toc">
        <!-- EXM-36950 - Expand the args.hdr parameter here -->
        <whc:include_html href="${args.hdr}"/>
        <whc:include_html href="${webhelp.fragment.before.body}"/>
        &header;

        <div class="container-fluid">
            <div class="row">

               <nav class="wh_tools hidden-print">

                    <div class="wh_right_tools hidden-sm hidden-xs">
                        <whc:webhelp_navigation_links/>

                        <whc:webhelp_toggle_highlight/>
                    </div>
                </nav>
            </div>

            <div class="wh_content_area">
                <div class="row">
                    <nav role="navigation"
                        class="col-lg-4 col-md-4 col-sm-4 col-xs-12 navbar hidden-print" id="wh_side_toc">
                        <whc:webhelp_side_toc data-tooltip-position="${webhelp.side.toc.tooltip.position}"/>
                    </nav>
                    <div class="col-lg-8 col-md-8 col-sm-8 col-xs-12" id="topic_content">

                        <div class="col-lg-9 col-md-9 col-sm-9 col-xs-12">
                            <whc:webhelp_topic_content class="body"/>
                            <whc:webhelp_child_links/>
                            <whc:webhelp_related_links/>
                            <whc:webhelp_feedback/>
                        </div>

                        <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12">
                            <nav id="toc" data-spy="affix" data-toggle="toc" data-offset-top="205"></nav>
                        </div>
                    </div>
                </div>
            </div>
        </div> &footer;
</code>```

CSS:

```<code>.navbar {
   /* background-color: transparent; */
 background-color: #e6edf1;
    background-image: none;
   /* background-image: url(images/skin_images/unity_gradient.png);
    background-repeat: repeat-x;*/
    border: none;
    border-radius: 0;
    margin: 0;
    /*position: fixed; */
    /* z-index: 4; */
    top: 0px;
    /*box-shadow: 0 1px 2px 0 black;
    height: 30px;   */

}

.wh_header {
   /*width: 960px;*/
width: 100%;
   margin: auto;
   /*text-align: right;*/
   height: 80px;
/* height: 100px; */
/*    position: fixed;
    top:0px; */
    padding-top: 20px;
    padding-right: 6px;
   /* z-index: 10000; */
  /* background-color: #e6edf1; */
 /* background-color: #ffffff; */
  background-image: url(../../../resources/images/unity_gradient_resized.png);

}

.fixed-header {
  position: fixed;
  top:0; left:0;
  width: 100%;
height: 36px;
padding-top: 6px;

}
</code>```

答:
Try Z-indexing, thisis happening because your Navbar is 'below' your body </p>

```<code>.navbar{
z-index:100
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If i put a high z-index on the header, that part works beautifully, but then none of the links in the other divs are clickable! I am overlooking something simple, and I can't see it. I can include other bits of my css - just not even sure where to look now.

Header before scrolling and rolling up:

Header rolled up but with content showing through it:

HTML:

FROM THE HEADER FILE

                    <whc:include_html href="${webhelp.fragment.before.logo_and_title}"/>

                    <whc:webhelp_logo class="hidden-xs"/>
                    <whc:webhelp_publication_title/>
                    <whc:include_html href="${webhelp.fragment.after.logo_and_title}"/>

                 <whc:webhelp_breadcrumb/>
                 <whc:webhelp_search_input/>
                 <whc:webhelp_print_link class="print"/>
                <whc:webhelp_indexterms_link/>

                <button type="button" data-target=".wh_top_menu_and_indexterms_link" id="wh_menu_mobile_button" data-toggle="collapse" class="navbar-toggle collapsed wh_toggle_button">

                </button>

                <whc:include_html href="${webhelp.fragment.before.top_menu}"/>
                <whc:webhelp_top_menu />

                <whc:include_html href="${webhelp.fragment.after.top_menu}"/>

FROM THE BODY OF THE TOPIC FILE

        <whc:include_html href="${args.hdr}"/>
        <whc:include_html href="${webhelp.fragment.before.body}"/>
        &header;

                        <whc:webhelp_navigation_links/>

                        <whc:webhelp_toggle_highlight/>

                        <whc:webhelp_side_toc data-tooltip-position="${webhelp.side.toc.tooltip.position}"/>

                            <whc:webhelp_topic_content class="body"/>
                            <whc:webhelp_child_links/>
                            <whc:webhelp_related_links/>
                            <whc:webhelp_feedback/>

 &footer;

CSS:

.navbar {
   /* background-color: transparent; */
 background-color: #e6edf1;
    background-image: none;
   /* background-image: url(images/skin_images/unity_gradient.png);
    background-repeat: repeat-x;*/
    border: none;
    border-radius: 0;
    margin: 0;
    /*position: fixed; */
    /* z-index: 4; */
    top: 0px;
    /*box-shadow: 0 1px 2px 0 black;
    height: 30px;   */

}

.wh_header {
   /*width: 960px;*/
width: 100%;
   margin: auto;
   /*text-align: right;*/
   height: 80px;
/* height: 100px; */
/*    position: fixed;
    top:0px; */
    padding-top: 20px;
    padding-right: 6px;
   /* z-index: 10000; */
  /* background-color: #e6edf1; */
 /* background-color: #ffffff; */
  background-image: url(../../../resources/images/unity_gradient_resized.png);

}

.fixed-header {
  position: fixed;
  top:0; left:0;
  width: 100%;
height: 36px;
padding-top: 6px;

}

Body:
Try Z-indexing, thisis happening because your Navbar is 'below' your body

.navbar{
z-index:100
}


问:
Why does built in Azure AD B2C profile edit policy show empty looking login screen?
I have a simple built-in profile edit policy: no social IdP, with custom UI screens.
Why is the first screen the user sees a Microsoft branded login screen, but without all of the usual input labels, headers and footers. The screen is basically an image, two empty boxes and a sign in button.

Have I made an error when configuring the policy? My single sign-on tab has been left to it's defaults. for both sign in and the profile edit policy.

Is this page necessary? If I am coming to this page after recently going through a sign in policy for this tenant, shouldn't SSO just move me to the profile edit screen?

If it is required; can we brand this screen as well using the built in policy? Or at least have the appropriate input labels in the boxes: "Email" and "Password"?

答:
The issue was with the URL I was using. The default link in the Azure portal is not an SSO compatible link, because it includes the url parameter: prompt=login.  By removing it, it will check for an already logged in user, and bypass login.

If anybody else has issues here, you want to also make sure your SSO Config is set to Tenant or Application, or else the sign-in policy cookie won't get used in the profile edit policy


问:
Bind Stroke from the property in ItemSources
I have a collection of the object say MyModel.cs. The collection is called Some. In MyModel it has a property Color which is Brush type.

The Color is Red for all now.

Now I have

```<code><MyControl: x:Name="control1" ItemsSource="{Binding Some}" Stroke="Red">
</code>```

But you see I hardcode the stroke. What I want is something like
     Stroke = "{Binding Some.Color}"

How?

答:
The control displays several models. If you want to set the Stroke property to the Color of one of them, you need to specify which one, e.g.:

```<code><MyControl x:Name="control1" ItemsSource="{Binding Some}" Stroke="{Binding Some[0].Color}">
</code>```

This will bind the Stroke property to the Color property of the first MyModel object, assuming that the Some collection has an indexer.

Body:
I have a collection of the object say MyModel.cs. The collection is called Some. In MyModel it has a property Color which is Brush type.

The Color is Red for all now.

Now I have

<MyControl: x:Name="control1" ItemsSource="{Binding Some}" Stroke="Red">

But you see I hardcode the stroke. What I want is something like
     Stroke = "{Binding Some.Color}"

How?

Body:
The control displays several models. If you want to set the Stroke property to the Color of one of them, you need to specify which one, e.g.:

<MyControl x:Name="control1" ItemsSource="{Binding Some}" Stroke="{Binding Some[0].Color}">

This will bind the Stroke property to the Color property of the first MyModel object, assuming that the Some collection has an indexer.


问:
Pandas: str.contains using regex
I have dataframe and I need to filter that with regex.

Dataframe:

```<code>                  domain                    tag1
0         ^mail.ru/search                  Сервис
1             go.mail.ru$              Веб-портал
2           vk.com/audios              Социальное
3            vk.com/video              Социальное
4             vk.com/apps              Социальное
5                  vk.com              Социальное
6       ^yandex.ru/search                  Сервис
7       ^yandex.ru/pogoda                  Сервис
8             ^yandex.ru$              Веб-портал
</code>```

I need to get only domain

I try to use

```<code>def get_domain_encoding(df):
    return df[df.domain.str.contains(r'[a-zA-Z0-9-_]+.[a-zA-Z0-9]')]
</code>```

And it returns me

```<code>                   domain                    tag1
0         ^mail.ru/search                  Сервис
2           vk.com/audios              Социальное
3            vk.com/video              Социальное
4             vk.com/apps              Социальное
5                  vk.com              Социальное
6       ^yandex.ru/search                  Сервис
7       ^yandex.ru/pogoda                  Сервис
8             ^yandex.ru$              Веб-портал
</code>```

When I change it to

```<code>def get_domain_encoding(df):
    return df[df.domain.str.contains(r'^[a-zA-Z0-9-_]+.[a-zA-Z0-9]$')]
</code>```

It returns me empty dataframe.

How can I fix that?

答:
You can try this:

```<code>df.domain.str.extract('(\w+\.)?(\w+\.\w+)', expand=False)[1]
</code>```

Output:

```<code>0      mail.ru
1      mail.ru
2       vk.com
3       vk.com
4       vk.com
5       vk.com
6    yandex.ru
7    yandex.ru
8    yandex.ru
Name: 1, dtype: object
</code>```

Modify with a little cleanup, using named groups and discarding the 'subdomain' group:

```<code>df.domain.str.extract('(?P<subdomain>\w+\.)?(?P<domain>\w+\.\w+)',expand=False)['domain']
</code>```

Title: Pandas: str.contains using regex

Body:
I have dataframe and I need to filter that with regex.

Dataframe:

                  domain                    tag1
0         ^mail.ru/search                  Сервис
1             go.mail.ru$              Веб-портал
2           vk.com/audios              Социальное
3            vk.com/video              Социальное
4             vk.com/apps              Социальное
5                  vk.com              Социальное
6       ^yandex.ru/search                  Сервис
7       ^yandex.ru/pogoda                  Сервис
8             ^yandex.ru$              Веб-портал

I need to get only domain

I try to use

def get_domain_encoding(df):
    return df[df.domain.str.contains(r'[a-zA-Z0-9-_]+.[a-zA-Z0-9]')]

And it returns me

                   domain                    tag1
0         ^mail.ru/search                  Сервис
2           vk.com/audios              Социальное
3            vk.com/video              Социальное
4             vk.com/apps              Социальное
5                  vk.com              Социальное
6       ^yandex.ru/search                  Сервис
7       ^yandex.ru/pogoda                  Сервис
8             ^yandex.ru$              Веб-портал

When I change it to

def get_domain_encoding(df):
    return df[df.domain.str.contains(r'^[a-zA-Z0-9-_]+.[a-zA-Z0-9]$')]

It returns me empty dataframe.

How can I fix that?

Body:
You can try this:

df.domain.str.extract('(\w+\.)?(\w+\.\w+)', expand=False)[1]

Output:

0      mail.ru
1      mail.ru
2       vk.com
3       vk.com
4       vk.com
5       vk.com
6    yandex.ru
7    yandex.ru
8    yandex.ru
Name: 1, dtype: object

Modify with a little cleanup, using named groups and discarding the 'subdomain' group:

df.domain.str.extract('(?P<subdomain>\w+\.)?(?P<domain>\w+\.\w+)',expand=False)['domain']


问:
Defining a string function without arguments in python
I have defined this function without arguments

```<code># Define the function shout
def shout():
"""Print a string with three exclamation marks"""
# Concatenate the strings: shout_word
shout_word = str('congratulations')+ str('!!!')

# Print shout_word
print(shout_word)

# Call shout
shout(hello)
</code>```

I get error when calling the function, what could be the reason?
your assistance would be highly appreciated

答:
```<code># Define the function shout
def shout(word):  # Function shout() takes argument word
    print(str(word) + '!!!')  # Converting to str in case word should be an int

word = 'congratulations'
shout(word)  # Call function shout with variable word.
</code>```

With a second, n_exclamation mark argument to further explain how functions and arguments works:

```<code># Define the function shout
def shout(word, n_exclamation=3):  # Function shout() takes argument word and n_exclamation, here n_exclamation is set to 3 in case we do not pass it whne we call shout()
    print(str(word) + ('!' * n_exclamation))  # Converting to str in case word should be an int

word = 'congratulations'
shout(word, 1)  # Call function shout with variable word, print 1 exclamation marks (n_exclamation).
shout(word)  # Call function shout with variable word, will print 3 exclamation marks since we didn't pass any argument to that variable, the function is declared to have a default of 3 when that happens.
</code>```

Body:
I have defined this function without arguments

# Define the function shout
def shout():
"""Print a string with three exclamation marks"""
# Concatenate the strings: shout_word
shout_word = str('congratulations')+ str('!!!')

# Print shout_word
print(shout_word)

# Call shout
shout(hello)

I get error when calling the function, what could be the reason?
your assistance would be highly appreciated

Body:
# Define the function shout
def shout(word):  # Function shout() takes argument word
    print(str(word) + '!!!')  # Converting to str in case word should be an int

word = 'congratulations'
shout(word)  # Call function shout with variable word.

With a second, n_exclamation mark argument to further explain how functions and arguments works:

# Define the function shout
def shout(word, n_exclamation=3):  # Function shout() takes argument word and n_exclamation, here n_exclamation is set to 3 in case we do not pass it whne we call shout()
    print(str(word) + ('!' * n_exclamation))  # Converting to str in case word should be an int

word = 'congratulations'
shout(word, 1)  # Call function shout with variable word, print 1 exclamation marks (n_exclamation).
shout(word)  # Call function shout with variable word, will print 3 exclamation marks since we didn't pass any argument to that variable, the function is declared to have a default of 3 when that happens.


问:
Cannot define a class or member that utilizes 'dynamic' because the compiler required type 'System.Runtime.CompilerServices.DynamicAttribute' asp.net
I can't create any views without getting this error.

I've tried every fix on Stack Overflow, yet nothing works.

The model:

```<code> public class Project
{
    public string Name { get; set; }
    public int Id { get; set; }

}
</code>```

The Controller:

```<code> public class ProjectsController : Controller
{
    // GET: Projects
    public ActionResult Project()
    {
        var project = new Project() {Name = "Things" };

        return View();
    }
}
</code>```

When I go into the generated folder "Projects" and create a view I get this error:

Severity  Code    Description Project File    Line    Suppression State
  Error CS1980  Cannot define a class or member that utilizes 'dynamic'
  because the compiler required type
  'System.Runtime.CompilerServices.DynamicAttribute' cannot be found.
  Are you missing a
  reference?    WebApplication8 C:\Users\mitch\Documents\Visual Studio
  2017\Projects\WebApplication8\WebApplication8\Views\Projet.cshtml 1   Active

答:
It looks like some reference version is invalid or doesn't exist, try adding System.Dynamic.Runtime reference first.

Secondly,Check your .NET target version and make sure there is no dll you are referencing with higher version, and try closing the visual studio and rebuild after reopen.

Body:
I can't create any views without getting this error.

I've tried every fix on Stack Overflow, yet nothing works.

The model:

 public class Project
{
    public string Name { get; set; }
    public int Id { get; set; }

}

The Controller:

 public class ProjectsController : Controller
{
    // GET: Projects
    public ActionResult Project()
    {
        var project = new Project() {Name = "Things" };

        return View();
    }
}

When I go into the generated folder "Projects" and create a view I get this error:

Severity  Code    Description Project File    Line    Suppression State
  Error CS1980  Cannot define a class or member that utilizes 'dynamic'
  because the compiler required type
  'System.Runtime.CompilerServices.DynamicAttribute' cannot be found.
  Are you missing a
  reference?    WebApplication8 C:\Users\mitch\Documents\Visual Studio
  2017\Projects\WebApplication8\WebApplication8\Views\Projet.cshtml 1   Active


问:
ag-grid-react crashing on basic component import: missing react-dom-factories
When importing a basic component I have webpack crash on me. I'm unsure as to why this is happening but it seems to be a missing lib within the ag-grid-react package... Has anyone run into this before? Any advice would be much obliged!

```<code>import Table from './components/Table'
</code>```

When creating the Table component it compiles ok, but as soon as I import it as above, it crashes webpack.

// Table.js

import React, { Component } from "react";
import { AgGridReact } from "ag-grid-react";

class Table extends Component {
  constructor(props) {
    super(props);

    this.state = {
      columnDefs: this.createColumnDefs(),
      rowData: this.createRowData()
    };
  }

  onGridReady(params) {
    this.gridApi = params.api;
    this.columnApi = params.columnApi;

    this.gridApi.sizeColumnsToFit();
  }

  createColumnDefs() {
    return [
      { headerName: "Make", field: "make" },
      { headerName: "Model", field: "model" },
      { headerName: "Price", field: "price" }
    ];
  }

  createRowData() {
    return [
      { make: "Toyota", model: "Celica", price: 35000 },
      { make: "Ford", model: "Mondeo", price: 32000 },
      { make: "Porsche", model: "Boxter", price: 72000 }
    ];
  }

  render() {
    let containerStyle = {
      height: 115,
      width: 500
    };

    return (

Simple ag-Grid React Example

        <AgGridReact
          // properties
          columnDefs={this.state.columnDefs}
          rowData={this.state.rowData}
          // events
          onGridReady={this.onGridReady}
        />

    );
  }
}

export default Table;```

Webpack crashes with

./node_modules/ag-grid-react/lib/agGridReact.js
Module not found: Can't resolve 'react-dom-factories' in '/Users/username/Sites/site/node_modules/ag-grid-react/lib'

答:
With react-dom 15.5 (I think), react-dom-factories was moved to a separate module. ag-grid-react was updated to account for this and added react-dom-factories as a peer dependency in its package.json. You likely got a warning when installing ag-grid-react about missing the react-dom-factories dependency.

To resolve this, try running npm install react-dom-factories (or the yarn equivalent if you're using yarn).

Body:
When importing a basic component I have webpack crash on me. I'm unsure as to why this is happening but it seems to be a missing lib within the ag-grid-react package... Has anyone run into this before? Any advice would be much obliged!

import Table from './components/Table'

When creating the Table component it compiles ok, but as soon as I import it as above, it crashes webpack.

// Table.js

import React, { Component } from "react";
import { AgGridReact } from "ag-grid-react";

class Table extends Component {
  constructor(props) {
    super(props);

    this.state = {
      columnDefs: this.createColumnDefs(),
      rowData: this.createRowData()
    };
  }

  onGridReady(params) {
    this.gridApi = params.api;
    this.columnApi = params.columnApi;

    this.gridApi.sizeColumnsToFit();
  }

  createColumnDefs() {
    return [
      { headerName: "Make", field: "make" },
      { headerName: "Model", field: "model" },
      { headerName: "Price", field: "price" }
    ];
  }

  createRowData() {
    return [
      { make: "Toyota", model: "Celica", price: 35000 },
      { make: "Ford", model: "Mondeo", price: 32000 },
      { make: "Porsche", model: "Boxter", price: 72000 }
    ];
  }

  render() {
    let containerStyle = {
      height: 115,
      width: 500
    };

    return (

Simple ag-Grid React Example

        <AgGridReact
          // properties
          columnDefs={this.state.columnDefs}
          rowData={this.state.rowData}
          // events
          onGridReady={this.onGridReady}
        />

    );
  }
}

export default Table;

Webpack crashes with

./node_modules/ag-grid-react/lib/agGridReact.js
Module not found: Can't resolve 'react-dom-factories' in '/Users/username/Sites/site/node_modules/ag-grid-react/lib'


问:
Averaging of two images with mask
I have two image like this:

I create two mask, which show me position of each image on scene.

I create mask which show me intersection of two images.

I create intersection mask with
cv::bitwise_and(mask_left, mask_right, mask_intersection);

I want adding two images together. Where pixels of mask_intersection is white, I want use average value of pixels on both images. Here is result, where I just add one image on another. The problem is sharp border, which I want to solve with averaging of both images only on mask_intersection.

I don't know how to solve this problem the easiest way.

答: Te process you are loocking for is called blending, and you can achieve it using cv::addWeighted(), then just multiply the result by the mask to cut off zones of the image that you don´t want to blend.

Title: Averaging of two images with mask


问:
Count distinct id with case
So say I have a list IDs with values, like so:

```<code>ID  VALUE
1   A
1   NULL
1   B
2   NULL
3   A
</code>```

And I want to count distinct ID for values that equal A OR B (at least one)

The answer should be 2, since there are 2 IDs that have either A or B value.

If I do a COUNT(DISTINCT(CASE WHEN ... I'm unable to get the unique IDs.

Is there another solution?

答:
```<code>select count(distinct Id)
from tbl
where value in ('A','B')
</code>```

Title: Count distinct id with case

Body:
So say I have a list IDs with values, like so:

ID  VALUE
1   A
1   NULL
1   B
2   NULL
3   A

And I want to count distinct ID for values that equal A OR B (at least one)

The answer should be 2, since there are 2 IDs that have either A or B value.

If I do a COUNT(DISTINCT(CASE WHEN ... I'm unable to get the unique IDs.

Is there another solution?


问:
Java For Loop Unreachable Code
I have a for loop in my code that's giving an error on the entire loop itself, saying it's "unreachable code". I'm completely unsure about what's causing this with this loop:

```<code>public ArrayList<Double> Update(ArrayList<Double> addInputs)
{
// stores the resultant outputs from each layer

ArrayList<Double> outputs = null;

int cWeight = 0;

// first check that we have the correct amount of inputs

if (addInputs.size() != numInputs);
{
    // just return an empty vector if incorrect
    return outputs;
}

// For each layer....

for (int i = 0; i < numHiddenLayers + 1; ++i)
{
    if (i > 0)
    {
        addInputs = outputs;
    }

    outputs.clear();

    cWeight = 0;

    // for each neuron sum the (inputs * corresponding weights) .Throw

    // the total at our sigmoid function to get the output.

    for (int j = 0; j < neuronLayers.get(i).numNeurons; ++j)
    {
        double netinput = 0;

        int numberInputs = neuronLayers.get(i).listNeurons.get(j).numInputs;

    // for each weight

    for (int k = 0; k < numberInputs - 1; ++k)
    {
        // sum the weights x inputs

        netinput += neuronLayers.get(i).listNeurons.get(j).weights.get(k) *
                addInputs.get(cWeight++);
    }

    // add in the bias

    netinput += neuronLayers.get(i).listNeurons.get(j).weights.get(numberInputs - 1)
            *  dBias;

    // we can store the outputs from each layer as we generate them.

    // the combined activation is first filtered through the sigmoid

    //function

    outputs.add(sigmoid(netinput,dActivationResponse));
    }
}
</code>```

It's claiming the entire for loop after

```<code>// For each layer....
</code>```

is unreachable code. Any help would be greatly appreciated.

答:
It is saying because if condition terminates because of semicolon

So return will always execute which transfer control to the caller function skipping you rest of the code

Title: Java For Loop Unreachable Code

Body:
I have a for loop in my code that's giving an error on the entire loop itself, saying it's "unreachable code". I'm completely unsure about what's causing this with this loop:

public ArrayList<Double> Update(ArrayList<Double> addInputs)
{
// stores the resultant outputs from each layer

ArrayList<Double> outputs = null;

int cWeight = 0;

// first check that we have the correct amount of inputs

if (addInputs.size() != numInputs);
{
    // just return an empty vector if incorrect
    return outputs;
}

// For each layer....

for (int i = 0; i < numHiddenLayers + 1; ++i)
{
    if (i > 0)
    {
        addInputs = outputs;
    }

    outputs.clear();

    cWeight = 0;

    // for each neuron sum the (inputs * corresponding weights) .Throw

    // the total at our sigmoid function to get the output.

    for (int j = 0; j < neuronLayers.get(i).numNeurons; ++j)
    {
        double netinput = 0;

        int numberInputs = neuronLayers.get(i).listNeurons.get(j).numInputs;

    // for each weight

    for (int k = 0; k < numberInputs - 1; ++k)
    {
        // sum the weights x inputs

        netinput += neuronLayers.get(i).listNeurons.get(j).weights.get(k) *
                addInputs.get(cWeight++);
    }

    // add in the bias

    netinput += neuronLayers.get(i).listNeurons.get(j).weights.get(numberInputs - 1)
            *  dBias;

    // we can store the outputs from each layer as we generate them.

    // the combined activation is first filtered through the sigmoid

    //function

    outputs.add(sigmoid(netinput,dActivationResponse));
    }
}

It's claiming the entire for loop after

// For each layer....

is unreachable code. Any help would be greatly appreciated.


问:
Help with mercurial repo problem
I have a repo in a condition I don't understand.  2 weeks ago, I tagged a release to mark a particular point I may have needed to go back to.  Later, I decided to branch, and have also been pulling in changes from another repo (the repo that I originally cloned).

The original rev that is of interest is 52:

```<code>changeset:   52:5044a88ba2a9
date:        Mon Jan 10 18:09:30 2011 -0500
</code>```

A few commits later, I branched into "MultiPartition"  (I should have done this immediately, but I didn't anticipate needing it).

After some more work, I pull changes from the sister repo (all the changes do not conflict with my work in the branch, so it's safe).

Here's what I see now:

```<code>$ hg branches
MultiPartition                75:9fd803c56505
default                       72:3939850a77e2 (inactive)
</code>```

Where I'm working in MultiPartition, and default is the tip from the sister repo.

If I look at the heads:

```<code>$ hg heads
changeset:   75:9fd803c56505
branch:      MultiPartition
tag:         tip
date:        Tue Jan 18 18:32:38 2011 -0500

changeset:   72:3939850a77e2
parent:      69:997a5b43216d
date:        Tue Jan 18 13:26:48 2011 -0500

changeset:   54:4ad1d36a79aa
date:        Thu Jan 13 19:14:57 2011 -0500
</code>```

there's rev 54 hanging out there, which I didn't (knowingly) mean to leave behind.

Here's where it gets strange:  The changeset 52 isn't in my current MultiPartition tip (though it was actually in the source on my disk, as I expected).  I've attached a graphlog of the changesets at the bottom.

If I use the hgcontains extension, I see:

```<code>$ hg headscontaining 52
changeset:   75:9fd803c56505
branch:      MultiPartition
tag:         tip
date:        Tue Jan 18 18:32:38 2011 -0500
</code>```

which tells me that the contents of rev 52 (which has new files I want in the current branch) should be in the tip of this branch. However, an hg update -C MultiPartition removes the new files from the directory I want them in.

If I use hgtk log and filter by the directory of interest, I see the 52 changeset which adds the files, but no newer changesets have any files removed from this directory.

The only thing that makes me wonder is this:  Changeset 71 was the merge from the original repo.  In that repo, those new files don't exist.  The log for that changset is:

```<code>| o  changeset:   71:ba4c67a24185
|/|  branch:      MultiPartition
| |  parent:      70:2dcbf69c325d
| |  parent:      69:997a5b43216d
| |  date:        Mon Jan 17 17:55:10 2011 -0500
</code>```

Here's my core question:

If parent 70: has what I expected, but parent 69: didn't, how is that resolved?

How can I check for other omissions?  Is there a way to see this sort of behavior?

I want to not have multiple heads, but I can't seem to "merge" them.  Technically, they are already merged (I think).  How should I clean this up?

Sorry if this is complex, but I don't know how else to ask the question except for giving a ton of info.

Full graphlog:

```<code>o  changeset:   75:9fd803c56505
|  branch:      MultiPartition
|  tag:         tip
|  date:        Tue Jan 18 18:32:38 2011 -0500
|
o    changeset:   74:be7df4e2579c
|\   branch:      MultiPartition
| |  parent:      73:3e7ac80ab37a
| |  parent:      72:3939850a77e2
| |  date:        Tue Jan 18 18:31:24 2011 -0500
| |
| o  changeset:   73:3e7ac80ab37a
| |  branch:      MultiPartition
| |  parent:      71:ba4c67a24185
| |  date:        Tue Jan 18 18:28:51 2011 -0500
| |
o |  changeset:   72:3939850a77e2
| |  parent:      69:997a5b43216d
| |  date:        Tue Jan 18 13:26:48 2011 -0500
| |
| o  changeset:   71:ba4c67a24185
|/|  branch:      MultiPartition
| |  parent:      70:2dcbf69c325d
| |  parent:      69:997a5b43216d
| |  date:        Mon Jan 17 17:55:10 2011 -0500
| |
| o  changeset:   70:2dcbf69c325d
| |  branch:      MultiPartition
| |  parent:      66:79272b7e7c01
| |  date:        Mon Jan 17 17:42:04 2011 -0500
| |
o |  changeset:   69:997a5b43216d
| |  date:        Mon Jan 17 12:00:09 2011 -0500
| |
o |  changeset:   68:b39f8a7af0c5
| |  date:        Sun Jan 16 20:23:43 2011 -0500
| |
o |  changeset:   67:63d3b40427e0
| |  parent:      58:29029a74e351
| |  date:        Sun Jan 16 18:07:49 2011 -0500
| |
| o  changeset:   66:79272b7e7c01
| |  branch:      MultiPartition
| |  date:        Mon Jan 17 09:43:32 2011 -0500
| |
| o  changeset:   65:b33eb978d647
| |  branch:      MultiPartition
| |  date:        Mon Jan 17 09:39:54 2011 -0500
| |
| o  changeset:   64:1fdafb6d0e84
| |  branch:      MultiPartition
| |  date:        Sun Jan 16 17:48:09 2011 -0500
| |
| o  changeset:   63:74942ab5113d
| |  branch:      MultiPartition
| |  date:        Sun Jan 16 17:46:15 2011 -0500
| |
| o  changeset:   62:2cd5a6d9d120
| |  branch:      MultiPartition
| |  date:        Sun Jan 16 01:55:23 2011 -0500
| |
| o  changeset:   61:acc73e7a35fc
|/|  branch:      MultiPartition
| |  parent:      60:c10e217081f0
| |  parent:      58:29029a74e351
| |  date:        Sun Jan 16 01:53:01 2011 -0500
| |
| o  changeset:   60:c10e217081f0
| |  branch:      MultiPartition
| |  date:        Sun Jan 16 01:45:16 2011 -0500
| |
| o  changeset:   59:2709b82b3ac0
| |  branch:      MultiPartition
| |  parent:      54:4ad1d36a79aa
| |  date:        Sun Jan 16 01:42:34 2011 -0500
| |
o |  changeset:   58:29029a74e351
| |  date:        Sun Jan 16 01:36:44 2011 -0500
| |
o |  changeset:   57:48840b75e37b
| |  date:        Fri Jan 14 11:04:06 2011 -0500
| |
o |  changeset:   56:dab5f0d40be9
| |  date:        Thu Jan 13 15:51:11 2011 -0500
| |
o |  changeset:   55:214ac45834fd
| |  parent:      51:7d0a1da31199
| |  date:        Wed Jan 12 16:49:00 2011 -0500
| |
| @  changeset:   54:4ad1d36a79aa
| |  date:        Thu Jan 13 19:14:57 2011 -0500
| |
| o  changeset:   53:8f06d69177d6
| |  date:        Thu Jan 13 14:02:42 2011 -0500
| |
| o  changeset:   52:5044a88ba2a9
|    date:        Mon Jan 10 18:09:30 2011 -0500
|
o
</code>```

答:
You actually still have two heads on the default branch, and one head on the MultiPartition branch, as hg heads has shown you.  Use hg heads -t to see actual heads, regardless of branch.  It looks like you use the graphlog extension, so use hg glog -r "branch(default)" to visualize your default branch.

As for your questions:

If parent 70: has what I expected, but parent 69: didn't, how is that resolved?

You can hg export -r 52 >52.patch then hg import 52.patch at the tip.  This will reapply the changes.  One of your merges must have dropped the content.

How can I check for other omissions? Is there a way to see this sort of behavior?

Not really.  As far as Mercurial is concerned 52 is an ancestor of your tip.  If the changes were dropped in a later changeset Mercurial doesn't really know.  You can hg diff two different changesets and track down where it got removed (probably in the merge).

I want to not have multiple heads, but I can't seem to "merge" them. Technically, they are already merged (I think). How should I clean this up?

default is typically where you want all your development to end up.  You can merge the two default heads, then hg ci --closebranch on MultiPartition and merge it into default.

Title: Help with mercurial repo problem

Body:
I have a repo in a condition I don't understand.  2 weeks ago, I tagged a release to mark a particular point I may have needed to go back to.  Later, I decided to branch, and have also been pulling in changes from another repo (the repo that I originally cloned).

The original rev that is of interest is 52:

changeset:   52:5044a88ba2a9
date:        Mon Jan 10 18:09:30 2011 -0500

A few commits later, I branched into "MultiPartition"  (I should have done this immediately, but I didn't anticipate needing it).

After some more work, I pull changes from the sister repo (all the changes do not conflict with my work in the branch, so it's safe).

Here's what I see now:

$ hg branches
MultiPartition                75:9fd803c56505
default                       72:3939850a77e2 (inactive)

Where I'm working in MultiPartition, and default is the tip from the sister repo.

If I look at the heads:

$ hg heads
changeset:   75:9fd803c56505
branch:      MultiPartition
tag:         tip
date:        Tue Jan 18 18:32:38 2011 -0500

changeset:   72:3939850a77e2
parent:      69:997a5b43216d
date:        Tue Jan 18 13:26:48 2011 -0500

changeset:   54:4ad1d36a79aa
date:        Thu Jan 13 19:14:57 2011 -0500

there's rev 54 hanging out there, which I didn't (knowingly) mean to leave behind.

Here's where it gets strange:  The changeset 52 isn't in my current MultiPartition tip (though it was actually in the source on my disk, as I expected).  I've attached a graphlog of the changesets at the bottom.

If I use the hgcontains extension, I see:

$ hg headscontaining 52
changeset:   75:9fd803c56505
branch:      MultiPartition
tag:         tip
date:        Tue Jan 18 18:32:38 2011 -0500

which tells me that the contents of rev 52 (which has new files I want in the current branch) should be in the tip of this branch. However, an hg update -C MultiPartition removes the new files from the directory I want them in.

If I use hgtk log and filter by the directory of interest, I see the 52 changeset which adds the files, but no newer changesets have any files removed from this directory.

The only thing that makes me wonder is this:  Changeset 71 was the merge from the original repo.  In that repo, those new files don't exist.  The log for that changset is:

| o  changeset:   71:ba4c67a24185
|/|  branch:      MultiPartition
| |  parent:      70:2dcbf69c325d
| |  parent:      69:997a5b43216d
| |  date:        Mon Jan 17 17:55:10 2011 -0500

Here's my core question:

If parent 70: has what I expected, but parent 69: didn't, how is that resolved?

How can I check for other omissions?  Is there a way to see this sort of behavior?

I want to not have multiple heads, but I can't seem to "merge" them.  Technically, they are already merged (I think).  How should I clean this up?

Sorry if this is complex, but I don't know how else to ask the question except for giving a ton of info.

Full graphlog:

o  changeset:   75:9fd803c56505
|  branch:      MultiPartition
|  tag:         tip
|  date:        Tue Jan 18 18:32:38 2011 -0500
|
o    changeset:   74:be7df4e2579c
|\   branch:      MultiPartition
| |  parent:      73:3e7ac80ab37a
| |  parent:      72:3939850a77e2
| |  date:        Tue Jan 18 18:31:24 2011 -0500
| |
| o  changeset:   73:3e7ac80ab37a
| |  branch:      MultiPartition
| |  parent:      71:ba4c67a24185
| |  date:        Tue Jan 18 18:28:51 2011 -0500
| |
o |  changeset:   72:3939850a77e2
| |  parent:      69:997a5b43216d
| |  date:        Tue Jan 18 13:26:48 2011 -0500
| |
| o  changeset:   71:ba4c67a24185
|/|  branch:      MultiPartition
| |  parent:      70:2dcbf69c325d
| |  parent:      69:997a5b43216d
| |  date:        Mon Jan 17 17:55:10 2011 -0500
| |
| o  changeset:   70:2dcbf69c325d
| |  branch:      MultiPartition
| |  parent:      66:79272b7e7c01
| |  date:        Mon Jan 17 17:42:04 2011 -0500
| |
o |  changeset:   69:997a5b43216d
| |  date:        Mon Jan 17 12:00:09 2011 -0500
| |
o |  changeset:   68:b39f8a7af0c5
| |  date:        Sun Jan 16 20:23:43 2011 -0500
| |
o |  changeset:   67:63d3b40427e0
| |  parent:      58:29029a74e351
| |  date:        Sun Jan 16 18:07:49 2011 -0500
| |
| o  changeset:   66:79272b7e7c01
| |  branch:      MultiPartition
| |  date:        Mon Jan 17 09:43:32 2011 -0500
| |
| o  changeset:   65:b33eb978d647
| |  branch:      MultiPartition
| |  date:        Mon Jan 17 09:39:54 2011 -0500
| |
| o  changeset:   64:1fdafb6d0e84
| |  branch:      MultiPartition
| |  date:        Sun Jan 16 17:48:09 2011 -0500
| |
| o  changeset:   63:74942ab5113d
| |  branch:      MultiPartition
| |  date:        Sun Jan 16 17:46:15 2011 -0500
| |
| o  changeset:   62:2cd5a6d9d120
| |  branch:      MultiPartition
| |  date:        Sun Jan 16 01:55:23 2011 -0500
| |
| o  changeset:   61:acc73e7a35fc
|/|  branch:      MultiPartition
| |  parent:      60:c10e217081f0
| |  parent:      58:29029a74e351
| |  date:        Sun Jan 16 01:53:01 2011 -0500
| |
| o  changeset:   60:c10e217081f0
| |  branch:      MultiPartition
| |  date:        Sun Jan 16 01:45:16 2011 -0500
| |
| o  changeset:   59:2709b82b3ac0
| |  branch:      MultiPartition
| |  parent:      54:4ad1d36a79aa
| |  date:        Sun Jan 16 01:42:34 2011 -0500
| |
o |  changeset:   58:29029a74e351
| |  date:        Sun Jan 16 01:36:44 2011 -0500
| |
o |  changeset:   57:48840b75e37b
| |  date:        Fri Jan 14 11:04:06 2011 -0500
| |
o |  changeset:   56:dab5f0d40be9
| |  date:        Thu Jan 13 15:51:11 2011 -0500
| |
o |  changeset:   55:214ac45834fd
| |  parent:      51:7d0a1da31199
| |  date:        Wed Jan 12 16:49:00 2011 -0500
| |
| @  changeset:   54:4ad1d36a79aa
| |  date:        Thu Jan 13 19:14:57 2011 -0500
| |
| o  changeset:   53:8f06d69177d6
| |  date:        Thu Jan 13 14:02:42 2011 -0500
| |
| o  changeset:   52:5044a88ba2a9
|    date:        Mon Jan 10 18:09:30 2011 -0500
|
o

ContentLicense: CC BY-SA 2.5


问:
use GAN to generator mnist,but study nothing
Recently,I am studying the GAN network,I'm using it to generator a mnisit image,the environment in my computer is ubuntu16.04,tensorflow,python3.

The code can run without any error.But the result shows the network study nothing,through training,the output image is still noisy image.

Firstly I design a generator network:the input is 784 dimension's noisy data,through a hidden layer and rule it,generate a 784 dimension's image.

Then I design a discriminator network:the input is real image and fake image,through a hidden layer and rule it,the output is 1 dimension's logits.

Then I defined the generator_loss and discriminator_loss, then train generator and discriminator.It can run,but the result show the network study nothing, the loss can not convergence.

```<code>import tensorflow as tf
import numpy as np
import tensorflow.contrib.slim as slim
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("/home/zyw/data/tensor_mnist-master/MNIST_data/",one_hot=True)
batch_size = 100

G_in = tf.placeholder(tf.float32,[None,784])
G_h1 = tf.layers.dense(G_in, 128)
G_h1 = tf.maximum(0.01 * G_h1, G_h1)
G_out = tf.tanh(tf.layers.dense(G_h1, 784))

real = tf.placeholder(tf.float32,[None,784])
Dl0 = tf.layers.dense(G_out, 128)
Dl0 = tf.maximum(0.01 * Dl0, Dl0)
p0 = tf.layers.dense(Dl0, 1)

Dl1 = tf.layers.dense(real, 128)
Dl1 = tf.maximum(0.01 * Dl1, Dl1)
p1 = tf.layers.dense(Dl1, 1)

G_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits =p0,labels=tf.ones_like(p0)*0.9))
D_real_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits =p1,labels=tf.ones_like(p1)*0.9))
D_fake_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits =p0,labels=tf.zeros_like(p0)))
D_total_loss = tf.add(D_fake_loss,D_real_loss)

G_train = tf.train.AdamOptimizer(0.01).minimize(G_loss)
D_train = tf.train.AdamOptimizer(0.01).minimize(D_total_loss)

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)

    for i in range(1000):
        mnist_data,_ = mnist.train.next_batch(batch_size)

        # noise_org = tf.random_normal([batch_size,784],stddev = 0.1,dtype = tf.float32)
        noise_org = np.random.randn(batch_size, 784)
        a,b,dloss=  sess.run([D_real_loss,D_fake_loss,D_total_loss,G_train,D_train],feed_dict={G_in:noise_org,real:mnist_data})[:3]
        if i%100==0:
            print(a,b,dloss)
    #test_generative_image
    noise_org = np.random.randn(1, 784)
    image = sess.run(G_out,feed_dict ={G_in:noise_org})
    outimage = tf.reshape(image, [28,28])
    plt.imshow(outimage.eval(),cmap='gray')
    plt.show()
    print('ok')
</code>```

the result is:

```<code>0.80509 0.63548 1.44057
0.33512 0.20223 0.53735
0.332536 0.97737 1.30991
0.328048 0.814452 1.1425
0.326688 0.411907 0.738596
0.325864 0.570807 0.896671
0.325575 0.970406 1.29598
0.325421 1.02487 1.35029
0.325222 1.34089 1.66612
0.325217 0.747129 1.07235
</code>```

答:
I have added the modified code with the comments where I made the changes. Moreover, I have described about my changes below.

```<code>import tensorflow as tf
import numpy as np
import tensorflow.contrib.slim as slim
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("/home/zyw/data/tensor_mnist-master/MNIST_data/",one_hot=True)

batch_size = 100

#define the generator function
def generator(input):
    G_h1 = tf.layers.dense(input, 128)
    # G_h1 = tf.maximum(0.01 * G_h1, G_h1)
    G_out = tf.sigmoid(tf.layers.dense(G_h1, 784))  # sigmoid function added
    return G_out

#Define the discrminator function
def discriminator(input):
    Dl0 = tf.layers.dense(input, 128)
    # Dl0 = tf.maximum(0.01 * Dl0, Dl0)
    p0 = tf.layers.dense(Dl0, 1)
    return p0

#Generator
with tf.variable_scope('G'):
    G_in = tf.placeholder(tf.float32, [None, 784])
    G_out = generator(G_in)

real = tf.placeholder(tf.float32, [None, 784])

#Discrimnator that takes the real data
with tf.variable_scope('D'):
    D1 = discriminator(real)

#Discriminator that takes fake data
with tf.variable_scope('D', reuse=True):  # need to use the same copy of Discrminator
    D2 = discriminator(G_out)

G_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=D2, labels=tf.ones_like(D2)))
D_real_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=D1, labels=tf.ones_like(D1)))
D_fake_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=D2, labels=tf.zeros_like(D2)))
D_total_loss = tf.add(D_fake_loss, D_real_loss)

vars = tf.trainable_variables() #all trainable variables
d_training_vars = [v for v in vars if v.name.startswith('D/')]  # varibles associated with the discrminator
g_training_vars = [v for v in vars if v.name.startswith('G/')]  # varibles associated with the generator

G_train = tf.train.AdamOptimizer(0.001).minimize(G_loss,var_list=g_training_vars)  # only train the variables associated with the generator
D_train = tf.train.AdamOptimizer(0.001).minimize(D_total_loss,var_list=d_training_vars)  # only train the variables associated with the discriminator

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)

    for i in range(1000):
        mnist_data, _ = mnist.train.next_batch(batch_size)
        # noise_org = tf.random_normal([batch_size,784],stddev = 0.1,dtype = tf.float32)
        noise_org = np.random.randn(batch_size, 784)

        a, b, dloss = sess.run([D_real_loss, D_fake_loss, D_total_loss, G_train, D_train],feed_dict={G_in: noise_org, real: mnist_data})[:3]
        if i % 100 == 0:
            print(a, b, dloss)

    # test_generative_image
    noise_org = np.random.randn(1, 784)
    image = sess.run(G_out, feed_dict={G_in: noise_org})
    outimage = tf.reshape(image, [28, 28])

    plt.imshow(outimage.eval(), cmap='gray')
    plt.show()
    print('ok')
</code>```

Few points you should note when implementing a GAN,

Need to use the same copies of the discriminator (i.e share same
weights) when implementing the discriminator loss (in your case Dl0
and Dl1 should share same paraments).

Generator activation function should be sigmoid not tanh
since the output of the generator should only be varying between 0
and 1. (since its a image)

When training the discriminator, you should only train the variables that associated with the discriminator. Likewise, when training the generator you only should train the variables that associated with the generator.

Sometimes it is important to make sure that the discriminator is
more powerful than the generator, as otherwise, it would not have
sufficient capacity to learn to be able to distinguish accurately
between generated and real samples.

These are only the basic things of GANs that you should note. However, there are many other aspects that you should consider when developing a GAN. You can get a good basic idea of GANs by reading following two articles.

http://blog.aylien.com/introduction-generative-adversarial-networks-code-tensorflow/

http://blog.evjang.com/2016/06/generative-adversarial-nets-in.html

Hope this helps.

Body:
Recently,I am studying the GAN network,I'm using it to generator a mnisit image,the environment in my computer is ubuntu16.04,tensorflow,python3.

The code can run without any error.But the result shows the network study nothing,through training,the output image is still noisy image.

Firstly I design a generator network:the input is 784 dimension's noisy data,through a hidden layer and rule it,generate a 784 dimension's image.

Then I design a discriminator network:the input is real image and fake image,through a hidden layer and rule it,the output is 1 dimension's logits.

Then I defined the generator_loss and discriminator_loss, then train generator and discriminator.It can run,but the result show the network study nothing, the loss can not convergence.

import tensorflow as tf
import numpy as np
import tensorflow.contrib.slim as slim
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("/home/zyw/data/tensor_mnist-master/MNIST_data/",one_hot=True)
batch_size = 100

G_in = tf.placeholder(tf.float32,[None,784])
G_h1 = tf.layers.dense(G_in, 128)
G_h1 = tf.maximum(0.01 * G_h1, G_h1)
G_out = tf.tanh(tf.layers.dense(G_h1, 784))

real = tf.placeholder(tf.float32,[None,784])
Dl0 = tf.layers.dense(G_out, 128)
Dl0 = tf.maximum(0.01 * Dl0, Dl0)
p0 = tf.layers.dense(Dl0, 1)

Dl1 = tf.layers.dense(real, 128)
Dl1 = tf.maximum(0.01 * Dl1, Dl1)
p1 = tf.layers.dense(Dl1, 1)

G_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits =p0,labels=tf.ones_like(p0)*0.9))
D_real_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits =p1,labels=tf.ones_like(p1)*0.9))
D_fake_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits =p0,labels=tf.zeros_like(p0)))
D_total_loss = tf.add(D_fake_loss,D_real_loss)

G_train = tf.train.AdamOptimizer(0.01).minimize(G_loss)
D_train = tf.train.AdamOptimizer(0.01).minimize(D_total_loss)

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)

    for i in range(1000):
        mnist_data,_ = mnist.train.next_batch(batch_size)

        # noise_org = tf.random_normal([batch_size,784],stddev = 0.1,dtype = tf.float32)
        noise_org = np.random.randn(batch_size, 784)
        a,b,dloss=  sess.run([D_real_loss,D_fake_loss,D_total_loss,G_train,D_train],feed_dict={G_in:noise_org,real:mnist_data})[:3]
        if i%100==0:
            print(a,b,dloss)
    #test_generative_image
    noise_org = np.random.randn(1, 784)
    image = sess.run(G_out,feed_dict ={G_in:noise_org})
    outimage = tf.reshape(image, [28,28])
    plt.imshow(outimage.eval(),cmap='gray')
    plt.show()
    print('ok')

the result is:

0.80509 0.63548 1.44057
0.33512 0.20223 0.53735
0.332536 0.97737 1.30991
0.328048 0.814452 1.1425
0.326688 0.411907 0.738596
0.325864 0.570807 0.896671
0.325575 0.970406 1.29598
0.325421 1.02487 1.35029
0.325222 1.34089 1.66612
0.325217 0.747129 1.07235

Body:
I have added the modified code with the comments where I made the changes. Moreover, I have described about my changes below.

import tensorflow as tf
import numpy as np
import tensorflow.contrib.slim as slim
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("/home/zyw/data/tensor_mnist-master/MNIST_data/",one_hot=True)

batch_size = 100

#define the generator function
def generator(input):
    G_h1 = tf.layers.dense(input, 128)
    # G_h1 = tf.maximum(0.01 * G_h1, G_h1)
    G_out = tf.sigmoid(tf.layers.dense(G_h1, 784))  # sigmoid function added
    return G_out

#Define the discrminator function
def discriminator(input):
    Dl0 = tf.layers.dense(input, 128)
    # Dl0 = tf.maximum(0.01 * Dl0, Dl0)
    p0 = tf.layers.dense(Dl0, 1)
    return p0

#Generator
with tf.variable_scope('G'):
    G_in = tf.placeholder(tf.float32, [None, 784])
    G_out = generator(G_in)

real = tf.placeholder(tf.float32, [None, 784])

#Discrimnator that takes the real data
with tf.variable_scope('D'):
    D1 = discriminator(real)

#Discriminator that takes fake data
with tf.variable_scope('D', reuse=True):  # need to use the same copy of Discrminator
    D2 = discriminator(G_out)

G_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=D2, labels=tf.ones_like(D2)))
D_real_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=D1, labels=tf.ones_like(D1)))
D_fake_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=D2, labels=tf.zeros_like(D2)))
D_total_loss = tf.add(D_fake_loss, D_real_loss)

vars = tf.trainable_variables() #all trainable variables
d_training_vars = [v for v in vars if v.name.startswith('D/')]  # varibles associated with the discrminator
g_training_vars = [v for v in vars if v.name.startswith('G/')]  # varibles associated with the generator

G_train = tf.train.AdamOptimizer(0.001).minimize(G_loss,var_list=g_training_vars)  # only train the variables associated with the generator
D_train = tf.train.AdamOptimizer(0.001).minimize(D_total_loss,var_list=d_training_vars)  # only train the variables associated with the discriminator

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)

    for i in range(1000):
        mnist_data, _ = mnist.train.next_batch(batch_size)
        # noise_org = tf.random_normal([batch_size,784],stddev = 0.1,dtype = tf.float32)
        noise_org = np.random.randn(batch_size, 784)

        a, b, dloss = sess.run([D_real_loss, D_fake_loss, D_total_loss, G_train, D_train],feed_dict={G_in: noise_org, real: mnist_data})[:3]
        if i % 100 == 0:
            print(a, b, dloss)

    # test_generative_image
    noise_org = np.random.randn(1, 784)
    image = sess.run(G_out, feed_dict={G_in: noise_org})
    outimage = tf.reshape(image, [28, 28])

    plt.imshow(outimage.eval(), cmap='gray')
    plt.show()
    print('ok')

Few points you should note when implementing a GAN,

Need to use the same copies of the discriminator (i.e share same
weights) when implementing the discriminator loss (in your case Dl0
and Dl1 should share same paraments).

Generator activation function should be sigmoid not tanh
since the output of the generator should only be varying between 0
and 1. (since its a image)

When training the discriminator, you should only train the variables that associated with the discriminator. Likewise, when training the generator you only should train the variables that associated with the generator.

Sometimes it is important to make sure that the discriminator is
more powerful than the generator, as otherwise, it would not have
sufficient capacity to learn to be able to distinguish accurately
between generated and real samples.

These are only the basic things of GANs that you should note. However, there are many other aspects that you should consider when developing a GAN. You can get a good basic idea of GANs by reading following two articles.

http://blog.aylien.com/introduction-generative-adversarial-networks-code-tensorflow/

http://blog.evjang.com/2016/06/generative-adversarial-nets-in.html

Hope this helps.


问:
: File has already been moved - cannot be transferred again in spring mvc while upload image
I read many solution on google and also on this site for this problem but nothing helpfull.
i am trying to upload image in spring mvc project dir \webapp\assets\images and also to server by using randomUUID and get the above  error.
pls someone help me

Here is my bean

```<code>@Entity
@Table(name="documentsww")
public class Document {

    @Id
    @GeneratedValue
    @Column(name="id")
    private Integer id;
    public Document(){

        this.code="DOC"+UUID.randomUUID().toString().substring(26).toUpperCase();
        this.code="DOC"+UUID.randomUUID().toString().substring(26).toUpperCase();

    }
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Column(name="name")
    private String name;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }
     @Column
    private String code;
    @Column(name="description")
    private String description;
    @Column(name="content")
    @Transient
    private MultipartFile  file;

    public MultipartFile getFile() {
        return file;
    }

    public void setFile(MultipartFile file) {
        this.file = file;
    }

    }
</code>```

and Controller is

```<code>@Controller
public class ImageCoontroller {

    @Autowired
    DocumentDao documentDao;
    @RequestMapping(value="/")
    public String getpage() {

        return "register";
    }

    @RequestMapping(value="/it")
    public String save(
            @ModelAttribute("document") Document document,HttpServletRequest request) {
        System.out.println("the values are  Description is  Code is ");
  documentDao.save(document);
    if(!document.getFile().getOriginalFilename().equals("")){
        ImageUtill.uploadfile(request,document.getFile(),document.getCode());

    }

        return "register";
    }

}
</code>```

the imageUtill class

```<code>public class ImageUtill {

    private static final String ABS_PATH="C:\\Users\\Junaid\\Documents\\workspace-sts-3.9.0.RELEASE\\Uplaod\\src\\main\\webapp\\assets\\images";
    private static String REAL_PATH="";
    public static void uploadfile(HttpServletRequest request, MultipartFile file, String code) {
    Logger loger=LoggerFactory.getLogger(ImageUtill.class);
        REAL_PATH=request.getSession().getServletContext().getRealPath("/assets/images/");
        loger.info(ABS_PATH);
        loger.info(REAL_PATH);
        System.out.println(REAL_PATH);
        System.out.println(ABS_PATH);
        // TODO Auto-generated method stub
        if(!new File(ABS_PATH).exists()){
            new File(ABS_PATH).mkdirs();

        }
        if(!new File(REAL_PATH).exists()){
            new File(REAL_PATH).mkdirs();
        //  F:\SpringProjects\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Image\WEB-INF\images
            //F:\SpringProjects\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Image\WEB_INF\images

        }
        try {
        //

            file.transferTo(new File(REAL_PATH+code+".jpg"));
            file.transferTo(new File(ABS_PATH+code+".jpg"));
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            System.out.println(e);
        }

    }

}
</code>```

答:
You can't use MultipartFile#transferTo method twice, second call of transferTo method should be replaced with a logic of file copying. You can use this method to copy files.

Almost pseudocode:

```<code>String firstFilePath = REAL_PATH+code+".jpg";
String secondFilePath = ABS_PATH+code+".jpg";
file.transferTo(new File(firstFilePath));
Files.copy(Paths.get(firstFilePath), Paths.get(secondFilePath));
</code>```

Body:
I read many solution on google and also on this site for this problem but nothing helpfull.
i am trying to upload image in spring mvc project dir \webapp\assets\images and also to server by using randomUUID and get the above  error.
pls someone help me

Here is my bean

@Entity
@Table(name="documentsww")
public class Document {

    @Id
    @GeneratedValue
    @Column(name="id")
    private Integer id;
    public Document(){

        this.code="DOC"+UUID.randomUUID().toString().substring(26).toUpperCase();
        this.code="DOC"+UUID.randomUUID().toString().substring(26).toUpperCase();

    }
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Column(name="name")
    private String name;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }
     @Column
    private String code;
    @Column(name="description")
    private String description;
    @Column(name="content")
    @Transient
    private MultipartFile  file;

    public MultipartFile getFile() {
        return file;
    }

    public void setFile(MultipartFile file) {
        this.file = file;
    }

    }

and Controller is

@Controller
public class ImageCoontroller {

    @Autowired
    DocumentDao documentDao;
    @RequestMapping(value="/")
    public String getpage() {

        return "register";
    }

    @RequestMapping(value="/it")
    public String save(
            @ModelAttribute("document") Document document,HttpServletRequest request) {
        System.out.println("the values are  Description is  Code is ");
  documentDao.save(document);
    if(!document.getFile().getOriginalFilename().equals("")){
        ImageUtill.uploadfile(request,document.getFile(),document.getCode());

    }

        return "register";
    }

}

the imageUtill class

public class ImageUtill {

    private static final String ABS_PATH="C:\\Users\\Junaid\\Documents\\workspace-sts-3.9.0.RELEASE\\Uplaod\\src\\main\\webapp\\assets\\images";
    private static String REAL_PATH="";
    public static void uploadfile(HttpServletRequest request, MultipartFile file, String code) {
    Logger loger=LoggerFactory.getLogger(ImageUtill.class);
        REAL_PATH=request.getSession().getServletContext().getRealPath("/assets/images/");
        loger.info(ABS_PATH);
        loger.info(REAL_PATH);
        System.out.println(REAL_PATH);
        System.out.println(ABS_PATH);
        // TODO Auto-generated method stub
        if(!new File(ABS_PATH).exists()){
            new File(ABS_PATH).mkdirs();

        }
        if(!new File(REAL_PATH).exists()){
            new File(REAL_PATH).mkdirs();
        //  F:\SpringProjects\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Image\WEB-INF\images
            //F:\SpringProjects\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Image\WEB_INF\images

        }
        try {
        //

            file.transferTo(new File(REAL_PATH+code+".jpg"));
            file.transferTo(new File(ABS_PATH+code+".jpg"));
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            System.out.println(e);
        }

    }

}

Body:
You can't use MultipartFile#transferTo method twice, second call of transferTo method should be replaced with a logic of file copying. You can use this method to copy files.

Almost pseudocode:

String firstFilePath = REAL_PATH+code+".jpg";
String secondFilePath = ABS_PATH+code+".jpg";
file.transferTo(new File(firstFilePath));
Files.copy(Paths.get(firstFilePath), Paths.get(secondFilePath));


问:
Two pseudo elements ::before with different properties
Used two pseudo elements ::before with different border properties (see js fiddle). Despite "you can use only one ::before and one ::after pseudo element" this actualy worked. Why?

https://jsfiddle.net/8L7zou3e/1/

```<code>.el {
    position: relative;
    margin: 100px 0 0 500px;
    width: 300px;
    height: 100px;
    background-color: #AA4343;
}
.el:before {
    content: '';
    display: inline-block;
    width: 0;
    height: 0;
    border-top: 50px solid #e86d0a;
    border-left: 50px solid transparent;
    position: absolute;
    top: 0;
    left: -50px;
}

.el:before {
    content: '';
    display: inline-block;
    width: 0;
    height: 0;
    border-bottom: 50px solid #e86d0a;
    border-left: 50px solid transparent;
    position: absolute;
    top: 0px;
    left: -50px;
}
</code>```

答:
There's only one pseudo-element but the properties are added because the two rules apply to that pseudo-element.

Your CSS is equivalent to

```<code>.el {
    position: relative;
    margin: 100px 0 0 500px;
    width: 300px;
    height: 100px;
    background-color: #AA4343;
}
.el:before {
    content: '';
    display: inline-block;
    width: 0;
    height: 0;
    border-top: 50px solid #e86d0a;
    border-left: 50px solid transparent;
    position: absolute;
    border-bottom: 50px solid #e86d0a;
    border-left: 50px solid transparent;
    top: 0;
    left: -50px;
}
</code>```

It's similar to this case which probably is more obvious:

```<code>a {
   color: red;
}
a {
   font-weight: bold;
}
</code>```

Body:
Used two pseudo elements ::before with different border properties (see js fiddle). Despite "you can use only one ::before and one ::after pseudo element" this actualy worked. Why?

https://jsfiddle.net/8L7zou3e/1/

.el {
    position: relative;
    margin: 100px 0 0 500px;
    width: 300px;
    height: 100px;
    background-color: #AA4343;
}
.el:before {
    content: '';
    display: inline-block;
    width: 0;
    height: 0;
    border-top: 50px solid #e86d0a;
    border-left: 50px solid transparent;
    position: absolute;
    top: 0;
    left: -50px;
}

.el:before {
    content: '';
    display: inline-block;
    width: 0;
    height: 0;
    border-bottom: 50px solid #e86d0a;
    border-left: 50px solid transparent;
    position: absolute;
    top: 0px;
    left: -50px;
}

Body:
There's only one pseudo-element but the properties are added because the two rules apply to that pseudo-element.

Your CSS is equivalent to

.el {
    position: relative;
    margin: 100px 0 0 500px;
    width: 300px;
    height: 100px;
    background-color: #AA4343;
}
.el:before {
    content: '';
    display: inline-block;
    width: 0;
    height: 0;
    border-top: 50px solid #e86d0a;
    border-left: 50px solid transparent;
    position: absolute;
    border-bottom: 50px solid #e86d0a;
    border-left: 50px solid transparent;
    top: 0;
    left: -50px;
}

It's similar to this case which probably is more obvious:

a {
   color: red;
}
a {
   font-weight: bold;
}


问:
javascript debugging gets into VM**** file how to blackbox these files?
When debugging JS using chrome development tool, while using step into next function(ctrl + ;). I'm getting into file names like VM****.   Is there a way to get rid of this?</p>

答: I know this is a rather old subject, but I had the same issue and noticed if I used an Incognito Chrome instance, the VMXXXX scripts no longer show up during the trace when I did an Event Listener Breakpoint (was debugging click). If this helps anyone.</p>


问:
Seamless FRAME/IFRAMEs (with reasonable scrollbars)?
Summary:

I'd like to display a shopping cart from another domain underneath my fixed content in my page - and have the scrollbars come out properly.

Details:

I need to display a shopping cart from a vendor within a page on "my" site with "my" header on top.  (Eventually the shopping will all be in a subdomain but not now, sigh.)  The header is a fixed height.  The shopping cart pages vary in height as you navigate within that frame.

I've tried frames and iframes and had cross-browser issues with the iframes.  I'm only testing four configurations, Windows/IE, Windows/Firefox, Mac/Safari and Mac/Firefox.

Right now I am using a frameset with two frames, one containing my fixed-height header page, the other containing the external page.  This does work - the one issue is that when a scrollbar appears it (of course) only appears on the bottom frame.

This will do and the client isn't very sophisticated but it bugs me.

If I use IFRAMES, I find I need to sprinkle height: 100% and overflow-y: auto in various places - and yet I still cannot avoid either one of two unacceptable issues that appear in at least one of the browser/OS combinations...

The combined content is larger than the window, but no scrollbar appears.

An inner scrollbar and an outer scrollbar both appear.

Any hints appreciated!

EDIT:

Thanks for the work - but I don't think I conveyed the issue correctly.

I'm not using frames for layout - I wish simply to make a page framing something on another site (that hosts the shopping cart and whose URL should not be exposed).

Frames "work" - BUT having an interior scrollbar on the second frame and no scrollbar on the whole page is definitely wrong behavior.  My client won't know this but it'll look amateurish to people seeing the page.

I don't see quite how a server-side include or CSS would do it and I know both fairly well.  If I used the server side include, how would links internal to the shopping cart work?  I'd leave my site, correct?

Summary:  A shopping cart hosted on another site, embedded on my content page.

答:
Don't use frames, if the user does command + click then the product will open in new window and your frame will disappear.

One feasible solution I see here is with Javascript:

Load the page via $.ajax

redirect all clicks so that it loads in ajax window by

```<code>$('iframe a').on('click',function(){

    // load the product via AJAX

});
</code>```

make sure height of Div is not fixed so that it expands automatically and scrollbars are there only on window.

This is best way I could think of keeping the integration seamless while hiding the url

Body:
Don't use frames, if the user does command + click then the product will open in new window and your frame will disappear.

One feasible solution I see here is with Javascript:

Load the page via $.ajax

redirect all clicks so that it loads in ajax window by

$('iframe a').on('click',function(){

    // load the product via AJAX

});

make sure height of Div is not fixed so that it expands automatically and scrollbars are there only on window.

This is best way I could think of keeping the integration seamless while hiding the url


问:
How can I install lua5.3 for Centos7
Good day,
I really spent almost all after-noon looking to install lua5.3 on Centos 7.
I mostly found information to install Lua5.1 but we really need a version 5.2 or 5.3.

If I found information for 5.3, it was not for Centos.

Until now, the best I could do, is to download the source version from lua web site
enter link description here
But I still can not install it.

Here are my steps, may be you can help to continue

```<code>curl -R -O http://www.lua.org/ftp/lua-5.3.4.tar.gz
tar zxf lua-5.3.4.tar.gz
cd lua-5.3.4
make linux test
</code>```

The problem, from that point how can I install it.

I tried

```<code>make
</code>```

and

```<code>make linux
</code>```

make linux make me a fatal error

[root@pc6 lua-5.3.4]# make linux cd src && make linux make1:
  Entering directory /root/install-package/lua-5.3.4/src' make all
  SYSCFLAGS="-DLUA_USE_LINUX" SYSLIBS="-Wl,-E -ldl -lreadline" make[2]:
  Entering directory/root/install-package/lua-5.3.4/src' gcc
  -std=gnu99 -O2 -Wall -Wextra -DLUA_COMPAT_5_2 -DLUA_USE_LINUX    -c -o lua.o lua.c lua.c:82:31: fatal error: readline/readline.h: No such
  file or directory  #include
                                 ^ compilation terminated. make[2]: * [lua.o] Error 1 make[2]: Leaving directory
  /root/install-package/lua-5.3.4/src' make[1]: *** [linux] Error 2
  make[1]: Leaving directory/root/install-package/lua-5.3.4/src' make:
  * [linux] Error 2

So what do you suggest me to do. Centos 7 has been istalled today. May do I miss to install a dependent a library?

Thank for your help

答:
The download page which you mention says:

There are detailed instructions in the package

This link points to the README, which says:

If you're running Linux and get compilation errors, make sure you have installed the readline development package (which is probably named libreadline-dev or readline-devel).

If you don't want to install readline, try make posix or make posix MYCFLAGS=-DLUA_USE_DLOPEN MYLIBS=-ldl instead. You may need to do make clean first.

Title: How can I install lua5.3 for Centos7

Body:
Good day,
I really spent almost all after-noon looking to install lua5.3 on Centos 7.
I mostly found information to install Lua5.1 but we really need a version 5.2 or 5.3.

If I found information for 5.3, it was not for Centos.

Until now, the best I could do, is to download the source version from lua web site
enter link description here
But I still can not install it.

Here are my steps, may be you can help to continue

curl -R -O http://www.lua.org/ftp/lua-5.3.4.tar.gz
tar zxf lua-5.3.4.tar.gz
cd lua-5.3.4
make linux test

The problem, from that point how can I install it.

I tried

make

and

make linux

make linux make me a fatal error

[root@pc6 lua-5.3.4]# make linux cd src && make linux make1:
  Entering directory /root/install-package/lua-5.3.4/src' make all
  SYSCFLAGS="-DLUA_USE_LINUX" SYSLIBS="-Wl,-E -ldl -lreadline" make[2]:
  Entering directory/root/install-package/lua-5.3.4/src' gcc
  -std=gnu99 -O2 -Wall -Wextra -DLUA_COMPAT_5_2 -DLUA_USE_LINUX    -c -o lua.o lua.c lua.c:82:31: fatal error: readline/readline.h: No such
  file or directory  #include
                                 ^ compilation terminated. make[2]: * [lua.o] Error 1 make[2]: Leaving directory
  /root/install-package/lua-5.3.4/src' make[1]: *** [linux] Error 2
  make[1]: Leaving directory/root/install-package/lua-5.3.4/src' make:
  * [linux] Error 2

So what do you suggest me to do. Centos 7 has been istalled today. May do I miss to install a dependent a library?

Thank for your help