问:
NHibernate MappingException
I have been interested in learning NHibernate, so i search a course, and i found one in Pluralsight, but when i go to follow the examples i get this exception and i don't know why i get this exception... and it's kind of annoying because where i search i can't find more info about the exception or an up-to-date guide of NHibernate. So my question is:

a) for the exception itself, why it occurs

b) if you can recommend me a site or a course or anything up to date to learn NHibernate.

Thanks in advance.

I leave the code here:

Customer.cs:

```<code>namespace NHibernateDemo
{
    public class Customer
    {
        public virtual int Id { get; set; }
        public virtual string FirstName { get; set; }
        public virtual string LastName { get; set; }
    }
}
</code>```

Customer.hbm.xml:

```<code><?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:hibernate-mapping-2.2"
                   assembly="NHibernateDemo"
                   namespace="NHibernateDemo">
  <class name="Customer">
    <id name="Id">
      <generator class="native"/>
    </id>
    <property name="FirstName"/>
    <property name="LastName"/>
  </class>
</hibernate-mapping>
</code>```

Program.cs:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using NHibernate.Cfg;
using NHibernate.Dialect;
using NHibernate.Driver;

namespace NHibernateDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var cfg = new Configuration();
            cfg.DataBaseIntegration(x =>
            {
                x.ConnectionString = "Server=localhost;Database=NHibernateDemo;Integrated Security=SSPI;";
                x.Driver<SqlClientDriver>();
                x.Dialect<MsSql2008Dialect>();
            });

            // Here is where i get the MappingException. It says that it can't compile the Customer.hbm.xml file.
            cfg.AddAssembly(Assembly.GetExecutingAssembly());

            var sessionFactory = cfg.BuildSessionFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var tx = session.BeginTransaction())
                {
                    var customers = session.CreateCriteria<Customer>()
                                           .List<Customer>();
                    foreach (var customer in customers)
                    {
                        Console.WriteLine("{0} {1}", customer.FirstName, customer.LastName);
                    }
                    tx.Commit();
                }
                Console.WriteLine("Press <ENTER> to exit...");
                Console.ReadLine();
            }
        }
    }
}
</code>```

Message of the exception:

```<code>"Could not compile the mapping document: NHibernateDemo.Customer.hbm.xml"
</code>```

StackTrace:

```<code>    NHibernate.MappingException: Could not compile the mapping document: NHibernateDemo.Customer.hbm.xml ---> System.InvalidOperationException: Error en el documento XML (1, 2). ---> System.InvalidOperationException: No se esperaba <hibernate-mapping xmlns='urn:hibernate-mapping-2.2'>.
   en Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderHbmMapping.Read109_hibernatemapping()
   --- Fin del seguimiento de la pila de la excepción interna ---
   en System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
   en System.Xml.Serialization.XmlSerializer.Deserialize(TextReader textReader)
   en NHibernate.Cfg.NamedXmlDocument..ctor(String name, XmlDocument document, XmlSerializer serializer)
   en NHibernate.Cfg.NamedXmlDocument..ctor(String name, XmlDocument document)
   en NHibernate.Cfg.Configuration.LoadMappingDocument(XmlReader hbmReader, String name)
   --- Fin del seguimiento de la pila de la excepción interna ---
   en NHibernate.Cfg.Configuration.LogAndThrow(Exception exception)
   en NHibernate.Cfg.Configuration.LoadMappingDocument(XmlReader hbmReader, String name)
   en NHibernate.Cfg.Configuration.AddInputStream(Stream xmlInputStream, String name)
   en NHibernate.Cfg.Configuration.AddResource(String path, Assembly assembly)
   en NHibernate.Cfg.Configuration.AddAssembly(Assembly assembly)
   en NHibernateDemo.Program.Main(String[] args) en d:\Sistema\Documents\Visual Studio 2015\Projects\NHibernateDemo\NHibernateDemo\Program.cs:línea 28
</code>```

答:
the problem is that it can't find the file to compile it, so :

try manually copying the file into your bin directory ( Debug or Release or .. )

make sure your NHibernateDemo.Customer.hbm.xml properties are Build Action : Embedded resource and Copy to Output Directory : Copy Always

if you still have the problem, try adding : cfg.AddFile("NHibernateDemo.Customer.hbm.xml") ( or the path to your hbm.xml file )

if you still have the problem, then try :

cfg.addFile(AssemblyLocation() + "NHibernateDemo.Customer.hbm.xml"); ( or the path to your hbm.xml file, where AssemblyLocation() is  :

```<code>private string AssemblyLocation()
{
    var codebase = new Uri(Assembly.GetExecutingAssembly().CodeBase);

    return Path.GetDirectoryName(codebase.LocalPath);
}
</code>```

cfg.AddAssembly isn't necessary so you might consider removing it  if none of the above works :P

Title: NHibernate MappingException

Body:
I have been interested in learning NHibernate, so i search a course, and i found one in Pluralsight, but when i go to follow the examples i get this exception and i don't know why i get this exception... and it's kind of annoying because where i search i can't find more info about the exception or an up-to-date guide of NHibernate. So my question is:

a) for the exception itself, why it occurs

b) if you can recommend me a site or a course or anything up to date to learn NHibernate.

Thanks in advance.

I leave the code here:

Customer.cs:

namespace NHibernateDemo
{
    public class Customer
    {
        public virtual int Id { get; set; }
        public virtual string FirstName { get; set; }
        public virtual string LastName { get; set; }
    }
}

Customer.hbm.xml:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:hibernate-mapping-2.2"
                   assembly="NHibernateDemo"
                   namespace="NHibernateDemo">
  <class name="Customer">
    <id name="Id">
      <generator class="native"/>
    </id>
    <property name="FirstName"/>
    <property name="LastName"/>
  </class>
</hibernate-mapping>

Program.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using NHibernate.Cfg;
using NHibernate.Dialect;
using NHibernate.Driver;

namespace NHibernateDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var cfg = new Configuration();
            cfg.DataBaseIntegration(x =>
            {
                x.ConnectionString = "Server=localhost;Database=NHibernateDemo;Integrated Security=SSPI;";
                x.Driver<SqlClientDriver>();
                x.Dialect<MsSql2008Dialect>();
            });

            // Here is where i get the MappingException. It says that it can't compile the Customer.hbm.xml file.
            cfg.AddAssembly(Assembly.GetExecutingAssembly());

            var sessionFactory = cfg.BuildSessionFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var tx = session.BeginTransaction())
                {
                    var customers = session.CreateCriteria<Customer>()
                                           .List<Customer>();
                    foreach (var customer in customers)
                    {
                        Console.WriteLine("{0} {1}", customer.FirstName, customer.LastName);
                    }
                    tx.Commit();
                }
                Console.WriteLine("Press <ENTER> to exit...");
                Console.ReadLine();
            }
        }
    }
}

Message of the exception:

"Could not compile the mapping document: NHibernateDemo.Customer.hbm.xml"

StackTrace:

    NHibernate.MappingException: Could not compile the mapping document: NHibernateDemo.Customer.hbm.xml ---> System.InvalidOperationException: Error en el documento XML (1, 2). ---> System.InvalidOperationException: No se esperaba <hibernate-mapping xmlns='urn:hibernate-mapping-2.2'>.
   en Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderHbmMapping.Read109_hibernatemapping()
   --- Fin del seguimiento de la pila de la excepción interna ---
   en System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
   en System.Xml.Serialization.XmlSerializer.Deserialize(TextReader textReader)
   en NHibernate.Cfg.NamedXmlDocument..ctor(String name, XmlDocument document, XmlSerializer serializer)
   en NHibernate.Cfg.NamedXmlDocument..ctor(String name, XmlDocument document)
   en NHibernate.Cfg.Configuration.LoadMappingDocument(XmlReader hbmReader, String name)
   --- Fin del seguimiento de la pila de la excepción interna ---
   en NHibernate.Cfg.Configuration.LogAndThrow(Exception exception)
   en NHibernate.Cfg.Configuration.LoadMappingDocument(XmlReader hbmReader, String name)
   en NHibernate.Cfg.Configuration.AddInputStream(Stream xmlInputStream, String name)
   en NHibernate.Cfg.Configuration.AddResource(String path, Assembly assembly)
   en NHibernate.Cfg.Configuration.AddAssembly(Assembly assembly)
   en NHibernateDemo.Program.Main(String[] args) en d:\Sistema\Documents\Visual Studio 2015\Projects\NHibernateDemo\NHibernateDemo\Program.cs:línea 28

Body:
the problem is that it can't find the file to compile it, so :

try manually copying the file into your bin directory ( Debug or Release or .. )

make sure your NHibernateDemo.Customer.hbm.xml properties are Build Action : Embedded resource and Copy to Output Directory : Copy Always

if you still have the problem, try adding : cfg.AddFile("NHibernateDemo.Customer.hbm.xml") ( or the path to your hbm.xml file )

if you still have the problem, then try :

cfg.addFile(AssemblyLocation() + "NHibernateDemo.Customer.hbm.xml"); ( or the path to your hbm.xml file, where AssemblyLocation() is  :

private string AssemblyLocation()
{
    var codebase = new Uri(Assembly.GetExecutingAssembly().CodeBase);

    return Path.GetDirectoryName(codebase.LocalPath);
}

cfg.AddAssembly isn't necessary so you might consider removing it  if none of the above works :P


来源: stackexchange

问:
Google Appspot: how to customize or change language of the Google Accounts Sign In page
I'm creating a Google Appspot app. If a user is not logged on, they are redirected to the standard sign in page:

```<code>resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
</code>```

The page URI parameters are:

```<code>https://www.google.com/accounts/ServiceLogin?
service=ah&continue=...&ltmpl=gm&ahname=Your+App+Name&sig=...
</code>```

Is there a way to customize the sign in page to some extent, while still using Google Accounts?

Most importantly, is it possible to change the language of the page (since my website is not in English)?

Edit: if I visit any Google site in a specific language (e.g. http://www.google.com/webhp?hl=th, then the login page would be in that language (perhaps Google sets a cookie?). However, ServiceLogin script seems not to support the hl= parameter.

答: I don't think you can change this right now. That said, it's possible that Google will serve the sign up page in whatever language is default in the user's browser. They might be doing that already, if I'm not mistaken.</p>

ContentLicense: CC BY-SA 2.5

Body:
I'm creating a Google Appspot app. If a user is not logged on, they are redirected to the standard sign in page:

resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));

The page URI parameters are:

https://www.google.com/accounts/ServiceLogin?
service=ah&continue=...&ltmpl=gm&ahname=Your+App+Name&sig=...

Is there a way to customize the sign in page to some extent, while still using Google Accounts?

Most importantly, is it possible to change the language of the page (since my website is not in English)?

Edit: if I visit any Google site in a specific language (e.g. http://www.google.com/webhp?hl=th, then the login page would be in that language (perhaps Google sets a cookie?). However, ServiceLogin script seems not to support the hl= parameter.


问:
Android button link to another page when login is correct
I have the code below that currently has a login of an id and password, when the link is clicked I want it to go to a profile page only if the login is correct, at the minute you can enter whatever you want or nothing at all and click Login and this will take you to the profile page. Can someone show me how I can improve my code so that the Login button will only link to the profile page if the login details are correct, according to what is in the database? I have more code that I can upload if you need it. Thanks

```<code>public class MainActivity extends ActionBarActivity {

EditText doctor_number, password;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    doctor_number = (EditText)findViewById(R.id.etDoctorNumber);
    password = (EditText)findViewById(R.id.etPassword);
    final Button btnLogin = (Button) findViewById(R.id.btnLogin);

    btnLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            OnLogin(v);
            //Intent profileIntent = new Intent(MainActivity.this, Profile.class);
            //MainActivity.this.startActivity(profileIntent);
        }
    });
}

public void OnLogin(View view){
    String str_doctor_number = doctor_number.getText().toString();
    String str_password = password.getText().toString();
    String type = "Login";

    BackgroundWorker backgroundWorker = new BackgroundWorker(this);
    backgroundWorker.execute(type, str_doctor_number, str_password);
}
}
</code>```

====
BackgroundWorker.java

```<code>public class BackgroundWorker extends AsyncTask<String, Void, String> {
    Context context;
    AlertDialog alertDialog;
    BackgroundWorker (Context ctx){
        context = ctx;
     }

@Override
protected String doInBackground(String... params) {
    String type = params[0];
    String login_url = "";
    String register_url = "";
    if (type.equals("Login")) {
        try {
            String doctorNumber = params[1];
            String password = params[2];
            URL url = new URL(login_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("doctor_number", "UTF-8")+"="+URLEncoder.encode(doctorNumber, "utf-8")+"&"
            +URLEncoder.encode("password", "UTF-8")+"="+URLEncoder.encode(password, "utf-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
            String result ="";
            String line ="";
            while ((line = bufferedReader.readLine()) != null){
                result += line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else if (type.equals("Register")){
        try {
            String patient_name = params[1];
            String check_in_date = params[2];
            String room_number = params[3];
            String bed_number = params[4];
            String notes = params[5];
            URL url = new URL(register_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("patient_name", "UTF-8")+"="+URLEncoder.encode(patient_name, "utf-8")+"&"
                    + URLEncoder.encode("check_in_date", "UTF-8")+"="+URLEncoder.encode(check_in_date, "utf-8")+"&"
                    + URLEncoder.encode("room_number", "UTF-8")+"="+URLEncoder.encode(room_number, "utf-8")+"&"
                    + URLEncoder.encode("bed_number", "UTF-8")+"="+URLEncoder.encode(bed_number, "utf-8")+"&"
                    + URLEncoder.encode("notes", "UTF-8")+"="+URLEncoder.encode(notes, "utf-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
            String result ="";
            String line ="";
            while ((line = bufferedReader.readLine()) != null){
                result += line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

@Override
protected void onPreExecute() {
    alertDialog = new AlertDialog.Builder(context).create();
    alertDialog.setTitle("Login status: ");
}

@Override
protected void onPostExecute(String result) {
    if (result.contains("Login Successful")){
        Intent profileIntent = new Intent(context, Profile.class);
        context.startActivity(profileIntent);
    } else {
        alertDialog.setMessage(result);
        alertDialog.show();
    }
}

@Override
protected void onProgressUpdate(Void... values) {
    super.onProgressUpdate(values);
}
}
</code>```

答:
Try to adapt this to your code:

```<code>public boolean verifyData(String user, String password){
    boolean authenticated = false;
    try {
        int attempts;
        Statement cmd = connection.createStatement();
        String query = "SELECT * FROM tableuserinfo";
        ResultSet res = cmd.executeQuery(query);
        String sqlUser = null;
        String sqlPsw = null;

        while(res.next()){
             sqlUser = res.getString("user");
             sqlPsw = res.getString("psw");

             if(sqlUser == user){

                 if(sqlPsw == password){
                     authenticated = true;
                     res.close();
                     break;
                 }
                 else{

                 }
             }
        }
    } catch (SQLException | NullPointerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return authenticated;
    }
    return authenticated;
}
</code>```

In these lines of code you ask the database for the username and password that you pass as parameters at the function (in your case doctor_number and password) and return true if they are correct or false if they aren't.

ContentLicense: CC BY-SA 3.0

Body:
I have the code below that currently has a login of an id and password, when the link is clicked I want it to go to a profile page only if the login is correct, at the minute you can enter whatever you want or nothing at all and click Login and this will take you to the profile page. Can someone show me how I can improve my code so that the Login button will only link to the profile page if the login details are correct, according to what is in the database? I have more code that I can upload if you need it. Thanks

public class MainActivity extends ActionBarActivity {

EditText doctor_number, password;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    doctor_number = (EditText)findViewById(R.id.etDoctorNumber);
    password = (EditText)findViewById(R.id.etPassword);
    final Button btnLogin = (Button) findViewById(R.id.btnLogin);

    btnLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            OnLogin(v);
            //Intent profileIntent = new Intent(MainActivity.this, Profile.class);
            //MainActivity.this.startActivity(profileIntent);
        }
    });
}

public void OnLogin(View view){
    String str_doctor_number = doctor_number.getText().toString();
    String str_password = password.getText().toString();
    String type = "Login";

    BackgroundWorker backgroundWorker = new BackgroundWorker(this);
    backgroundWorker.execute(type, str_doctor_number, str_password);
}
}

====
BackgroundWorker.java

public class BackgroundWorker extends AsyncTask<String, Void, String> {
    Context context;
    AlertDialog alertDialog;
    BackgroundWorker (Context ctx){
        context = ctx;
     }

@Override
protected String doInBackground(String... params) {
    String type = params[0];
    String login_url = "";
    String register_url = "";
    if (type.equals("Login")) {
        try {
            String doctorNumber = params[1];
            String password = params[2];
            URL url = new URL(login_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("doctor_number", "UTF-8")+"="+URLEncoder.encode(doctorNumber, "utf-8")+"&"
            +URLEncoder.encode("password", "UTF-8")+"="+URLEncoder.encode(password, "utf-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
            String result ="";
            String line ="";
            while ((line = bufferedReader.readLine()) != null){
                result += line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else if (type.equals("Register")){
        try {
            String patient_name = params[1];
            String check_in_date = params[2];
            String room_number = params[3];
            String bed_number = params[4];
            String notes = params[5];
            URL url = new URL(register_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("patient_name", "UTF-8")+"="+URLEncoder.encode(patient_name, "utf-8")+"&"
                    + URLEncoder.encode("check_in_date", "UTF-8")+"="+URLEncoder.encode(check_in_date, "utf-8")+"&"
                    + URLEncoder.encode("room_number", "UTF-8")+"="+URLEncoder.encode(room_number, "utf-8")+"&"
                    + URLEncoder.encode("bed_number", "UTF-8")+"="+URLEncoder.encode(bed_number, "utf-8")+"&"
                    + URLEncoder.encode("notes", "UTF-8")+"="+URLEncoder.encode(notes, "utf-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
            String result ="";
            String line ="";
            while ((line = bufferedReader.readLine()) != null){
                result += line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

@Override
protected void onPreExecute() {
    alertDialog = new AlertDialog.Builder(context).create();
    alertDialog.setTitle("Login status: ");
}

@Override
protected void onPostExecute(String result) {
    if (result.contains("Login Successful")){
        Intent profileIntent = new Intent(context, Profile.class);
        context.startActivity(profileIntent);
    } else {
        alertDialog.setMessage(result);
        alertDialog.show();
    }
}

@Override
protected void onProgressUpdate(Void... values) {
    super.onProgressUpdate(values);
}
}

Body:
Try to adapt this to your code:

public boolean verifyData(String user, String password){
    boolean authenticated = false;
    try {
        int attempts;
        Statement cmd = connection.createStatement();
        String query = "SELECT * FROM tableuserinfo";
        ResultSet res = cmd.executeQuery(query);
        String sqlUser = null;
        String sqlPsw = null;

        while(res.next()){
             sqlUser = res.getString("user");
             sqlPsw = res.getString("psw");

             if(sqlUser == user){

                 if(sqlPsw == password){
                     authenticated = true;
                     res.close();
                     break;
                 }
                 else{

                 }
             }
        }
    } catch (SQLException | NullPointerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return authenticated;
    }
    return authenticated;
}

In these lines of code you ask the database for the username and password that you pass as parameters at the function (in your case doctor_number and password) and return true if they are correct or false if they aren't.


问:
insert comboBox value
i try to insert comboBox value in table for this I try this

```<code>public void additem(string name,int cost,int f)
    {
        con.Open();
        cmd = new SqlCommand("insert into Item(ItemName,ItemCost,ItemCategoryIdF)values(@ItemName,@ItemCost,@ItemCategoryIdF)", con);
        cmd.Parameters.AddWithValue("@ItemName", name);
        cmd.Parameters.AddWithValue("@ItemCost", cost);
        cmd.Parameters.AddWithValue("@ItemCategoryIdF", f);
        cmd.ExecuteNonQuery();
    }
</code>```

and on button click

```<code>  private void button1_Click(object sender, EventArgs e)
    {
        con.Open();
        string name = textBox1.Text;
        int cost = Convert.ToInt32(textBox2.Text);
        int f = Convert.ToInt32(comboBox1.Selectedvalue);
        Items ab = new Items();
        ab.additem(name, cost, f);
        cmd.ExecuteNonQuery();
        MessageBox.Show("Item Is Inserted!");
        con.Close();
    }
</code>```

this insert successfully but when I check in table f value shows 0 and 0 value inserted in table .. so how I insert selected value from comboBox1in table ?

when I select value from combobox then that value should in f .. suppose in combobox values is chips, sweets, biscuits so if I select biscuit then f value should b 2 because chips for 1 , sweets for 2 and biscuits for 3

updated code but this shows error

```<code>**Additional information: Cannot bind to the new display member.**
</code>```

value I load in comboxbox

```<code> private void Item_Load(object sender, EventArgs e)
    {
        Global.objCon = new SqlConnection(Global.con);
        Global.sqlquery=("select CategoryId,CategoryName from Category");
        Global.objCon.Open();
        Global.objcmd = new SqlCommand(Global.sqlquery, Global.objCon);
        Global. dr = Global.objcmd.ExecuteReader();
        ArrayList arr = new ArrayList();
        while(Global.dr.Read())
        {
            AddItem obj=new AddItem(Convert.ToInt16(Global.dr["CategoryId"]),Global.dr["CategoryName"].ToString());
            arr.Add(obj);
        }
        reader.Close();
        Global.objCon.Close();
        comboBox1.DataSource = arr;
        comboBox1.DisplayMember = "CategoryName";
        comboBox1.ValueMember = "Categoryid";

    }
</code>```

any help

答:
Try this:</p>

```<code> private void Item_Load(object sender, EventArgs e)
{
    Global.objCon = new SqlConnection(Global.con);
    Global.sqlquery=("select CategoryId,CategoryName from Category");
    Global.objCon.Open();
    Global.objcmd = new SqlCommand(Global.sqlquery, Global.objCon);
    Global. dr = Global.objcmd.ExecuteReader();
    BindingList<AddItem> arr = new BindingList<AddItem>();
    while(Global.dr.Read())
    {
        AddItem obj=new AddItem(Convert.ToInt16(Global.dr["CategoryId"]),Global.dr["CategoryName"].ToString());
        arr.Add(obj);
    }
    reader.Close();
    Global.objCon.Close();
    comboBox1.DataSource = arr;
    comboBox1.DisplayMember = "CategoryName";
    comboBox1.ValueMember = "Categoryid";
}
</code>```

Title: insert comboBox value

Body:
i try to insert comboBox value in table for this I try this

public void additem(string name,int cost,int f)
    {
        con.Open();
        cmd = new SqlCommand("insert into Item(ItemName,ItemCost,ItemCategoryIdF)values(@ItemName,@ItemCost,@ItemCategoryIdF)", con);
        cmd.Parameters.AddWithValue("@ItemName", name);
        cmd.Parameters.AddWithValue("@ItemCost", cost);
        cmd.Parameters.AddWithValue("@ItemCategoryIdF", f);
        cmd.ExecuteNonQuery();
    }

and on button click

  private void button1_Click(object sender, EventArgs e)
    {
        con.Open();
        string name = textBox1.Text;
        int cost = Convert.ToInt32(textBox2.Text);
        int f = Convert.ToInt32(comboBox1.Selectedvalue);
        Items ab = new Items();
        ab.additem(name, cost, f);
        cmd.ExecuteNonQuery();
        MessageBox.Show("Item Is Inserted!");
        con.Close();
    }

this insert successfully but when I check in table f value shows 0 and 0 value inserted in table .. so how I insert selected value from comboBox1in table ?

when I select value from combobox then that value should in f .. suppose in combobox values is chips, sweets, biscuits so if I select biscuit then f value should b 2 because chips for 1 , sweets for 2 and biscuits for 3

updated code but this shows error

**Additional information: Cannot bind to the new display member.**

value I load in comboxbox

 private void Item_Load(object sender, EventArgs e)
    {
        Global.objCon = new SqlConnection(Global.con);
        Global.sqlquery=("select CategoryId,CategoryName from Category");
        Global.objCon.Open();
        Global.objcmd = new SqlCommand(Global.sqlquery, Global.objCon);
        Global. dr = Global.objcmd.ExecuteReader();
        ArrayList arr = new ArrayList();
        while(Global.dr.Read())
        {
            AddItem obj=new AddItem(Convert.ToInt16(Global.dr["CategoryId"]),Global.dr["CategoryName"].ToString());
            arr.Add(obj);
        }
        reader.Close();
        Global.objCon.Close();
        comboBox1.DataSource = arr;
        comboBox1.DisplayMember = "CategoryName";
        comboBox1.ValueMember = "Categoryid";

    }

any help

Body:
Try this:

 private void Item_Load(object sender, EventArgs e)
{
    Global.objCon = new SqlConnection(Global.con);
    Global.sqlquery=("select CategoryId,CategoryName from Category");
    Global.objCon.Open();
    Global.objcmd = new SqlCommand(Global.sqlquery, Global.objCon);
    Global. dr = Global.objcmd.ExecuteReader();
    BindingList<AddItem> arr = new BindingList<AddItem>();
    while(Global.dr.Read())
    {
        AddItem obj=new AddItem(Convert.ToInt16(Global.dr["CategoryId"]),Global.dr["CategoryName"].ToString());
        arr.Add(obj);
    }
    reader.Close();
    Global.objCon.Close();
    comboBox1.DataSource = arr;
    comboBox1.DisplayMember = "CategoryName";
    comboBox1.ValueMember = "Categoryid";
}


问:
Initial connection to SQL Server Connection Is Slow. Why?
I have run into a situation with a C# application installed at two sites where the initial connection to SQL Server is extremely slow.  I wrote a test application to verify where the slowdown occurs and it is on the first SQLConnection.Open statement.  It was taking about 41 seconds to establish a connection to the server via named pipes.  We thought it might be a DNS issue but its just as slow using a TCP/IP connection.  After the initial connection is made the connection is pooled and the application responds normally.  Both the workstation and the server are decent machines running Windows 7 Pro, Core 2 Duo 3.16 Ghz with 4 gig of Ram.  I did find the following article on a microsoft forum:

http://social.msdn.microsoft.com/Forums/en/windowscompatibility/thread/f295994c-5812-4e46-8ac9-f05471d4dd54

Turning off the LLMNR protocol did cut the initial connection time in about half to 21 seconds.  However, this is still a long time to get an initial connection to SQL Server.  The only things slightly different from our norm is that DNS in this case is done thru a router and not an actual server.  This has occurred at only two places so far, others run with no issues.  Any help would be appreciated.

Thank You,
Dennis

答: I tried specifying the connection string with integrated security = false (meaning the user id and password are in the connection string) and encrypt = false (just be be 100% sure SSL encryption is not being used).  These specifications did not seem to help and I could not get a connection explicitly using the TCP/IP network library (NetworkLibrary = "dbmssocn").  This could have to do with the server firewall and the port not being open.  I switched back to named pipes and put the named pipe network library specification in the connection string this time (NetworkLibrary = "dbnmpntw").  After this change, the connection was made instantaneously.</p>


问:
ggsave(): Error in UseMethod("grid.draw") : no applicable method for 'grid.draw' applied to an object of class "character"
I am trying to save a plot with ggsave().  I enter the following:

```<code>library(ggplot2)

Test = data.frame("X" = seq(1, 10, 1), "Y" = 2*seq(1, 10, 1))

P = ggplot(
    Test, aes(x=X, y=Y))+
    geom_line()

ggsave(P, "test.pdf", device = "pdf")
</code>```

But get the error:

```<code>Saving 7 x 7 in image
Error in UseMethod("grid.draw") :
  no applicable method for 'grid.draw' applied to an object of class "character"
</code>```

答:
Many R functions that save data, such as write.table(), saveRDS() etc. take as their first argument the object to be saved.  But, this is not true for ggsave().  Instead, by default, its first argument is the name of the file to save to.  Thus, the syntax above would need to be modified in one of two ways:

```<code>ggsave(plot = P, filename = "test.pdf", device = "pdf")
ggsave("test.pdf", P, device = "pdf")
</code>```

Body:
I am trying to save a plot with ggsave().  I enter the following:

library(ggplot2)

Test = data.frame("X" = seq(1, 10, 1), "Y" = 2*seq(1, 10, 1))

P = ggplot(
    Test, aes(x=X, y=Y))+
    geom_line()

ggsave(P, "test.pdf", device = "pdf")

But get the error:

Saving 7 x 7 in image
Error in UseMethod("grid.draw") :
  no applicable method for 'grid.draw' applied to an object of class "character"

Body:
Many R functions that save data, such as write.table(), saveRDS() etc. take as their first argument the object to be saved.  But, this is not true for ggsave().  Instead, by default, its first argument is the name of the file to save to.  Thus, the syntax above would need to be modified in one of two ways:

ggsave(plot = P, filename = "test.pdf", device = "pdf")
ggsave("test.pdf", P, device = "pdf")

ContentLicense: CC BY-SA 4.0


问:
How can I disable / overrride the Wireframe and Stats key in OpenSceneGraph?
I inherited a decent-sized code base that has a subpar camera control scheme.  I'd like to use WASD for controls, but W is for wireframe and S is for statistics.  The only solution I could find was:

```<code>viewer.setKeyEventSetsDone(0);
</code>```

But this doesn't work (or I have it in the wrong place).

What's the easiest way to accomplish disabling wireframe and statistics?  (Or even better remapping them)

答:
The objects that consume the W and S events are two "events handlers", in particular:

StatsHandler, for which you can set the toggle key with this method

StateSetManipulator, refer to this method

Check your code base, you will see them attached to the main osg viewer or one of its views.

Body:
I inherited a decent-sized code base that has a subpar camera control scheme.  I'd like to use WASD for controls, but W is for wireframe and S is for statistics.  The only solution I could find was:

viewer.setKeyEventSetsDone(0);

But this doesn't work (or I have it in the wrong place).

What's the easiest way to accomplish disabling wireframe and statistics?  (Or even better remapping them)


问:
How do I add a horizontal line in a html select control?
How do I add a horizontal line (
 tag) in the dropdown control or in select control in HTML?

答:
```<code><option>----------</option>
</code>```

or

```<code><option>__________</option>
</code>```

but you can't write <option>
</option>

you could also add a css class to an empty <option> with a background image

```<code><option class="divider"> </option>
</code>```

Body:
<option>----------</option>

or

<option>__________</option>

but you can't write <option><hr /></option>

you could also add a css class to an empty <option> with a background image

<option class="divider"> </option>


问:
GMAIL API .NET Invalid Attachment Token
I simply want to download attachments from my last emails programmatically with ASP.NET MVC.

As far as I can find here, the only permission I need from google is "https://www.googleapis.com/auth/gmail.readonly" that grants me    "Read all resources and their metadata—no write operations." Source:
(https://developers.google.com/gmail/api/auth/scopes )

The problem is when I try to access the attach I get an error:

```<code>$exception
{"Google.Apis.Requests.RequestError
Invalid attachment token [400]
Errors
[Message[Invalid attachment token]
Location[ - ] Reason[invalidArgument]
Domain[global]\r\n]\r\n"}
</code>```

This is an example of my code, so far:

```<code>  static string[] Scopes = { GmailService.Scope.GmailReadonly };

   public ActionResult Login()
    {
        UserCredential credential;
        var diskPath = Server.MapPath("~");

        using (var stream = new FileStream(diskPath + "/Content/client_secret.json", FileMode.Open, FileAccess.Read))
        {
            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                Scopes,
                "user",
                CancellationToken.None).Result;
        }

        // Create Gmail API service.
        var service = new GmailService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = ApplicationName,
        });

        var resp = service.HttpClient.GetStringAsync("https://www.googleapis.com/gmail/v1/users/me/messages?q=\"has:attachment\"").Result;
        var root = JsonConvert.DeserializeObject<ListMessagesResponse>(resp);
        foreach (var msg in root.Messages)
            GetAttachments(service, msg.Id);

        return View();
    }

    public static void GetAttachments(GmailService service, String messageId)
    {
        var message = service.Users.Messages.Get("me", messageId).Execute();
        var parts = message.Payload.Parts;
        foreach (var part in parts)
        {
            if (!String.IsNullOrEmpty(part.Filename))
            {
                var attachPart = service.Users.Messages.Attachments.Get("me", messageId, part.PartId).Execute();
                var file = Convert.FromBase64String(attachPart.Data);
                System.IO.File.WriteAllBytes(part.Filename, file);
            }
        }
    }
</code>```

I get this error when I go through:

```<code>  var attachPart = service.Users.Messages.Attachments.Get("me", messageId, part.PartId).Execute();
</code>```

Is there any other Scope I have to put in for Attachments? Or do I have to refresh the token after some operations? I already tried to remove and add again the App in my Google+ profile!

答:
[MY ERROR]

Instead of:

```<code> var attachPart = service.Users.Messages.Attachments.Get("me", messageId, part.PartId).Execute();
</code>```

I must use the ATTACHMENT ID like this:

```<code> var attachPart = service.Users.Messages.Attachments.Get("me", messageId, part.Body.AttachmentId).Execute();
</code>```

Title: GMAIL API .NET Invalid Attachment Token

Body:
I simply want to download attachments from my last emails programmatically with ASP.NET MVC.

As far as I can find here, the only permission I need from google is "https://www.googleapis.com/auth/gmail.readonly" that grants me    "Read all resources and their metadata—no write operations." Source:
(https://developers.google.com/gmail/api/auth/scopes )

The problem is when I try to access the attach I get an error:

$exception
{"Google.Apis.Requests.RequestError
Invalid attachment token [400]
Errors
[Message[Invalid attachment token]
Location[ - ] Reason[invalidArgument]
Domain[global]\r\n]\r\n"}

This is an example of my code, so far:

  static string[] Scopes = { GmailService.Scope.GmailReadonly };

   public ActionResult Login()
    {
        UserCredential credential;
        var diskPath = Server.MapPath("~");

        using (var stream = new FileStream(diskPath + "/Content/client_secret.json", FileMode.Open, FileAccess.Read))
        {
            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                Scopes,
                "user",
                CancellationToken.None).Result;
        }

        // Create Gmail API service.
        var service = new GmailService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = ApplicationName,
        });

        var resp = service.HttpClient.GetStringAsync("https://www.googleapis.com/gmail/v1/users/me/messages?q=\"has:attachment\"").Result;
        var root = JsonConvert.DeserializeObject<ListMessagesResponse>(resp);
        foreach (var msg in root.Messages)
            GetAttachments(service, msg.Id);

        return View();
    }

    public static void GetAttachments(GmailService service, String messageId)
    {
        var message = service.Users.Messages.Get("me", messageId).Execute();
        var parts = message.Payload.Parts;
        foreach (var part in parts)
        {
            if (!String.IsNullOrEmpty(part.Filename))
            {
                var attachPart = service.Users.Messages.Attachments.Get("me", messageId, part.PartId).Execute();
                var file = Convert.FromBase64String(attachPart.Data);
                System.IO.File.WriteAllBytes(part.Filename, file);
            }
        }
    }

I get this error when I go through:

  var attachPart = service.Users.Messages.Attachments.Get("me", messageId, part.PartId).Execute();

Is there any other Scope I have to put in for Attachments? Or do I have to refresh the token after some operations? I already tried to remove and add again the App in my Google+ profile!

Body:
[MY ERROR]

Instead of:

 var attachPart = service.Users.Messages.Attachments.Get("me", messageId, part.PartId).Execute();

I must use the ATTACHMENT ID like this:

 var attachPart = service.Users.Messages.Attachments.Get("me", messageId, part.Body.AttachmentId).Execute();


问:
immutability of const in es6
I am new to react and have a question about immutability in es6 to help my understanding of immutability.

For example, I know this is invalid in JSX as it is reassigning a const.

```<code>const helloWorld = 'Hello World';
helloWorld = 'Bye World';
</code>```

however, this seems valid:

```<code>const helloWorld = {greeting: 'hello World'};
helloWorld.greeting = 'bye world';
</code>```

In essence, the concept i'm trying to wrap my brain around is the idea that while although helloWorld is immutable, the value it holds is not. How and why does this still represent immutability? And why would you use it in this fashion instead of using a let variable?

Thanks and apologies for the noob question if it is as such! :)

答:
First const is not a part of JSX, it's language feature in ECMAScript6. const only make the variable a constant and the value it refers is still mutable.

If you want to make the value immutable, use Object.freeze or a library like Immutable.js.

Title: immutability of const in es6

Body:
I am new to react and have a question about immutability in es6 to help my understanding of immutability.

For example, I know this is invalid in JSX as it is reassigning a const.

const helloWorld = 'Hello World';
helloWorld = 'Bye World';

however, this seems valid:

const helloWorld = {greeting: 'hello World'};
helloWorld.greeting = 'bye world';

In essence, the concept i'm trying to wrap my brain around is the idea that while although helloWorld is immutable, the value it holds is not. How and why does this still represent immutability? And why would you use it in this fashion instead of using a let variable?

Thanks and apologies for the noob question if it is as such! :)


问:
Combining ng-if together
I want my two ng-if to work together instead of separately. If both are true then only show the last one that is true. My code looks like this right now.

```<code><div>
    <img ng-src="{{img(myColor)}}" ng-if="myColor">

    <img ng-src="{{img(myColor2)}}" ng-if="myColor2">
</div>
</code>```

However, this just stacks them on top of each other when both ng-if become true. Is there a way to only show one at a time without css

答:
I might be very late to suggest a solution. But I assume you can do it with && bitwise operator.

Below is the sample code:

```

Title: Combining ng-if together

Body:
I want my two ng-if to work together instead of separately. If both are true then only show the last one that is true. My code looks like this right now.

However, this just stacks them on top of each other when both ng-if become true. Is there a way to only show one at a time without css

Body:
I might be very late to suggest a solution. But I assume you can do it with && bitwise operator.

Below is the sample code:

<div>
    <img ng-src="{{img(myColor)}}" ng-if="myColor && !myColor2">

    <img ng-src="{{img(myColor2)}}" ng-if="myColor && myColor2">
</div>


问:
Drawing multiple GeoJSON lines with Mapbox and Nominatim
I'm trying to draw a street when a user clicks on it on the map that uses OSM data and is rendered by Mapbox. I get the coordinates from the click and send them to the server, and then i return the LineStrings, that Nominatim provides for specific street. I have an issue with longer streets: they seem to be incomplete(eg. 100m of correctly drawn line, then 100 of the street is missing and then again normally drawn line), some longer streets can be made of even as much as 10 or more segments. In my opinion this problem can be caused because osm has incomplete data(though i doubt that) or i don't draw/load the data correctly. My code looks like that:

map.on("click", function(e) {
      //get coordinates and send them to the server.

      function getRequest() {
        return $.ajax({
          url: "/street",
          data: clickCoords,
        });
      };

      $.when(getRequest()).done(function(response, status, jqXHR) {
        streetGEOJSON = response;
        var feat = [];
        for (var i = 0; i < streetGEOJSON.length; i++) {
          feat[i] = {
            "type": "Feature",
            "geometry": {
              "type": "LineString",
              "coordinates": streetGEOJSON[i]
            }
          }
        }
        var lines = {
          "type": "geojson",
          "data": {
            "type": "FeatureCollection",
            "features": feat
          }
        }
        map.addSource("street", lines);

        map.addLayer({
          "id": "street",
          "type": "line",
          "source": "street",
          "filter": ["==", "$type", "LineString"],
          "layout": {
            "line-join": "round",
            "line-cap": "round"
          },
          "paint": {
            "line-color": "#888",
            "line-width": 8
          }
        });
      });```

example of wronly drawn street: http://prntscr.com/erfwhr

also noticed this: http://prntscr.com/erg0r0 .
the data passed to as get response can be as much as 3000 or more characters long. i'm guessing that's the problem, and the browser doesn't wait for all the coordinates..

Any help or insight would be really appreciated.

答: I will post the answer if anyone encounters similar problems :) the problem was not in the request from the server but in nominatim reducing search results so the solution was to include &dedupe=0 in get request for nominatim.</p>

Body:
I'm trying to draw a street when a user clicks on it on the map that uses OSM data and is rendered by Mapbox. I get the coordinates from the click and send them to the server, and then i return the LineStrings, that Nominatim provides for specific street. I have an issue with longer streets: they seem to be incomplete(eg. 100m of correctly drawn line, then 100 of the street is missing and then again normally drawn line), some longer streets can be made of even as much as 10 or more segments. In my opinion this problem can be caused because osm has incomplete data(though i doubt that) or i don't draw/load the data correctly. My code looks like that:

map.on("click", function(e) {
      //get coordinates and send them to the server.

      function getRequest() {
        return $.ajax({
          url: "/street",
          data: clickCoords,
        });
      };

      $.when(getRequest()).done(function(response, status, jqXHR) {
        streetGEOJSON = response;
        var feat = [];
        for (var i = 0; i < streetGEOJSON.length; i++) {
          feat[i] = {
            "type": "Feature",
            "geometry": {
              "type": "LineString",
              "coordinates": streetGEOJSON[i]
            }
          }
        }
        var lines = {
          "type": "geojson",
          "data": {
            "type": "FeatureCollection",
            "features": feat
          }
        }
        map.addSource("street", lines);

        map.addLayer({
          "id": "street",
          "type": "line",
          "source": "street",
          "filter": ["==", "$type", "LineString"],
          "layout": {
            "line-join": "round",
            "line-cap": "round"
          },
          "paint": {
            "line-color": "#888",
            "line-width": 8
          }
        });
      });

example of wronly drawn street: http://prntscr.com/erfwhr

also noticed this: http://prntscr.com/erg0r0 .
the data passed to as get response can be as much as 3000 or more characters long. i'm guessing that's the problem, and the browser doesn't wait for all the coordinates..

Any help or insight would be really appreciated.


问:
Wagtail Images Not Loading Once Deployed
I'm not quite sure what's going on, but my images loaded fine on my local development server. However, once I deployed, the images will not load. I checked the URL and it seems to be correct. I'm not sure what's going on here.

base.py

```<code>MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
</code>```

HTML

```<code>{% load wagtailcore_tags wagtailimages_tags %}
...
{% with post.main_image as main_image %}
    {% if main_image %}{% image main_image fill-400x200 %}{% endif %}
{% endwith %}
</code>```

Page Source for Element

```<code><img alt="photo" src="/media/images/Lily.2e16d0ba.fill-400x200.jpg" width="400" height="201">
</code>```

I'm pretty confused and I can't really find much about the topic. Am I the only one who's run in to this issue? Any help would be greatly appreciated.

答:
During development (when you use ./manage.py runserver and have the DEBUG setting set to True), Django serves static files itself as a convenience. In production, it's up to you to configure your web server to serve static files from /media and /static: https://docs.djangoproject.com/en/1.10/howto/static-files/deployment/

This is for performance and security reasons - there's no point having static files served via Python code when there's already a web server properly tuned for that task.

Body:
I'm not quite sure what's going on, but my images loaded fine on my local development server. However, once I deployed, the images will not load. I checked the URL and it seems to be correct. I'm not sure what's going on here.

base.py

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

HTML

{% load wagtailcore_tags wagtailimages_tags %}
...
{% with post.main_image as main_image %}
    {% if main_image %}{% image main_image fill-400x200 %}{% endif %}
{% endwith %}

Page Source for Element

I'm pretty confused and I can't really find much about the topic. Am I the only one who's run in to this issue? Any help would be greatly appreciated.


问:
Copy files with strange name in python got error 22
I try to copy files with arbitrary names in windows 7 64bit with python using os,  shutil.copy2 and win32.file.copyfile. I copied all the files in certain folders. Sometimes I had ioerror error 22 whenIi had non English
letters in the file names.  In gui, I can easily copy them without any problem with mouse. Any api I should consider? Any suggestion?  Like replacimg all the illegal letter automatically?</p>

答:
Try using shutil.copytree to copy a folder and all it's content to a destination.

```<code>import shutil
shutil.copytree('path/to/folder', 'path/to/destination')
</code>```

Body:
Try using shutil.copytree to copy a folder and all it's content to a destination.

import shutil
shutil.copytree('path/to/folder', 'path/to/destination')


问:
How to find the index of the permutation
```<code>% index(+List, -Idx) Predicate will get List with permutation and I want to
know index of permutation

For example: ?- index([4,1,3,2],X).
                X= 19.
</code>```

My solution:

```<code>index([],0).
index([_],1).
index([X,Y],2):- Y > X.
index([H,X|T],Idx):-index([X|T],Idx+1),H > X.
</code>```

Why is it wrong?
And how can I make incremention of Idx?

答:
permutation/2 generates elements on backtracking. It's not really easy to track the index of a solution, so this is the easier way for your immediate problem:

```<code>?- findall(P,permutation([1,2,3,4],P),L), nth0(I,L,[4,1,3,2]).                                                                                L = [[1, 2, 3, 4], [1, 2, 4, 3], [1, 3, 2, 4], [1, 3, 4, 2], [1, 4, 2, 3], [1, 4, 3|...], [2, 1|...], [2|...], [...|...]|...],
I = 19 ;
false.
</code>```

edit

something more efficient, could use this

```<code>nthsol(Goal, N) :-
    State = state(0, _),
    Goal,
    arg(1, State, C),
    N is C+1,
    nb_setarg(1, State, N).
</code>```

in this way:

```<code>?- nthsol(permutation([1,2,3,4],P),I),P=[4,1,3,2].
P = [4, 1, 3, 2],
I = 20 ;
false.
</code>```

the index now it's a counter, so it's offset by 1

Body:
% index(+List, -Idx) Predicate will get List with permutation and I want to
know index of permutation

For example: ?- index([4,1,3,2],X).
                X= 19.

My solution:

index([],0).
index([_],1).
index([X,Y],2):- Y > X.
index([H,X|T],Idx):-index([X|T],Idx+1),H > X.

Why is it wrong?
And how can I make incremention of Idx?

Body:
permutation/2 generates elements on backtracking. It's not really easy to track the index of a solution, so this is the easier way for your immediate problem:

?- findall(P,permutation([1,2,3,4],P),L), nth0(I,L,[4,1,3,2]).                                                                                L = [[1, 2, 3, 4], [1, 2, 4, 3], [1, 3, 2, 4], [1, 3, 4, 2], [1, 4, 2, 3], [1, 4, 3|...], [2, 1|...], [2|...], [...|...]|...],
I = 19 ;
false.

edit

something more efficient, could use this

nthsol(Goal, N) :-
    State = state(0, _),
    Goal,
    arg(1, State, C),
    N is C+1,
    nb_setarg(1, State, N).

in this way:

?- nthsol(permutation([1,2,3,4],P),I),P=[4,1,3,2].
P = [4, 1, 3, 2],
I = 20 ;
false.

the index now it's a counter, so it's offset by 1


问:
C++ static pointer to function
I would like to have a private static pointer to a function in my class. Basically, it would look like this:

```<code>//file.h
class X {
private:
    static int (*staticFunc)(const X&);
    ...
public:
    void f();

};

//file.cpp
void X::f()
{
    staticFunc(*this);
}
</code>```

This gives me an "unresolved external symbol" error. I know that static members must be initialized in the .cpp too, I've tried this:

```<code>int (X::*staticFunc)(const X&) = NULL;
</code>```

but this gives me an "initializing a function" error. It gives me an uglier error if I try to initialize it with an existing function. Without "= NULL", I get the same error.

Thanks.

答:
It's a member of X, so you need to say

```<code>int (*X::staticFunc)(const X&) = NULL;
</code>```

Otherwise, you'd just create a global variable called staticFunc which is not related to that static member of X.

Title: C++ static pointer to function

Body:
I would like to have a private static pointer to a function in my class. Basically, it would look like this:

//file.h
class X {
private:
    static int (*staticFunc)(const X&);
    ...
public:
    void f();

};

//file.cpp
void X::f()
{
    staticFunc(*this);
}

This gives me an "unresolved external symbol" error. I know that static members must be initialized in the .cpp too, I've tried this:

int (X::*staticFunc)(const X&) = NULL;

but this gives me an "initializing a function" error. It gives me an uglier error if I try to initialize it with an existing function. Without "= NULL", I get the same error.

Thanks.

Body:
It's a member of X, so you need to say

int (*X::staticFunc)(const X&) = NULL;

Otherwise, you'd just create a global variable called staticFunc which is not related to that static member of X.


问:
Compile error in RegExp pattern with double quotes
I want to search a string picked from .txt file for numbers enclosed in double quotes. I am doing all this with Excel macros. Example data:

```<code>"08134789316498"
"022"
</code>```

My code:

```<code>Set oRegex1 = CreateObject("VBScript.RegExp")
oRegex1.Pattern = "(\"[0-9]+\"])"
</code>```

But the above line is giving error:

"Compile Error: Expected end of statement"

Note: I have already added references to "Microsoft VBScript Regular Expressions 5.5" and "Microsoft VBScript Regular Expressions 1.0"

答:
It should be like this.</p>

```<code>oRegex1.Pattern = "(""[0-9]+"")"
</code>```

Body:
I want to search a string picked from .txt file for numbers enclosed in double quotes. I am doing all this with Excel macros. Example data:

"08134789316498"
"022"

My code:

Set oRegex1 = CreateObject("VBScript.RegExp")
oRegex1.Pattern = "(\"[0-9]+\"])"

But the above line is giving error:

"Compile Error: Expected end of statement"

Note: I have already added references to "Microsoft VBScript Regular Expressions 5.5" and "Microsoft VBScript Regular Expressions 1.0"

Body:
It should be like this.

oRegex1.Pattern = "(""[0-9]+"")"


问:
Rails: Adding scope in a model using column values of same model in where clause
I am new to rails. I am trying to create a scope using where clause. In that where clause i want to use column values of same model. But i don't know the correct way of doing that. Please help me out. Here's the code snippet:

```<code>attr_accessible :booked_qty,
                :cancelled_qty,
                :quantity_shipped
</code>```

This is the scope that i am trying to create:

```<code>scope :shipped_qty_less_than_max_tolerance_qty, where("quantity_shipped < ?",self.booked_qty-self.cancelled_qty)
</code>```

So what's the best way to write this scope? Thanks in advance!

答:
After visiting all the possible links and trying out different possibilities here's what worked for me:

```<code>scope :shipped_qty_less_than_max_tolerance_qty, where("quantity_shipped < booked_qty-cancelled_qty")
</code>```

Thank you everyone for their support.Cheers!

Body:
I am new to rails. I am trying to create a scope using where clause. In that where clause i want to use column values of same model. But i don't know the correct way of doing that. Please help me out. Here's the code snippet:

attr_accessible :booked_qty,
                :cancelled_qty,
                :quantity_shipped

This is the scope that i am trying to create:

scope :shipped_qty_less_than_max_tolerance_qty, where("quantity_shipped < ?",self.booked_qty-self.cancelled_qty)

So what's the best way to write this scope? Thanks in advance!

Body:
After visiting all the possible links and trying out different possibilities here's what worked for me:

scope :shipped_qty_less_than_max_tolerance_qty, where("quantity_shipped < booked_qty-cancelled_qty")

Thank you everyone for their support.Cheers!


问:
tensorflow modify variables in py_func (and its grad func)
In tensorflow, we can define our own op and its gradient by:
https://gist.github.com/harpone/3453185b41d8d985356cbe5e57d67342

However, can we modify any variable in the computational graph in these python functions. For example in the "_MySquareGrad" function?

I assume we can get the variable by:

```<code>var  = tf.get_variable('var')
</code>```

and then do something to change its value and then assign it back?
e.g.

```<code>tmp = var*10
var.assign(tmp)
</code>```

Thanks!

Also when we do var*10, do we have to convert it to numpy?

Background: I'm familiar with automatic differentiation, but new to Tensorflow and Python. So please point out any syntactic problem and let me know if my intention is clear.

答:
You can modify the variables in the computational graph in these python functions. Your example code with tmp = var*10 will work and does not convert anything to numpy.

In fact you should try to avoid converting to numpy as much as possible since it will slow down the computation.

edit:

You can include your code to the gradient computation graph of the _MySquareGrad function doing this:

```<code>def _MySquareGrad(op, grad):

  #first get a Variable that was created using tf.get_variable()
  with tf.variable_scope("", reuse=True):
    var  = tf.get_variable('var')

  #now create the assign graph:
  tmp = var*10.
  assign_op = var.assign(tmp)

  #now make the assign operation part of the grad calculation graph:
  with tf.control_dependencies([assign_op]):
    x = tf.identity(op.inputs[0])

  return grad * 20 * x
</code>```

Here is a working example:

```<code>import tensorflow as tf
from tensorflow.python.framework import ops
import numpy as np

# Define custom py_func which takes also a grad op as argument:
def py_func(func, inp, Tout, stateful=True, name=None, grad=None):

    # Need to generate a unique name to avoid duplicates:
    rnd_name = 'PyFuncGrad' + str(np.random.randint(0, 1E+8))

    tf.RegisterGradient(rnd_name)(grad)  # see _MySquareGrad for grad example
    g = tf.get_default_graph()
    with g.gradient_override_map({"PyFunc": rnd_name}):
        return tf.py_func(func, inp, Tout, stateful=stateful, name=name)

# Def custom square function using np.square instead of tf.square:
def mysquare(x, name=None):

    with ops.name_scope(name, "Mysquare", [x]) as name:
        sqr_x = py_func(np.square,
                        [x],
                        [tf.float32],
                        name=name,
                        grad=_MySquareGrad)  # <-- here's the call to the gradient
        return sqr_x[0]

### Actual gradient:
##def _MySquareGrad(op, grad):
    ##x = op.inputs[0]
    ##return grad * 20 * x  # add a "small" error just to see the difference:

def _MySquareGrad(op, grad):

  #first get a Variable that was created using tf.get_variable()
  with tf.variable_scope("", reuse=True):
    var  = tf.get_variable('var')

  #now create the assign graph:
  tmp = var*10.
  assign_op = var.assign(tmp)

  #now make the assign operation part of the grad calculation graph:
  with tf.control_dependencies([assign_op]):
    x = tf.identity(op.inputs[0])

  return grad * 20 * x

with tf.Session() as sess:
    x = tf.constant([1., 2.])

    var = tf.get_variable(name="var", shape=[], initializer=tf.constant_initializer(0.2))

    y = mysquare(x)
    tf.global_variables_initializer().run()

    print(x.eval(), y.eval(), tf.gradients(y, x)[0].eval())
    print("Now var is 10 times larger:", var.eval())
</code>```

Body:
In tensorflow, we can define our own op and its gradient by:
https://gist.github.com/harpone/3453185b41d8d985356cbe5e57d67342

However, can we modify any variable in the computational graph in these python functions. For example in the "_MySquareGrad" function?

I assume we can get the variable by:

var  = tf.get_variable('var')

and then do something to change its value and then assign it back?
e.g.

tmp = var*10
var.assign(tmp)

Thanks!

Also when we do var*10, do we have to convert it to numpy?

Background: I'm familiar with automatic differentiation, but new to Tensorflow and Python. So please point out any syntactic problem and let me know if my intention is clear.

Body:
You can modify the variables in the computational graph in these python functions. Your example code with tmp = var*10 will work and does not convert anything to numpy.

In fact you should try to avoid converting to numpy as much as possible since it will slow down the computation.

edit:

You can include your code to the gradient computation graph of the _MySquareGrad function doing this:

def _MySquareGrad(op, grad):

  #first get a Variable that was created using tf.get_variable()
  with tf.variable_scope("", reuse=True):
    var  = tf.get_variable('var')

  #now create the assign graph:
  tmp = var*10.
  assign_op = var.assign(tmp)

  #now make the assign operation part of the grad calculation graph:
  with tf.control_dependencies([assign_op]):
    x = tf.identity(op.inputs[0])

  return grad * 20 * x

Here is a working example:

import tensorflow as tf
from tensorflow.python.framework import ops
import numpy as np

# Define custom py_func which takes also a grad op as argument:
def py_func(func, inp, Tout, stateful=True, name=None, grad=None):

    # Need to generate a unique name to avoid duplicates:
    rnd_name = 'PyFuncGrad' + str(np.random.randint(0, 1E+8))

    tf.RegisterGradient(rnd_name)(grad)  # see _MySquareGrad for grad example
    g = tf.get_default_graph()
    with g.gradient_override_map({"PyFunc": rnd_name}):
        return tf.py_func(func, inp, Tout, stateful=stateful, name=name)

# Def custom square function using np.square instead of tf.square:
def mysquare(x, name=None):

    with ops.name_scope(name, "Mysquare", [x]) as name:
        sqr_x = py_func(np.square,
                        [x],
                        [tf.float32],
                        name=name,
                        grad=_MySquareGrad)  # <-- here's the call to the gradient
        return sqr_x[0]

### Actual gradient:
##def _MySquareGrad(op, grad):
    ##x = op.inputs[0]
    ##return grad * 20 * x  # add a "small" error just to see the difference:

def _MySquareGrad(op, grad):

  #first get a Variable that was created using tf.get_variable()
  with tf.variable_scope("", reuse=True):
    var  = tf.get_variable('var')

  #now create the assign graph:
  tmp = var*10.
  assign_op = var.assign(tmp)

  #now make the assign operation part of the grad calculation graph:
  with tf.control_dependencies([assign_op]):
    x = tf.identity(op.inputs[0])

  return grad * 20 * x

with tf.Session() as sess:
    x = tf.constant([1., 2.])

    var = tf.get_variable(name="var", shape=[], initializer=tf.constant_initializer(0.2))

    y = mysquare(x)
    tf.global_variables_initializer().run()

    print(x.eval(), y.eval(), tf.gradients(y, x)[0].eval())
    print("Now var is 10 times larger:", var.eval())


问:
Android Floating Action Button not being recognized
When I look at my code in the editor, nothing seems to be a problem. However, when I run the code on my phone and try to go from one activity to another which features a floating action button, the floating action button cannot find the view by Id despite the ID being exactly the same in both java and XML.

My Java:

```<code>package com.test.app.app2_test1;

import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class TermsOfUse extends AppCompatActivity {
    FloatingActionButton mFloatingActionButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.terms_of_use);

        mFloatingActionButton = (FloatingActionButton) mFloatingActionButton.findViewById(R.id.terms_back_fab);

        mFloatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }
}
</code>```

My XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.test.app.app2_test1.TermsOfUse"
    android:background="@color/backdrop">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="44dp"
        android:orientation="vertical">

    </ScrollView>

    <View
        android:layout_gravity="bottom"
        android:layout_width="match_parent"
        android:layout_height="44dp"
        android:background="@color/colorPrimary"
        android:elevation="4dp"/>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/terms_back_fab"
        android:layout_gravity="bottom"
        android:layout_width="56dp"
        android:layout_height="56dp"
        android:layout_margin="16dp"
        android:src="@drawable/ic_arrow_back"
        app:pressedTranslationZ="12dp"/>

</android.support.design.widget.CoordinatorLayout>
</code>```

The message that I get in my console is the following:

Attempt to invoke virtual method 'android.view.View android.support.design.widget.FloatingActionButton.findViewById(int)' on a null object reference

Any help would be appreciated.

答:
You are treating a view as a child of its own!

Replace:

```<code>mFloatingActionButton = (FloatingActionButton) mFloatingActionButton.findViewById(R.id.terms_back_fab);
</code>```

With:

```<code>mFloatingActionButton = (FloatingActionButton)findViewById(R.id.terms_back_fab);
</code>```

Body:
When I look at my code in the editor, nothing seems to be a problem. However, when I run the code on my phone and try to go from one activity to another which features a floating action button, the floating action button cannot find the view by Id despite the ID being exactly the same in both java and XML.

My Java:

package com.test.app.app2_test1;

import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class TermsOfUse extends AppCompatActivity {
    FloatingActionButton mFloatingActionButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.terms_of_use);

        mFloatingActionButton = (FloatingActionButton) mFloatingActionButton.findViewById(R.id.terms_back_fab);

        mFloatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }
}

My XML:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.test.app.app2_test1.TermsOfUse"
    android:background="@color/backdrop">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="44dp"
        android:orientation="vertical">

    </ScrollView>

    <View
        android:layout_gravity="bottom"
        android:layout_width="match_parent"
        android:layout_height="44dp"
        android:background="@color/colorPrimary"
        android:elevation="4dp"/>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/terms_back_fab"
        android:layout_gravity="bottom"
        android:layout_width="56dp"
        android:layout_height="56dp"
        android:layout_margin="16dp"
        android:src="@drawable/ic_arrow_back"
        app:pressedTranslationZ="12dp"/>

</android.support.design.widget.CoordinatorLayout>

The message that I get in my console is the following:

Attempt to invoke virtual method 'android.view.View android.support.design.widget.FloatingActionButton.findViewById(int)' on a null object reference

Any help would be appreciated.

Body:
You are treating a view as a child of its own!

Replace:

mFloatingActionButton = (FloatingActionButton) mFloatingActionButton.findViewById(R.id.terms_back_fab);

With:

mFloatingActionButton = (FloatingActionButton)findViewById(R.id.terms_back_fab);


问:
Picking a dll in a particular path while loading a shared library in Windows
I am using MinGW to create a shared library that is dynamically linked and loaded using the LoadLibrary function. My shared library is dependent on a dll that can be found in two different places on the path. These two are different (two different versions) and at the time of loading the library, it picks the wrong dll. How can I explicitly specify which dll to pick?

To be more specific these are the commands I am using:

Compilation

```<code>g++ -m64 -O3 -c my_file.cpp -o myfile.o
</code>```

Creating shared library

```<code>g++ -m64 -shared myfile.o -o myfile.dll
</code>```

I have tried many things including -L option but have not yet been able to figure out how to do this. I also have searched online for a couple of hours but it turn out to be of no use.

Any help is much appreciated.

Thanks in advance

It turns out that the dll I don't want to load is indeed at "The directory where the executable module for the current process is located." The other dll, with the same name is on the path but not where windows looks first. From what this document says, LoadLibrary will always pick the dll from the directory where the executable module for the current process is located, if the dll exists there, no matter what. Is there a way around this? Moving the dlls is really not an option as this is a third party program that we are building on

答:
It turns out that there is another windows function called LoadLibraryEx that allows to explicitly specify a path where the libraries will get loaded. You can learn more about it here:

https://msdn.microsoft.com/en-us/library/windows/desktop/ms684179(v=vs.85).aspx

Specifically, as the docment mentions:

If this value is used and lpFileName specifies an absolute path, the
  system uses the alternate file search strategy discussed in the
  Remarks section to find associated executable modules that the
  specified module causes to be loaded.

and

If lpFileName specifies an absolute path and dwFlags is set to
  LOAD_WITH_ALTERED_SEARCH_PATH, LoadLibraryEx uses the altered search
  path.

Body:
I am using MinGW to create a shared library that is dynamically linked and loaded using the LoadLibrary function. My shared library is dependent on a dll that can be found in two different places on the path. These two are different (two different versions) and at the time of loading the library, it picks the wrong dll. How can I explicitly specify which dll to pick?

To be more specific these are the commands I am using:

Compilation

g++ -m64 -O3 -c my_file.cpp -o myfile.o

Creating shared library

g++ -m64 -shared myfile.o -o myfile.dll

I have tried many things including -L option but have not yet been able to figure out how to do this. I also have searched online for a couple of hours but it turn out to be of no use.

Any help is much appreciated.

Thanks in advance

It turns out that the dll I don't want to load is indeed at "The directory where the executable module for the current process is located." The other dll, with the same name is on the path but not where windows looks first. From what this document says, LoadLibrary will always pick the dll from the directory where the executable module for the current process is located, if the dll exists there, no matter what. Is there a way around this? Moving the dlls is really not an option as this is a third party program that we are building on


问:
Xamarin- Rtl Support in Xamarin.android
I need to support Rtl in my app here is what I did

Replace all the occurrences of layout attributes that contains ‘left’ and ‘right’ to ‘start’ and ‘end’ respectively. For example, android:paddingLeft should become android:paddingStart

Reference

Here is how android studio render my xml layout

my xml code

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/layout"
    android:orientation="vertical"
    >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginLeft="22.3dp"
        android:layout_marginStart="22.3dp"
        android:layout_marginRight="15.3dp"
        android:layout_marginEnd="15.3dp"
        android:layout_marginTop="19dp">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="13.3sp"
            android:textColor="@color/bluey_grey"
            android:textAllCaps="true"
            android:text="@string/language" />
        <TextView
            android:id="@+id/languageText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="13.3sp"
            android:textColor="@color/orange_two"
            android:text="English" />
    </LinearLayout>
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginTop="15dp"
        android:background="@color/silver_two" />
    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="18dp">
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toLeftOf="@+id/notificationChk"
            android:layout_toStartOf="@+id/notificationChk"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:orientation="vertical">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="13.3sp"
                android:textColor="@color/bluey_grey"
                android:textAllCaps="true"
                android:text="@string/push_notifications" />
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="11.7sp"
                android:textColor="@color/cool_grey"
                android:text="@string/pushNotificationDetails" />
        </LinearLayout>
        <android.support.v7.widget.AppCompatCheckBox
            android:id="@+id/notificationChk"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            app:buttonTint="@color/colorPrimary"
            android:layout_centerVertical="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />
    </RelativeLayout>
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginTop="15dp"
        android:background="@color/silver_two" />
    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="18dp">
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toLeftOf="@+id/newsLatterChk"
            android:layout_toStartOf="@+id/newsLatterChk"

            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:orientation="vertical">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="13.3sp"
                android:textAllCaps="true"
                android:textColor="@color/bluey_grey"
                android:text="@string/newsletter" />
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="11.7sp"
                android:textColor="@color/cool_grey"

                android:text="@string/newsLetterDetails" />
        </LinearLayout>
        <CheckBox
            android:id="@+id/newsLatterChk"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />
    </RelativeLayout>
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginTop="15dp"
        android:background="@color/silver_two" />
    <TextView
        android:text="Save"
        android:layout_marginTop="20dp"
        android:padding="10dp"
        android:textSize="14.7dp"
        android:textAllCaps="true"
        android:layout_gravity="center"
        android:gravity="center"
        android:textColor="@color/orange_three"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/saveBtn" />
    <TextView
        android:id="@+id/logoutBtn"
        android:text="@string/logout"
        android:textAllCaps="true"
        android:layout_marginTop="15dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="@color/tomato" />
    <Space
        android:layout_width="wrap_content"
        android:layout_height="20dp" />
    </LinearLayout>
</LinearLayout>
</code>```

but when I run in xamarin here is what I get

what I miss to full support Rtl ??

here is my post in Xamarin Forums  for more detail about my issue

答:
this issue cause my minimum sdk is 16 when I changed to 17 it works , seem to be bug in xamarin

Update

you can keep minSdkVersion 16 as you want but make sure you set targetSdkVersion to 17+

```<code><uses-sdk android:minSdkVersion="16" android:targetSdkVersion="25" />
</code>```

Note when you set target from manifest to auto use target its not placed in manifest it keep like that

```<code><uses-sdk android:minSdkVersion="16"  />
</code>```

so set version manual

Title: Xamarin- Rtl Support in Xamarin.android

Body:
I need to support Rtl in my app here is what I did

Replace all the occurrences of layout attributes that contains ‘left’ and ‘right’ to ‘start’ and ‘end’ respectively. For example, android:paddingLeft should become android:paddingStart

Reference

Here is how android studio render my xml layout

my xml code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/layout"
    android:orientation="vertical"
    >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginLeft="22.3dp"
        android:layout_marginStart="22.3dp"
        android:layout_marginRight="15.3dp"
        android:layout_marginEnd="15.3dp"
        android:layout_marginTop="19dp">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="13.3sp"
            android:textColor="@color/bluey_grey"
            android:textAllCaps="true"
            android:text="@string/language" />
        <TextView
            android:id="@+id/languageText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="13.3sp"
            android:textColor="@color/orange_two"
            android:text="English" />
    </LinearLayout>
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginTop="15dp"
        android:background="@color/silver_two" />
    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="18dp">
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toLeftOf="@+id/notificationChk"
            android:layout_toStartOf="@+id/notificationChk"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:orientation="vertical">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="13.3sp"
                android:textColor="@color/bluey_grey"
                android:textAllCaps="true"
                android:text="@string/push_notifications" />
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="11.7sp"
                android:textColor="@color/cool_grey"
                android:text="@string/pushNotificationDetails" />
        </LinearLayout>
        <android.support.v7.widget.AppCompatCheckBox
            android:id="@+id/notificationChk"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            app:buttonTint="@color/colorPrimary"
            android:layout_centerVertical="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />
    </RelativeLayout>
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginTop="15dp"
        android:background="@color/silver_two" />
    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="18dp">
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toLeftOf="@+id/newsLatterChk"
            android:layout_toStartOf="@+id/newsLatterChk"

            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:orientation="vertical">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="13.3sp"
                android:textAllCaps="true"
                android:textColor="@color/bluey_grey"
                android:text="@string/newsletter" />
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="11.7sp"
                android:textColor="@color/cool_grey"

                android:text="@string/newsLetterDetails" />
        </LinearLayout>
        <CheckBox
            android:id="@+id/newsLatterChk"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />
    </RelativeLayout>
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginTop="15dp"
        android:background="@color/silver_two" />
    <TextView
        android:text="Save"
        android:layout_marginTop="20dp"
        android:padding="10dp"
        android:textSize="14.7dp"
        android:textAllCaps="true"
        android:layout_gravity="center"
        android:gravity="center"
        android:textColor="@color/orange_three"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/saveBtn" />
    <TextView
        android:id="@+id/logoutBtn"
        android:text="@string/logout"
        android:textAllCaps="true"
        android:layout_marginTop="15dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="@color/tomato" />
    <Space
        android:layout_width="wrap_content"
        android:layout_height="20dp" />
    </LinearLayout>
</LinearLayout>

but when I run in xamarin here is what I get

what I miss to full support Rtl ??

here is my post in Xamarin Forums  for more detail about my issue

Body:
this issue cause my minimum sdk is 16 when I changed to 17 it works , seem to be bug in xamarin

Update

you can keep minSdkVersion 16 as you want but make sure you set targetSdkVersion to 17+

<uses-sdk android:minSdkVersion="16" android:targetSdkVersion="25" />

Note when you set target from manifest to auto use target its not placed in manifest it keep like that

<uses-sdk android:minSdkVersion="16"  />

so set version manual


问:
How to get Heroku to recognize a yarn.lock or package.json within a subdirectory (not root)
I have a Rails application using React, Webpack, and Yarn for the client side. I have everything relating to the client side within the /client directory. This includes my yarn.lock and package.json files. I have a Procfile that cds into /client and properly runs yarn run build. This works locally with no errors. However, when I deploy/push to Heroku, my push is rejected and I get the following error:

```<code>remote:        cd client && yarn run build:production
remote:        sh: 1: yarn: not found
remote:        rake aborted!
remote:        Command failed with status (127): [cd client && yarn run build:production...]
</code>```

What this says to me is that Heroku wasn't able to find a yarn.lock file in the root level. How do I get Heroku to use the yarn.lock file within my /client directory?

Or is the cause of this error something else entirely?

答:
Make sure to use both ruby and node buildpacks. I got this error when I didn't.

Execute these in your root folder:

```<code>heroku buildpacks:set heroku/ruby
heroku buildpacks:add --index 1 heroku/nodejs
</code>```

Sources: https://devcenter.heroku.com/articles/using-multiple-buildpacks-for-an-app

https://github.com/shakacode/react_on_rails/blob/master/docs/additional-reading/heroku-deployment.md

Body:
I have a Rails application using React, Webpack, and Yarn for the client side. I have everything relating to the client side within the /client directory. This includes my yarn.lock and package.json files. I have a Procfile that cds into /client and properly runs yarn run build. This works locally with no errors. However, when I deploy/push to Heroku, my push is rejected and I get the following error:

remote:        cd client && yarn run build:production
remote:        sh: 1: yarn: not found
remote:        rake aborted!
remote:        Command failed with status (127): [cd client && yarn run build:production...]

What this says to me is that Heroku wasn't able to find a yarn.lock file in the root level. How do I get Heroku to use the yarn.lock file within my /client directory?

Or is the cause of this error something else entirely?

Body:
Make sure to use both ruby and node buildpacks. I got this error when I didn't.

Execute these in your root folder:

heroku buildpacks:set heroku/ruby
heroku buildpacks:add --index 1 heroku/nodejs

Sources: https://devcenter.heroku.com/articles/using-multiple-buildpacks-for-an-app

https://github.com/shakacode/react_on_rails/blob/master/docs/additional-reading/heroku-deployment.md


问:
Spring Standard Bean Injection vs. Autowiring
As far as I understand When Using Dependency Injection all bean are initializing on Start.

```<code><bean id="userPreferences" class="com.foo.UserPreferences">
  </bean>
  <!-- a singleton-scoped bean injected to the above bean -->
  <bean id="userService" class="com.foo.SimpleUserService">

      <!-- a reference to the userPreferences bean -->
      <property name="userPreferences" ref="userPreferences"/>
  </bean>
</code>```

and the configuration above means that userService and userPreferences created when application starts. Is it correct?

When using Autowiring and using  <context:component-scan>

```<code>public class SimpleUserService{

@Autowired
UserPreferences userPreferences;

//omitted
}
</code>```

1) Is userPreference created on  Application init?

2) What is the default scope for bean injected by autowire and how can we change it?

3) How   affects bean creation and bean injection?

Hope I made myself clear.

答:
The @autowired notation is an obsolete way to say @inject. THe latter is a feature of JavaEE 6.

stackoverflow.com/questions/7142622/what-is-the-difference-between-inject-and-autowired-in-spring-framework-which

Body:
As far as I understand When Using Dependency Injection all bean are initializing on Start.

<bean id="userPreferences" class="com.foo.UserPreferences">
  </bean>

  <bean id="userService" class="com.foo.SimpleUserService">

      <property name="userPreferences" ref="userPreferences"/>
  </bean>

and the configuration above means that userService and userPreferences created when application starts. Is it correct?

When using Autowiring and using  <context:component-scan>

public class SimpleUserService{

@Autowired
UserPreferences userPreferences;

//omitted
}

1) Is userPreference created on  Application init?

2) What is the default scope for bean injected by autowire and how can we change it?

3) How   affects bean creation and bean injection?

Hope I made myself clear.


问:
How can i convert my already exist array to a new specific array?
Here is my Array of canada post shipping rate:

```<code>Array(
[Priority] => Array
    (
        [num] => 388.98
        [str] => Can$ 388.98
    )

[Xpresspost] => Array
    (
        [num] => 294.98
        [str] => Can$ 294.98
    )

[Regular] => Array
    (
        [num] => 97.14
        [str] => Can$ 97.14
    ))
</code>```

Now i want to subtract the value of num by it's half and want's to make a new array from above array like this :

```<code>Array(
[Priority] => Array
    (
        [num] => 194.49
        [str] => Can$ 194.49
    )

[Xpresspost] => Array
    (
        [num] => 147.49
        [str] => Can$ 147.49
    )

[Regular] => Array
    (
        [num] => 48.57
        [str] => Can$ 48.57
    ))
</code>```

So how can i do that ?

答:
you could use a foreach over your array </p>

```<code>foreach($my_array  as $key => $value){
    $val = $value['num']/2;
    $value['num'] = $val;
    $value['str'] = 'Can$ ' .$val;
  }
</code>```

Body:
Here is my Array of canada post shipping rate:

Array(
[Priority] => Array
    (
        [num] => 388.98
        [str] => Can$ 388.98
    )

[Xpresspost] => Array
    (
        [num] => 294.98
        [str] => Can$ 294.98
    )

[Regular] => Array
    (
        [num] => 97.14
        [str] => Can$ 97.14
    ))

Now i want to subtract the value of num by it's half and want's to make a new array from above array like this :

Array(
[Priority] => Array
    (
        [num] => 194.49
        [str] => Can$ 194.49
    )

[Xpresspost] => Array
    (
        [num] => 147.49
        [str] => Can$ 147.49
    )

[Regular] => Array
    (
        [num] => 48.57
        [str] => Can$ 48.57
    ))

So how can i do that ?

Body:
you could use a foreach over your array

foreach($my_array  as $key => $value){
    $val = $value['num']/2;
    $value['num'] = $val;
    $value['str'] = 'Can$ ' .$val;
  }