问:
Reference known property in (List<someClass>)someObject
have tried some searches. Probably my lack of knowledge that I'm not using the right search terms or perhaps just not understanding the answers.

I have a method that is being passed an object, which I want to output a particular value to a text file.
I already know the object will be a List< someClass > of a few different possible classes (customers/employees/items etc). But all of the classes contain the same string property (e.g.) string idNumber.

So something like this:

```<code>public static void OutputFile(object myInput)
{
  foreach (someGenericObject in (List<anyType>)myInput)
  {
    string textToOutput = someGenericObject.idNUmber;
    //output the text to somewhere else here
  }
}
</code>```

I feel like as long as I know that it will always contain a this "idNumber" property regardless of the type, that I should be able to reference it somehow. But I just can't seem to get my head around it?

The error I typically get is something like:

Cannot cast List< Employee > to List< object > etc.

Thanks in advance

答:
You can use [dynamic].</p>

```<code>foreach (var someGenericObject in (dynamic)myInput)
{
    //...
}
</code>```

Body:
have tried some searches. Probably my lack of knowledge that I'm not using the right search terms or perhaps just not understanding the answers.

I have a method that is being passed an object, which I want to output a particular value to a text file.
I already know the object will be a List< someClass > of a few different possible classes (customers/employees/items etc). But all of the classes contain the same string property (e.g.) string idNumber.

So something like this:

public static void OutputFile(object myInput)
{
  foreach (someGenericObject in (List<anyType>)myInput)
  {
    string textToOutput = someGenericObject.idNUmber;
    //output the text to somewhere else here
  }
}

I feel like as long as I know that it will always contain a this "idNumber" property regardless of the type, that I should be able to reference it somehow. But I just can't seem to get my head around it?

The error I typically get is something like:

Cannot cast List< Employee > to List< object > etc.

Thanks in advance

Body:
You can use [dynamic].

foreach (var someGenericObject in (dynamic)myInput)
{
    //...
}


来源: stackexchange

问:
How to call a models database query in a javascript function in a view?
On my user inbox from my user messaging system I am building a feature where a user can make an email message a favourite message.

I have created 2 methods in my messages model. One updates the 0 in the 'messages' table, 'favourite' column to 1 which would mean the user wants the message to be a favourite. Also the image the user clicks on to make the message a favourite turns from grey to colour.

Then I do this same process again if a user wants to make the message not a favourite. The 1 is updated to a 0 and the image turns greyed out again.

Below is my jquery/javascript that basically does something if the box is checked  (image is in colour) and something else if the box is not unchecked (image greyed out).

```<code>// favourite check box
    $('input.favourite:checkbox').simpleImageCheck({
  image: '<?php echo base_url()?>images/messages/check.png',
  imageChecked: '<?php echo base_url()?>images/messages/unchecked.png',
  afterCheck: function(isChecked) {
    if (isChecked) {
  //query to db from php to update favourite number to 1
    }
    else (!isChecked)
        {
            //query to db from php to update favourite number to 0
        }
  }
});
</code>```

What I am trying to figure out is the best way to called my 2 db queries in my model:

```<code>public function favourite_checked($message_id)
{
    $username = $this->session->userdata('username');
    return $this->db->query("UPDATE messages SET favourite = 1 WHERE id = $message_id AND to_user = '$username'");
}

    public function favourite_unchecked($message_id)
{
    $username = $this->session->userdata('username');
    return $this->db->query("UPDATE messages SET favourite = 0 WHERE id = $message_id AND to_user = '$username'");
}
</code>```

What would be the best way to do this? Calling a model directly in a view is bad practice isn't it?

So how could I achieve what I would like to achieve?

Could a controller act as a middle man?

If so how would I even call a controller in a javascript function?

I always appreciate the advice given on here. Thanks in advance

答:
in addition to Summer's $.get method, you can use jQuery's $.post() method in much the same way. I like using
post better because Codeigniter was written to favor post requests over get requests.  </p>

ContentLicense: CC BY-SA 2.5

Body:
On my user inbox from my user messaging system I am building a feature where a user can make an email message a favourite message.

I have created 2 methods in my messages model. One updates the 0 in the 'messages' table, 'favourite' column to 1 which would mean the user wants the message to be a favourite. Also the image the user clicks on to make the message a favourite turns from grey to colour.

Then I do this same process again if a user wants to make the message not a favourite. The 1 is updated to a 0 and the image turns greyed out again.

Below is my jquery/javascript that basically does something if the box is checked  (image is in colour) and something else if the box is not unchecked (image greyed out).

// favourite check box
    $('input.favourite:checkbox').simpleImageCheck({
  image: '<?php echo base_url()?>images/messages/check.png',
  imageChecked: '<?php echo base_url()?>images/messages/unchecked.png',
  afterCheck: function(isChecked) {
    if (isChecked) {
  //query to db from php to update favourite number to 1
    }
    else (!isChecked)
        {
            //query to db from php to update favourite number to 0
        }
  }
});

What I am trying to figure out is the best way to called my 2 db queries in my model:

public function favourite_checked($message_id)
{
    $username = $this->session->userdata('username');
    return $this->db->query("UPDATE messages SET favourite = 1 WHERE id = $message_id AND to_user = '$username'");
}

    public function favourite_unchecked($message_id)
{
    $username = $this->session->userdata('username');
    return $this->db->query("UPDATE messages SET favourite = 0 WHERE id = $message_id AND to_user = '$username'");
}

What would be the best way to do this? Calling a model directly in a view is bad practice isn't it?

So how could I achieve what I would like to achieve?

Could a controller act as a middle man?

If so how would I even call a controller in a javascript function?

I always appreciate the advice given on here. Thanks in advance


问:
Tomcat started but application is not running
I created a spring application and deployed it in tomcat server (Tomcat v5.5 Server). I checked in tomcat manager and found my application is listed.But while i try to run my application,i am getting a page showing

**This program cannot display the webpage

Most likely causes:
You are not connected to the Internet.
The website is encountering problems.
There might be a typing error in the address.

What you can try:
     Check your Internet connection. Try visiting another website to make sure you are connected.

Retype the address.**

I don't know where i am missing out.Please help me in sorting out this issue.

My web.xml file as follows

<?xml version="1.0"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
     <context-param>
    <description>Log4j configuration file used by spring to initialize logging</description>
    <param-name>log4jConfigLocation</param-name>
    <param-value>classpath:pricingLog4j.properties</param-value>
 </context-param>
 <context-param>
  <description>By default myfaces serializes the current view and saves it in session after view is rendered.
        In Pricing UI, values on the Page tags are bound to UIComponents on backing bean using "binding" attribute. Most of the components are created
        in the backing bean. When myfces serializes, it serializes the wrapped object under UIComponents, i.e HtmlDataTabl's value attribute, which are in Pricing UI case
        business objects which have a big graphs attached to it and you start getting "serialization" error

        Keep this pram-value to false to avoid serialization.</description>
  <param-name>org.apache.myfaces.SERIALIZE_STATE_IN_SESSION</param-name>
  <param-value>false</param-value>
 </context-param>
 <context-param>
  <description>Comma separated list of URIs of (additional) faces config
            files. (e.g. /WEB-INF/my-config.xml) See JSF 1.0 PRD2,
            10.3.2.
            DONOT ADD DEFAULT faces-config.xml HERE. IT IS AUTOMATICALLY LOADED BY FACES. IF GIVEN HERE, IT WILL BE LOADED TWICE</description>
  <param-name>javax.faces.CONFIG_FILES</param-name>
  <param-value>/WEB-INF/faces-navigation.xml</param-value>
 </context-param>
 <context-param>
  <param-name>facelets.LIBRARIES</param-name>
  <param-value>
            /WEB-INF/taglib/tomahawk-taglib.xml;
            /WEB-INF/taglib/tomahawk-sandbox-taglib.xml;
            /WEB-INF/taglib/jcp-pricing-ui-taglib.xml;
            /WEB-INF/taglib/acegijsf-taglib.xml
  </param-value>
 </context-param>
 <context-param>
  <param-name>javax.faces.DEFAULT_SUFFIX</param-name>
  <param-value>.xhtml</param-value>
 </context-param>
 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>
            classpath:/config/pricingEngineContext-caching.xml
            classpath:/config/pricingEngineContext-messaging.xml
            classpath:/config/pricingEngineContext-service.xml
            classpath:/config/pricingEngineContext.xml
            classpath:/config/pricingWebApplicationContext.xml
            classpath:/config/securityContext.xml</param-value>
 </context-param>
 <context-param>
  <description>State saving method: "client" or "server" (= default) See
            JSF Specification 2.5.2</description>
  <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
  <param-value>server</param-value>
 </context-param>
 <context-param>
  <description>This parameter tells MyFaces if javascript code should be
            allowed in the rendered HTML output. If javascript is
            allowed, command_link anchors will have javascript code that
            submits the corresponding form. If javascript is not
            allowed, the state saving info and nested parameters will be
            added as url parameters. Default: "true"</description>
  <param-name>org.apache.myfaces.ALLOW_JAVASCRIPT</param-name>
  <param-value>true</param-value>
 </context-param>
 <context-param>
  <description>If true, rendered HTML code will be formatted, so that it is
            "human readable". i.e. additional line separators and
            whitespace will be written, that do not influence the HTML
            code. Default: "true"</description>
  <param-name>org.apache.myfaces.PRETTY_HTML</param-name>
  <param-value>true</param-value>
 </context-param>
 <context-param>
  <param-name>org.apache.myfaces.DETECT_JAVASCRIPT</param-name>
  <param-value>false</param-value>
 </context-param>
 <context-param>
  <description>If true, a javascript function will be rendered that is able
            to restore the former vertical scroll on every request.
            Convenient feature if you have pages with long lists and you
            do not want the browser page to always jump to the top if
            you trigger a link or button action that stays on the same
            page. Default: "false"</description>
  <param-name>org.apache.myfaces.AUTO_SCROLL</param-name>
  <param-value>true</param-value>
 </context-param>

 <context-param>
  <param-name>facelets.DEVELOPMENT</param-name>
  <param-value>true</param-value>
 </context-param>
 <context-param>
  <param-name>facelets.REFRESH_PERIOD</param-name>
  <param-value>2</param-value>
 </context-param>
 <context-param>
  <param-name>org.ajax4jsf.SKIN</param-name>
  <param-value>DEFAULT</param-value>
 </context-param>
 <filter>
  <filter-name>Acegi Channel Processing Filter</filter-name>
  <filter-class>org.acegisecurity.util.FilterToBeanProxy</filter-class>
  <init-param>
   <param-name>targetClass</param-name>
   <param-value>org.acegisecurity.securechannel.ChannelProcessingFilter</param-value>
  </init-param>
 </filter>

 <filter>
  <filter-name>Acegi Filter Chain Proxy</filter-name>
  <filter-class>org.acegisecurity.util.FilterToBeanProxy</filter-class>
  <init-param>
   <param-name>targetClass</param-name>
   <param-value>org.acegisecurity.util.FilterChainProxy</param-value>
  </init-param>
 </filter>

 <filter>
  <filter-name>hibernateFilter</filter-name>
  <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
  <init-param>
   <param-name>sessionFactoryBeanName</param-name>
   <param-value>sessionFactory</param-value>
  </init-param>
 </filter>

 <filter>
  <description>Set the size limit for uploaded files. Format: 10 - 10 bytes
            10k - 10 KB 10m - 10 MB 1g - 1 GB</description>
  <filter-name>extensionsFilter</filter-name>
  <filter-class>org.apache.myfaces.webapp.filter.ExtensionsFilter</filter-class>
  <init-param>
   <param-name>uploadMaxFileSize</param-name>
   <param-value>100m</param-value>
  </init-param>
  <init-param>
   <description>Set the threshold size - files below this limit are
                stored in memory, files above this limit are stored on
                disk.

                Format: 10 - 10 bytes 10k - 10 KB 10m - 10 MB 1g - 1 GB</description>
   <param-name>uploadThresholdSize</param-name>
   <param-value>100k</param-value>
  </init-param>
  <init-param>
   <description>Set the path where the intermediary files will be
                stored.</description>
   <param-name>uploadRepositoryPath</param-name>
   <param-value>/tmp</param-value>
  </init-param>
 </filter>
 <filter>
  <filter-name>orchestraFilter</filter-name>
  <filter-class>org.apache.myfaces.orchestra.conversation.jsf.filter.OrchestraServletFilter</filter-class>
 </filter>
 <filter>
  <filter-name>promotionFilter</filter-name>
  <filter-class>com.jcpenney.web.servlet.PromotionFilter</filter-class>
 </filter>
 <filter>
  <display-name>Ajax4jsf Filter</display-name>
  <filter-name>ajax4jsf</filter-name>
  <filter-class>org.ajax4jsf.Filter</filter-class>
 </filter>
 <filter-mapping>
  <filter-name>Acegi Channel Processing Filter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
 <filter-mapping>
  <filter-name>Acegi Filter Chain Proxy</filter-name>
  <url-pattern>/*</url-pattern>
  <dispatcher>FORWARD</dispatcher>
  <dispatcher>REQUEST</dispatcher>
 </filter-mapping>
 <filter-mapping>
  <filter-name>orchestraFilter</filter-name>
  <url-pattern>*.faces</url-pattern>
 </filter-mapping>

 <filter-mapping>
  <filter-name>hibernateFilter</filter-name>
  <url-pattern>*.faces</url-pattern>
 </filter-mapping>
 <filter-mapping>
  <filter-name>hibernateFilter</filter-name>
  <url-pattern>*.remoting</url-pattern>
 </filter-mapping>

 <filter-mapping>
  <filter-name>extensionsFilter</filter-name>
  <url-pattern>/faces/*</url-pattern>
 </filter-mapping>
 <filter-mapping>
  <filter-name>extensionsFilter</filter-name>
  <url-pattern>*.faces</url-pattern>
 </filter-mapping>
 <filter-mapping>
  <filter-name>promotionFilter</filter-name>
  <url-pattern>*.faces</url-pattern>
 </filter-mapping>
 <filter-mapping>
  <filter-name>ajax4jsf</filter-name>
  <servlet-name>Faces Servlet</servlet-name>
  <dispatcher>REQUEST</dispatcher>
  <dispatcher>FORWARD</dispatcher>
  <dispatcher>INCLUDE</dispatcher>
 </filter-mapping>
 <listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
 </listener>

 <listener>
  <listener-class>org.apache.myfaces.webapp.StartupServletContextListener</listener-class>
 </listener>
 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
 <listener>
  <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
 </listener>
 <listener>
  <listener-class>org.apache.myfaces.orchestra.conversation.servlet.ConversationManagerSessionListener</listener-class>
 </listener>
 <listener>
  <listener-class>com.jcpenney.pricing.web.listeners.SessionLoggingListener</listener-class>
 </listener>

 <listener>
  <listener-class>com.jcpenney.pricing.audit.LogoutLogger</listener-class>
 </listener>

 <servlet>
  <servlet-name>Faces Servlet</servlet-name>
  <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet>
  <servlet-name>Tomahawk-663 Websphere Workaround Servlet</servlet-name>
  <servlet-class>com.jcpenney.web.Tomahawk663Servlet</servlet-class>
 </servlet>
 <servlet>
  <servlet-name>dwr-invoker</servlet-name>
  <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
  <init-param>
     <param-name>debug</param-name>
     <param-value>false</param-value>
  </init-param>
 </servlet>

 <servlet-mapping>
  <servlet-name>Faces Servlet</servlet-name>
  <url-pattern>*.faces</url-pattern>
 </servlet-mapping>

 <servlet-mapping>
  <servlet-name>Tomahawk-663 Websphere Workaround Servlet</servlet-name>
  <url-pattern>/faces/*</url-pattern>
 </servlet-mapping>
 <servlet-mapping>
  <servlet-name>dwr-invoker</servlet-name>
  <url-pattern>/dwr/*</url-pattern>
 </servlet-mapping>

    <servlet>
        <servlet-name>pricingUi-monitoring</servlet-name>
        <servlet-class>org.springframework.web.context.support.HttpRequestHandlerServlet</servlet-class>
        <load-on-startup>3</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>pricingUi-monitoring</servlet-name>
        <url-pattern>/ping</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>pricingUi-monitoring</servlet-name>
        <url-pattern>/services/ping</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>pricingEngine</servlet-name>
        <servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
        <init-param>
            <param-name>transformWsdlLocations</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:config/pricingEngineContext-webservice.xml</param-value>
        </init-param>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet>
        <servlet-name>sale-price-upload</servlet-name>
        <servlet-class>org.springframework.web.context.support.HttpRequestHandlerServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>sale-price-upload</servlet-name>
        <url-pattern>/services/salePriceFileUpload</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>pricingEngine</servlet-name>
        <url-pattern>/services/*</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>pricingEngine</servlet-name>
        <url-pattern>*.wsdl</url-pattern>
    </servlet-mapping>

 <session-config>

  <session-timeout>60</session-timeout>
 </session-config>

 <welcome-file-list>
  <welcome-file>index.html</welcome-file>
 </welcome-file-list>
 <login-config>
  <auth-method>BASIC</auth-method>
 </login-config>

</web-app>
```

答:
I cannot see the exact log messages that is generated for this Error here in the question. Not enough information.

It is also not mentioned how you are building your application and whether the application build is successful or not. I assuming the build is successful.

For a workaround suggestion, if you are using pom.xml in your application and maven to build, can you please check the <source> and <target> of your application?

```<code><source>1.8</source>
<target>1.8</target>
</code>```

If the java version that is mentioned in your pom is mis-matched with your system's java version, the error may appear. That is, your server may startup but your application maynot.

Also you can check your system's java version by using below commands like:

```<code>java -version
javac -version
</code>```

Both the versions should be matched. If you see any difference, change the necessary and rebuild your application and restart the server.

ContentLicense: CC BY-SA 3.0

Body:
I cannot see the exact log messages that is generated for this Error here in the question. Not enough information.

It is also not mentioned how you are building your application and whether the application build is successful or not. I assuming the build is successful.

For a workaround suggestion, if you are using pom.xml in your application and maven to build, can you please check the <source> and <target> of your application?

<source>1.8</source>
<target>1.8</target>

If the java version that is mentioned in your pom is mis-matched with your system's java version, the error may appear. That is, your server may startup but your application maynot.

Also you can check your system's java version by using below commands like:

java -version
javac -version

Both the versions should be matched. If you see any difference, change the necessary and rebuild your application and restart the server.


问:
Perl Parsing CSV Efficient with Embedded Commas and Adding To Database
How do you apply regular expressions to an array. While reading in my csv file I applied this...

```<code>        s/, /- /g;
        s/1,000/1000/g;
</code>```

But after I put the data in my multidimensional array I don't know how to insert the commas back to my fields.

答:
Firstly, there are a few CSV modules you can use to achieve this easily, however in some cases I know people do not have access to, or cannot install packages for reasons. Therefore, this should help if that is the case.

If I am getting you correctly, you are trying to write fields from CSV, which has embedded commas.If this is the case, these imbedded comma fields should have parenthesis or quotes around them in order to ensure they are not seen as the CSV's comma delimited fields. We can then just grab all of the data in your CSV. In this case we will have a csv that uses parenthesis, quotes and both to display data that is using embedded commas:

These show the CSV commas:

```<code>"Potatoes 1,000", (Tomatoes, 200), "(GemSquash, 1,029.95)"
                ^                ^
</code>```

These are embedded commas:

```<code>"Potatoes 1,000", (Tomatoes, 200), "(GemSquash, 1,029.95)"
           ^               ^                  ^  ^
</code>```

So the below will search and replace the data using the parenthesis and the double quotes to determine which are csv commas and which are embedded.

```<code>use strict;
use warnings;

my $string = '(Potatoes 1,000), "Tomatoes, 200", "(GemSquash, 1,029.95)"';
my $query = qr/(?: "\( ( [^()""]* ) \)" |  \( ( [^()]* ) \) |  " ( [^"]* ) " |  ( [^,]* ) ) , \s* /x;
my @results = grep defined, "$string," =~ /$query/g;
print "$_\n" for @results;
</code>```

RESULTS

```<code>Potatoes 1,000
Tomatoes, 200
GemSquash, 1,029.95
</code>```

Body:
How do you apply regular expressions to an array. While reading in my csv file I applied this...

        s/, /- /g;
        s/1,000/1000/g;

But after I put the data in my multidimensional array I don't know how to insert the commas back to my fields.

Body:
Firstly, there are a few CSV modules you can use to achieve this easily, however in some cases I know people do not have access to, or cannot install packages for reasons. Therefore, this should help if that is the case.

If I am getting you correctly, you are trying to write fields from CSV, which has embedded commas.If this is the case, these imbedded comma fields should have parenthesis or quotes around them in order to ensure they are not seen as the CSV's comma delimited fields. We can then just grab all of the data in your CSV. In this case we will have a csv that uses parenthesis, quotes and both to display data that is using embedded commas:

These show the CSV commas:

"Potatoes 1,000", (Tomatoes, 200), "(GemSquash, 1,029.95)"
                ^                ^

These are embedded commas:

"Potatoes 1,000", (Tomatoes, 200), "(GemSquash, 1,029.95)"
           ^               ^                  ^  ^

So the below will search and replace the data using the parenthesis and the double quotes to determine which are csv commas and which are embedded.

use strict;
use warnings;

my $string = '(Potatoes 1,000), "Tomatoes, 200", "(GemSquash, 1,029.95)"';
my $query = qr/(?: "\( ( [^()""]* ) \)" |  \( ( [^()]* ) \) |  " ( [^"]* ) " |  ( [^,]* ) ) , \s* /x;
my @results = grep defined, "$string," =~ /$query/g;
print "$_\n" for @results;

RESULTS

Potatoes 1,000
Tomatoes, 200
GemSquash, 1,029.95


问:
retrieve data from database and put into textview
I am successful in inserting data into the database but when i try to retrieve data and display in textView it gets directed to the MainActivity.

The Regiser_page.java is as follows

```<code>public class Register_Page extends Activity {
    int from_Where_I_Am_Coming = 0;
    private no.nordicsemi.android.nrftoolbox.myDbAdapter mydb ;
    Button b1,b2;
    TextView name ;
    TextView email;
    TextView pass;
    TextView dob;
    TextView gender;
    TextView phone;
    TextView city;
    int id_To_Update = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register__page);
        name = (TextView) findViewById(R.id.editText_name);
        phone = (TextView) findViewById(R.id.editText_phone);
        email = (TextView) findViewById(R.id.editText_email);
        pass = (TextView) findViewById(R.id.editText_pass);
        dob = (TextView) findViewById(R.id.editText_dob);
        gender=(TextView)findViewById(R.id.editText_gender);
        city=(TextView)findViewById(R.id.editText_city);
        b1=(Button)findViewById(R.id.button_register);
        b2=(Button)findViewById(R.id.button_view);
        mydb = new no.nordicsemi.android.nrftoolbox.myDbAdapter(this);

public void addUser(View view) {

        if(mydb.insertContact(name.getText().toString(), email.getText().toString(),
                pass.getText().toString(), dob.getText().toString(),
                gender.getText().toString(),phone.getText().toString(),city.getText().toString())){
            Toast.makeText(getApplicationContext(), "done",
                    Toast.LENGTH_SHORT).show();

        } else{
            Toast.makeText(getApplicationContext(), "not done",
                    Toast.LENGTH_SHORT).show();
        }

    }

}
 public void getmydata(View v){
        Intent intent =new Intent();
        intent.setClass(this ,View_Profile.class);
        startActivity(intent);
    }
</code>```

The Activity_register_page.xml is as follows:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="no.nordicsemi.android.nrftoolbox.Register_Page">

    <RelativeLayout
        android:id="@+id/layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#ffffff"
        android:orientation="vertical"
        android:weightSum="1">

        <TextView
            android:id="@+id/register"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignEnd="@+id/editText_name"
            android:layout_alignParentTop="true"
            android:layout_marginLeft="100dp"
            android:layout_marginTop="28dp"
            android:layout_weight="0.36"
            android:text="Register Here"
            android:textAlignment="center"
            android:textAllCaps="true"
            android:textColor="#3333ff"
            android:textSize="28dp" />

        <Button
            android:id="@+id/button_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="790dp"
            android:onClick="mydata"
            android:text="View data" />

        <TextView
            android:id="@+id/textView_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="14sp"
            android:layout_marginTop="70sp"
            android:autoText="false"
            android:text="Name :"
            android:textColor="#3368ff"
            android:textColorLink="#000000"
            android:textSize="20sp" />

        <EditText
            android:id="@+id/editText_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10sp"
            android:layout_marginRight="10sp"
            android:layout_marginTop="100sp"
            android:ems="10"
            android:hint="Enter your name"
            android:inputType="textPersonName" />

        <TextView
            android:id="@+id/textView_email"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="14sp"
            android:layout_marginTop="160sp"
            android:text="Email-id :"
            android:textColor="#3368ff"
            android:textColorLink="#000000"
            android:textSize="20sp" />

        <EditText
            android:id="@+id/editText_email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10sp"
            android:layout_marginRight="10sp"
            android:layout_marginTop="190sp"
            android:ems="10"
            android:hint="Enter Email-id"
            android:inputType="textEmailAddress" />

        <TextView
            android:id="@+id/textView_pass"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="14dp"
            android:layout_marginTop="250dp"
            android:hint="Enter Password"
            android:text="Password"
            android:textColor="#3368ff"
            android:textSize="20sp" />

        <EditText
            android:id="@+id/editText_pass"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="280dp"
            android:ems="10"
            android:hint="Enter Password"
            android:inputType="textPassword" />

        <TextView
            android:id="@+id/textView_dob"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="14sp"
            android:layout_marginTop="450sp"
            android:text="Date of Birth :"
            android:textColor="#3368ff"
            android:textColorLink="#000000"
            android:textSize="20sp" />

        <EditText
            android:id="@+id/editText_dob"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="480dp"
            android:ems="10"
            android:hint="Date of Birth"
            android:inputType="date" />

        <TextView
            android:id="@+id/textView_phone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="14sp"
            android:layout_marginTop="540sp"
            android:text="Phone No. :"
            android:textColor="#3368ff"
            android:textColorLink="#000000"
            android:textSize="20sp" />

        <EditText
            android:id="@+id/editText_phone"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10sp"
            android:layout_marginRight="10sp"
            android:layout_marginTop="570sp"
            android:ems="10"
            android:hint="Enter Phone No."
            android:inputType="phone" />

        <TextView
            android:id="@+id/textView_city"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="14sp"
            android:layout_marginTop="630sp"
            android:text="City :"
            android:textColor="#3368ff"
            android:textColorLink="#000000"
            android:textSize="20sp" />

        <EditText
            android:id="@+id/editText_city"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10sp"
            android:layout_marginRight="10sp"
            android:layout_marginTop="660sp"
            android:ems="10"
            android:hint="Enter your City"
            android:inputType="textPersonName" />

        <TextView
            android:id="@+id/textView_gender"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="14sp"
            android:layout_marginTop="340sp"
            android:text="Gender :"
            android:textColor="#3368ff"
            android:textColorLink="#000000"
            android:textSize="20sp" />

        <EditText
            android:id="@+id/editText_gender"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="370dp"
            android:ems="10"
            android:hint="M/F/Others"
            android:inputType="textPersonName" />

        <Button
            android:id="@+id/button_register"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:layout_marginBottom="20dp"
            android:layout_marginLeft="110dp"
            android:layout_marginTop="720dp"
            android:background="#3368ff"
            android:onClick="addUser"
            android:text="Register"
            android:textAlignment="center"
            android:textColor="#ffffff" />

    </RelativeLayout>
</android.support.v4.widget.NestedScrollView>
</code>```

The View_Profile.java is as follows:

```<code>public class View_Profile extends AppCompatActivity {
    TextView name, email, pass, phone, gender, city, dob;
    int id_To_Update=0;
    private no.nordicsemi.android.nrftoolbox.myDbAdapter mydb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view__profile);
        name = (TextView) findViewById(R.id.textView_name);
        phone = (TextView) findViewById(R.id.textView_phone);
        email = (TextView) findViewById(R.id.textView_email);
        pass = (TextView) findViewById(R.id.textView_pass);
        gender = (TextView) findViewById(R.id.textView_gender);
        dob = (TextView) findViewById(R.id.textView_dob);
        city = (TextView) findViewById(R.id.textView_city);
        mydb = new no.nordicsemi.android.nrftoolbox.myDbAdapter(this);
        Cursor rs = mydb.getData(1);
        id_To_Update = 1;
        rs.moveToFirst();

        String nam = rs.getString(rs.getColumnIndex(mydb.CONTACTS_COLUMN_NAME));
        String phon = rs.getString(rs.getColumnIndex(mydb.CONTACTS_COLUMN_PHONE));
        String emai = rs.getString(rs.getColumnIndex(mydb.CONTACTS_COLUMN_EMAIL));
        String cit = rs.getString(rs.getColumnIndex(mydb.CONTACTS_COLUMN_CITY));
        String gend = rs.getString(rs.getColumnIndex(mydb.CONTACTS_COLUMN_GENDER));
        String pas = rs.getString(rs.getColumnIndex(mydb.CONTACTS_COLUMN_PASS));
        String dobb = rs.getString(rs.getColumnIndex(mydb.CONTACTS_COLUMN_DOB));

        if (!rs.isClosed())  {
            rs.close();
        }

        name.setText((CharSequence)nam);
        name.setFocusable(false);
        name.setClickable(false);

        email.setText((CharSequence)emai);
        email.setFocusable(false);
        email.setClickable(false);

        pass.setText((CharSequence)pas);
        pass.setFocusable(false);
        pass.setClickable(false);

        dob.setText((CharSequence)dobb);
        dob.setFocusable(false);
        dob.setClickable(false);

        gender.setText((CharSequence)gend);
        gender.setFocusable(false);
        gender.setClickable(false);

        phone.setText((CharSequence)phon);
        phone.setFocusable(false);
        phone.setClickable(false);

        city.setText((CharSequence)cit);
        city.setFocusable(false);
        city.setClickable(false);

    }
}
</code>```

The myDbAdapter.java is as follows:

```<code>public class myDbAdapter extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "MyDBName.db";
    public static final String CONTACTS_TABLE_NAME = "contacts";
    public static final String CONTACTS_COLUMN_ID = "id";
    public static final String CONTACTS_COLUMN_NAME = "name";
    public static final String CONTACTS_COLUMN_EMAIL = "email";
    public static final String CONTACTS_COLUMN_PASS = "password";
    public static final String CONTACTS_COLUMN_DOB = "date-of-birth";
    public static final String CONTACTS_COLUMN_GENDER = "gender";
    public static final String CONTACTS_COLUMN_PHONE="phone";
    public static final String CONTACTS_COLUMN_CITY="city";
    private HashMap hp;

    public myDbAdapter(Context context) {
        super(context, DATABASE_NAME , null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL(
                "create table contacts " +
                        "(id integer primary key, name text,email text,pass text, dob text,gender text,phone text,city text)"
        );
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS contacts");
        onCreate(db);
    }

    public boolean insertContact (String name, String email, String pass, String dob,String gender,String phone,String city) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("name", name);
        contentValues.put("email", email);
        contentValues.put("password", pass);
        contentValues.put("date-of-birth", dob);
        contentValues.put("gender", gender);
        contentValues.put("phone",phone);
        contentValues.put("city",city);
        db.insert("contacts", null, contentValues);
        return true;
    }

    public Cursor getData(int id) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res =  db.rawQuery( "select * from contacts where id="+id+"", null );

        return res;
    }

    public int numberOfRows(){
        SQLiteDatabase db = this.getReadableDatabase();
        int numRows = (int) DatabaseUtils.queryNumEntries(db, CONTACTS_TABLE_NAME);
        return numRows;
    }

    public boolean updateContact (Integer id, String name, String email, String pass, String dob,String gender,String phone,String city) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("name", name);
        contentValues.put("email", email);
        contentValues.put("password", pass);
        contentValues.put("date-of-birth", dob);
        contentValues.put("gender", gender);
        contentValues.put("phone",phone);
        contentValues.put("city",city);
        db.update("contacts", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
        return true;
    }

    public Integer deleteContact (Integer id) {
        SQLiteDatabase db = this.getWritableDatabase();
        return db.delete("contacts",
                "id = ? ",
                new String[] { Integer.toString(id) });
    }

    public ArrayList<String> getAllCotacts() {
        ArrayList<String> array_list = new ArrayList<String>();

        //hp = new HashMap();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res =  db.rawQuery( "select * from contacts", null );
        res.moveToFirst();

        while(res.isAfterLast() == false){
            array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)));
            res.moveToNext();
        }
        return array_list;
    }
}
</code>```

What is the error that is directing View_Profile to MainActivity and results in failure of the display of the result??

My log file shows this error :

```<code>near "-": syntax error
 Error inserting phone=5895346896 email=man@gmail.com name=my name gender=male password=47ufvjtio city=bangalore date-of-birth=30-02-95
                                                                                android.database.sqlite.SQLiteException: near "-": syntax error (code 1): , while compiling: INSERT INTO contacts(phone,email,name,gender,password,city,date-of-birth) VALUES (?,?,?,?,?,?,?)
                                                                                at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                                at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
                                                                                at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
                                                                                at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                                at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
                                                                                at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
                                                                                at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
                                                                                at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
                                                                                at no.nordicsemi.android.nrftoolbox.myDbAdapter.insertContact(myDbAdapter.java:60)
                                                                                at no.nordicsemi.android.nrftoolbox.Register_Page.addUser(Register_Page.java:194)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at android.view.View$1.onClick(View.java:4020)
                                                                                at android.view.View.performClick(View.java:4785)
                                                                                at android.view.View$PerformClick.run(View.java:19888)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5276)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:911)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:706)
</code>```

Is there any error in the insertContact code?? or why is this not working?

答:
When you add new activity you have to register it in manifest file.You should have to register you new activity in your project manifest file.

```<code> <activity
        android:name=".Register_Page"/>

 <activity
        android:name=".View_Profile"/>
</code>```

Add this two line of code in manifest file of your project. you have to add them after your MainActivity's  tag ends in your manifest file.

Body:
I am successful in inserting data into the database but when i try to retrieve data and display in textView it gets directed to the MainActivity.

The Regiser_page.java is as follows

public class Register_Page extends Activity {
    int from_Where_I_Am_Coming = 0;
    private no.nordicsemi.android.nrftoolbox.myDbAdapter mydb ;
    Button b1,b2;
    TextView name ;
    TextView email;
    TextView pass;
    TextView dob;
    TextView gender;
    TextView phone;
    TextView city;
    int id_To_Update = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register__page);
        name = (TextView) findViewById(R.id.editText_name);
        phone = (TextView) findViewById(R.id.editText_phone);
        email = (TextView) findViewById(R.id.editText_email);
        pass = (TextView) findViewById(R.id.editText_pass);
        dob = (TextView) findViewById(R.id.editText_dob);
        gender=(TextView)findViewById(R.id.editText_gender);
        city=(TextView)findViewById(R.id.editText_city);
        b1=(Button)findViewById(R.id.button_register);
        b2=(Button)findViewById(R.id.button_view);
        mydb = new no.nordicsemi.android.nrftoolbox.myDbAdapter(this);

public void addUser(View view) {

        if(mydb.insertContact(name.getText().toString(), email.getText().toString(),
                pass.getText().toString(), dob.getText().toString(),
                gender.getText().toString(),phone.getText().toString(),city.getText().toString())){
            Toast.makeText(getApplicationContext(), "done",
                    Toast.LENGTH_SHORT).show();

        } else{
            Toast.makeText(getApplicationContext(), "not done",
                    Toast.LENGTH_SHORT).show();
        }

    }

}
 public void getmydata(View v){
        Intent intent =new Intent();
        intent.setClass(this ,View_Profile.class);
        startActivity(intent);
    }

The Activity_register_page.xml is as follows:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="no.nordicsemi.android.nrftoolbox.Register_Page">

    <RelativeLayout
        android:id="@+id/layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#ffffff"
        android:orientation="vertical"
        android:weightSum="1">

        <TextView
            android:id="@+id/register"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignEnd="@+id/editText_name"
            android:layout_alignParentTop="true"
            android:layout_marginLeft="100dp"
            android:layout_marginTop="28dp"
            android:layout_weight="0.36"
            android:text="Register Here"
            android:textAlignment="center"
            android:textAllCaps="true"
            android:textColor="#3333ff"
            android:textSize="28dp" />

        <Button
            android:id="@+id/button_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="790dp"
            android:onClick="mydata"
            android:text="View data" />

        <TextView
            android:id="@+id/textView_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="14sp"
            android:layout_marginTop="70sp"
            android:autoText="false"
            android:text="Name :"
            android:textColor="#3368ff"
            android:textColorLink="#000000"
            android:textSize="20sp" />

        <EditText
            android:id="@+id/editText_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10sp"
            android:layout_marginRight="10sp"
            android:layout_marginTop="100sp"
            android:ems="10"
            android:hint="Enter your name"
            android:inputType="textPersonName" />

        <TextView
            android:id="@+id/textView_email"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="14sp"
            android:layout_marginTop="160sp"
            android:text="Email-id :"
            android:textColor="#3368ff"
            android:textColorLink="#000000"
            android:textSize="20sp" />

        <EditText
            android:id="@+id/editText_email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10sp"
            android:layout_marginRight="10sp"
            android:layout_marginTop="190sp"
            android:ems="10"
            android:hint="Enter Email-id"
            android:inputType="textEmailAddress" />

        <TextView
            android:id="@+id/textView_pass"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="14dp"
            android:layout_marginTop="250dp"
            android:hint="Enter Password"
            android:text="Password"
            android:textColor="#3368ff"
            android:textSize="20sp" />

        <EditText
            android:id="@+id/editText_pass"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="280dp"
            android:ems="10"
            android:hint="Enter Password"
            android:inputType="textPassword" />

        <TextView
            android:id="@+id/textView_dob"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="14sp"
            android:layout_marginTop="450sp"
            android:text="Date of Birth :"
            android:textColor="#3368ff"
            android:textColorLink="#000000"
            android:textSize="20sp" />

        <EditText
            android:id="@+id/editText_dob"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="480dp"
            android:ems="10"
            android:hint="Date of Birth"
            android:inputType="date" />

        <TextView
            android:id="@+id/textView_phone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="14sp"
            android:layout_marginTop="540sp"
            android:text="Phone No. :"
            android:textColor="#3368ff"
            android:textColorLink="#000000"
            android:textSize="20sp" />

        <EditText
            android:id="@+id/editText_phone"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10sp"
            android:layout_marginRight="10sp"
            android:layout_marginTop="570sp"
            android:ems="10"
            android:hint="Enter Phone No."
            android:inputType="phone" />

        <TextView
            android:id="@+id/textView_city"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="14sp"
            android:layout_marginTop="630sp"
            android:text="City :"
            android:textColor="#3368ff"
            android:textColorLink="#000000"
            android:textSize="20sp" />

        <EditText
            android:id="@+id/editText_city"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10sp"
            android:layout_marginRight="10sp"
            android:layout_marginTop="660sp"
            android:ems="10"
            android:hint="Enter your City"
            android:inputType="textPersonName" />

        <TextView
            android:id="@+id/textView_gender"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="14sp"
            android:layout_marginTop="340sp"
            android:text="Gender :"
            android:textColor="#3368ff"
            android:textColorLink="#000000"
            android:textSize="20sp" />

        <EditText
            android:id="@+id/editText_gender"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="370dp"
            android:ems="10"
            android:hint="M/F/Others"
            android:inputType="textPersonName" />

        <Button
            android:id="@+id/button_register"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:layout_marginBottom="20dp"
            android:layout_marginLeft="110dp"
            android:layout_marginTop="720dp"
            android:background="#3368ff"
            android:onClick="addUser"
            android:text="Register"
            android:textAlignment="center"
            android:textColor="#ffffff" />

    </RelativeLayout>
</android.support.v4.widget.NestedScrollView>

The View_Profile.java is as follows:

public class View_Profile extends AppCompatActivity {
    TextView name, email, pass, phone, gender, city, dob;
    int id_To_Update=0;
    private no.nordicsemi.android.nrftoolbox.myDbAdapter mydb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view__profile);
        name = (TextView) findViewById(R.id.textView_name);
        phone = (TextView) findViewById(R.id.textView_phone);
        email = (TextView) findViewById(R.id.textView_email);
        pass = (TextView) findViewById(R.id.textView_pass);
        gender = (TextView) findViewById(R.id.textView_gender);
        dob = (TextView) findViewById(R.id.textView_dob);
        city = (TextView) findViewById(R.id.textView_city);
        mydb = new no.nordicsemi.android.nrftoolbox.myDbAdapter(this);
        Cursor rs = mydb.getData(1);
        id_To_Update = 1;
        rs.moveToFirst();

        String nam = rs.getString(rs.getColumnIndex(mydb.CONTACTS_COLUMN_NAME));
        String phon = rs.getString(rs.getColumnIndex(mydb.CONTACTS_COLUMN_PHONE));
        String emai = rs.getString(rs.getColumnIndex(mydb.CONTACTS_COLUMN_EMAIL));
        String cit = rs.getString(rs.getColumnIndex(mydb.CONTACTS_COLUMN_CITY));
        String gend = rs.getString(rs.getColumnIndex(mydb.CONTACTS_COLUMN_GENDER));
        String pas = rs.getString(rs.getColumnIndex(mydb.CONTACTS_COLUMN_PASS));
        String dobb = rs.getString(rs.getColumnIndex(mydb.CONTACTS_COLUMN_DOB));

        if (!rs.isClosed())  {
            rs.close();
        }

        name.setText((CharSequence)nam);
        name.setFocusable(false);
        name.setClickable(false);

        email.setText((CharSequence)emai);
        email.setFocusable(false);
        email.setClickable(false);

        pass.setText((CharSequence)pas);
        pass.setFocusable(false);
        pass.setClickable(false);

        dob.setText((CharSequence)dobb);
        dob.setFocusable(false);
        dob.setClickable(false);

        gender.setText((CharSequence)gend);
        gender.setFocusable(false);
        gender.setClickable(false);

        phone.setText((CharSequence)phon);
        phone.setFocusable(false);
        phone.setClickable(false);

        city.setText((CharSequence)cit);
        city.setFocusable(false);
        city.setClickable(false);

    }
}

The myDbAdapter.java is as follows:

public class myDbAdapter extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "MyDBName.db";
    public static final String CONTACTS_TABLE_NAME = "contacts";
    public static final String CONTACTS_COLUMN_ID = "id";
    public static final String CONTACTS_COLUMN_NAME = "name";
    public static final String CONTACTS_COLUMN_EMAIL = "email";
    public static final String CONTACTS_COLUMN_PASS = "password";
    public static final String CONTACTS_COLUMN_DOB = "date-of-birth";
    public static final String CONTACTS_COLUMN_GENDER = "gender";
    public static final String CONTACTS_COLUMN_PHONE="phone";
    public static final String CONTACTS_COLUMN_CITY="city";
    private HashMap hp;

    public myDbAdapter(Context context) {
        super(context, DATABASE_NAME , null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL(
                "create table contacts " +
                        "(id integer primary key, name text,email text,pass text, dob text,gender text,phone text,city text)"
        );
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS contacts");
        onCreate(db);
    }

    public boolean insertContact (String name, String email, String pass, String dob,String gender,String phone,String city) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("name", name);
        contentValues.put("email", email);
        contentValues.put("password", pass);
        contentValues.put("date-of-birth", dob);
        contentValues.put("gender", gender);
        contentValues.put("phone",phone);
        contentValues.put("city",city);
        db.insert("contacts", null, contentValues);
        return true;
    }

    public Cursor getData(int id) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res =  db.rawQuery( "select * from contacts where id="+id+"", null );

        return res;
    }

    public int numberOfRows(){
        SQLiteDatabase db = this.getReadableDatabase();
        int numRows = (int) DatabaseUtils.queryNumEntries(db, CONTACTS_TABLE_NAME);
        return numRows;
    }

    public boolean updateContact (Integer id, String name, String email, String pass, String dob,String gender,String phone,String city) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("name", name);
        contentValues.put("email", email);
        contentValues.put("password", pass);
        contentValues.put("date-of-birth", dob);
        contentValues.put("gender", gender);
        contentValues.put("phone",phone);
        contentValues.put("city",city);
        db.update("contacts", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
        return true;
    }

    public Integer deleteContact (Integer id) {
        SQLiteDatabase db = this.getWritableDatabase();
        return db.delete("contacts",
                "id = ? ",
                new String[] { Integer.toString(id) });
    }

    public ArrayList<String> getAllCotacts() {
        ArrayList<String> array_list = new ArrayList<String>();

        //hp = new HashMap();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res =  db.rawQuery( "select * from contacts", null );
        res.moveToFirst();

        while(res.isAfterLast() == false){
            array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)));
            res.moveToNext();
        }
        return array_list;
    }
}

What is the error that is directing View_Profile to MainActivity and results in failure of the display of the result??

My log file shows this error :

near "-": syntax error
 Error inserting phone=5895346896 email=man@gmail.com name=my name gender=male password=47ufvjtio city=bangalore date-of-birth=30-02-95
                                                                                android.database.sqlite.SQLiteException: near "-": syntax error (code 1): , while compiling: INSERT INTO contacts(phone,email,name,gender,password,city,date-of-birth) VALUES (?,?,?,?,?,?,?)
                                                                                at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                                at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
                                                                                at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
                                                                                at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                                at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
                                                                                at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
                                                                                at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
                                                                                at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
                                                                                at no.nordicsemi.android.nrftoolbox.myDbAdapter.insertContact(myDbAdapter.java:60)
                                                                                at no.nordicsemi.android.nrftoolbox.Register_Page.addUser(Register_Page.java:194)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at android.view.View$1.onClick(View.java:4020)
                                                                                at android.view.View.performClick(View.java:4785)
                                                                                at android.view.View$PerformClick.run(View.java:19888)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5276)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:911)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:706)

Is there any error in the insertContact code?? or why is this not working?

Body:
When you add new activity you have to register it in manifest file.You should have to register you new activity in your project manifest file.

 <activity
        android:name=".Register_Page"/>

 <activity
        android:name=".View_Profile"/>

Add this two line of code in manifest file of your project. you have to add them after your MainActivity's  tag ends in your manifest file.


问:
No Json formatter for Option[String]?
I am trying to marshall and un-marshall an Option[String] field to and from JSON. For my use-case, a None value should be marshaled as "null". Here is the code I have:

```<code>import org.scalatest.{FlatSpec, Matchers}

import play.api.libs.json._
import play.api.libs.json.Reads._
import play.api.libs.functional.syntax._

case class Person(
  id: Int,
  firstName: Option[String],
  lastName: Option[String]
)

object Person {
  implicit lazy val personFormat = (
    (__ \ "id").format[Int] and
    (__ \ "first_name").format[Option[String]] and
    (__ \ "last_name").format[Option[String]]
  )(Person.apply, unlift(Person.unapply))
}

class PersonSpec extends FlatSpec with Matchers {
  "When Person instance is marshaled None fields " should
    "be serialized as \"null\" values" in {
    val person = Person(1, None, None)
    import Person._
    val json = Json.toJson(person)
    println(json)
    (json \ "id").as[Int] should be (1)
    (json \ "first_name").get should be (JsNull)
    (json \ "last_name").get should be (JsNull)
  }
}
</code>```

This results in the following compiler error:

```<code>PersonSpec.scala:19: No Json formatter found for type Option[String]. Try to implement an implicit Format for this type.
[error]     (__ \ "first_name").format[Option[String]] and
[error]                               ^
</code>```

These are some of the things I have tried:

Replacing (__ \ "first_name").format[Option[String]] with (__ \ "first_name").formatNullable[String] makes the compiler happy, but the test fails (""java.util.NoSuchElementException: None.get"") with the following output (from println(json))

```<code>{"id":1}
</code>```

This confirms with formatNullable's behavior (don't render None valued fields).

Next, I replaced the format with a writes. Like so:

```<code>object Person {
  implicit lazy val personWrite = (
    (__ \ "id").write[Int] and
    (__ \ "first_name").write[Option[String]] and
    (__ \ "last_name").write[Option[String]]
  )(unlift(Person.unapply))
}
</code>```

Now, the compiler is happy and the test passes.

But I now need to implement a separate Reads. If I could, I would rather not as it violates DRY principle.

What am I doing wrong and when write[Option[...]] works perfectly why not format[Option[...]]?

答:
You can use:</p>
```<code>(__ \ "first_name").formatNullable[String]
</code>```

Title: No Json formatter for Option[String]?

Body:
I am trying to marshall and un-marshall an Option[String] field to and from JSON. For my use-case, a None value should be marshaled as "null". Here is the code I have:

import org.scalatest.{FlatSpec, Matchers}

import play.api.libs.json._
import play.api.libs.json.Reads._
import play.api.libs.functional.syntax._

case class Person(
  id: Int,
  firstName: Option[String],
  lastName: Option[String]
)

object Person {
  implicit lazy val personFormat = (
    (__ \ "id").format[Int] and
    (__ \ "first_name").format[Option[String]] and
    (__ \ "last_name").format[Option[String]]
  )(Person.apply, unlift(Person.unapply))
}

class PersonSpec extends FlatSpec with Matchers {
  "When Person instance is marshaled None fields " should
    "be serialized as \"null\" values" in {
    val person = Person(1, None, None)
    import Person._
    val json = Json.toJson(person)
    println(json)
    (json \ "id").as[Int] should be (1)
    (json \ "first_name").get should be (JsNull)
    (json \ "last_name").get should be (JsNull)
  }
}

This results in the following compiler error:

PersonSpec.scala:19: No Json formatter found for type Option[String]. Try to implement an implicit Format for this type.
[error]     (__ \ "first_name").format[Option[String]] and
[error]                               ^

These are some of the things I have tried:

Replacing (__ \ "first_name").format[Option[String]] with (__ \ "first_name").formatNullable[String] makes the compiler happy, but the test fails (""java.util.NoSuchElementException: None.get"") with the following output (from println(json))

{"id":1}

This confirms with formatNullable's behavior (don't render None valued fields).

Next, I replaced the format with a writes. Like so:

object Person {
  implicit lazy val personWrite = (
    (__ \ "id").write[Int] and
    (__ \ "first_name").write[Option[String]] and
    (__ \ "last_name").write[Option[String]]
  )(unlift(Person.unapply))
}

Now, the compiler is happy and the test passes.

But I now need to implement a separate Reads. If I could, I would rather not as it violates DRY principle.

What am I doing wrong and when write[Option[...]] works perfectly why not format[Option[...]]?

Body:
You can use:

(__ \ "first_name").formatNullable[String]

ContentLicense: CC BY-SA 4.0


问:
How to give dynamic filepath in appender tag in log4j_config.xml?
Hi I am using log4j api to log the informations. I have used log4j_conffig.xml file for creating the log files. I have given the absolute path for each log file in param tag value.

eg :

```<code>appender name="GPREPROCESSOR_DEBUG" class="org.apache.log4j.DailyRollingFileAppender"><br>
        param name="DatePattern" value="'_'yyyyMMdd"/><br>
        param name="File" value="D:/logFiles/GPreprocessor_Debug.log"/><br>
        layout class="com.dnb.genericpreprocessor.common.log.AppXMLLayout"/><br>
/appender><br>
</code>```

i do not want to give "D:/logFiles/" directly.Actually that path is dynamic based on my project location. so how can i give that

答: You have use ${java.home} or ${user.home} to define a relative path for your file. See log4help for more complete examples.</p>

OwnerDisplayName: raja

Body:
Hi I am using log4j api to log the informations. I have used log4j_conffig.xml file for creating the log files. I have given the absolute path for each log file in param tag value.

eg :

appender name="GPREPROCESSOR_DEBUG" class="org.apache.log4j.DailyRollingFileAppender">

        param name="DatePattern" value="'_'yyyyMMdd"/>

        param name="File" value="D:/logFiles/GPreprocessor_Debug.log"/>

        layout class="com.dnb.genericpreprocessor.common.log.AppXMLLayout"/>

/appender>

i do not want to give "D:/logFiles/" directly.Actually that path is dynamic based on my project location. so how can i give that


问:
Could not locate javascript files in react-split-pane
I installed react-split-pane through npm. But couldn't reference it to my project.
Please let me know how to reference this in the project.

The GitHub repo is https://github.com/tomkp/react-split-pane

答:
If you are using create-react-app then your code should look like this:

//other import
import SplitPane from 'react-split-pane'

//component declaration
export default class SomeClass extend component {
 //other logic
 render() {
 return(
    <SplitPane split="vertical" minSize={50} defaultSize={100}>

   </SplitPane>
 );

 }

 }
 ```

Body:
If you are using create-react-app then your code should look like this:

//other import
import SplitPane from 'react-split-pane'

//component declaration
export default class SomeClass extend component {
 //other logic
 render() {
 return(
    <SplitPane split="vertical" minSize={50} defaultSize={100}>
       <div></div>
       <div></div>
   </SplitPane>
 );

 }

 }


问:
Additional time-scale with scale_x_datetime
I have data that looks like this:

```<code>        Date Timestamp        xAcc        yAcc       zAcc
17:42:20.361   1866703 -0.03526625 -0.01266312 -0.9679290
17:42:20.381   1866713 -0.02735012 -0.02082901 -0.9759240
17:42:20.381   1866723 -0.05109851 -0.01674607 -0.9599340
</code>```

What I'm trying to achieve is, to plot Timestamp against e.g. xAcc, but with the real time in seconds on the x-scale, starting with 0.

```<code>diff = as.difftime("00:00:00.010001", "%H:%M:%OS")
start = as.POSIXct("1970-01-01 00:00:00.000", "", format="%Y-%m-%d %H:%M:%OS")
DF$Date = seq.POSIXt(start, by=diff, length.out=length(DF$Date))

ggplot(DF, aes(Timestamp, xAcc)) +
     geom_line() +
     labs(x = 't') +
     scale_x_datetime(labels = DF$Date)
</code>```

But then I get this:

```<code>Error: Invalid input: time_trans works with objects of class POSIXct only
</code>```

Which I find strange, since ?seq.POSIXt says

Value A vector of class "POSIXct".

Does the problem have something to do with

```<code>> class(DF$Date)
[1] "POSIXct" "POSIXt"
</code>```

I found a similar question there combined use of geom_boxplot and scale_x_datetime and tried different variations of

```<code>... + scale_x_discrete(labels = format.Date(DF$Date, "%S"))
</code>```

But then there's no scale at all.

Any help would be appreciated.

答:
You can map Date, which is POSIXct, to x.

reprex::reprex_info()
#> Created by the reprex package v0.1.1.9000 on 2017-11-14

library(ggplot2)

DF <- read.table(text = "        Date Timestamp        xAcc        yAcc       zAcc
17:42:20.361   1866703 -0.03526625 -0.01266312 -0.9679290
17:42:20.381   1866713 -0.02735012 -0.02082901 -0.9759240
17:42:20.381   1866723 -0.05109851 -0.01674607 -0.9599340", header = TRUE)

diff <- as.difftime("00:00:00.010001", "%H:%M:%OS")
start <- as.POSIXct("1970-01-01 00:00:00.000", "", format="%Y-%m-%d %H:%M:%OS")
DF$Date <- seq.POSIXt(start, by=diff, length.out=length(DF$Date))

p <- ggplot(DF, aes(Date, xAcc)) +
  geom_line() +
  labs(x = 't')
p
```

<p><img src="https://i.imgur.com/ahOUMC1.png" alt=""></p>

<p>If you want more control on breaks and labels, you can specify them on <code>scale_x_datetime()</code>:</p>

<pre class="lang-r prettyprint-override"><code>p +  scale_x_datetime(breaks = DF$Date, labels = DF$Date)
</code>```

Body:
I have data that looks like this:

        Date Timestamp        xAcc        yAcc       zAcc
17:42:20.361   1866703 -0.03526625 -0.01266312 -0.9679290
17:42:20.381   1866713 -0.02735012 -0.02082901 -0.9759240
17:42:20.381   1866723 -0.05109851 -0.01674607 -0.9599340

What I'm trying to achieve is, to plot Timestamp against e.g. xAcc, but with the real time in seconds on the x-scale, starting with 0.

diff = as.difftime("00:00:00.010001", "%H:%M:%OS")
start = as.POSIXct("1970-01-01 00:00:00.000", "", format="%Y-%m-%d %H:%M:%OS")
DF$Date = seq.POSIXt(start, by=diff, length.out=length(DF$Date))

ggplot(DF, aes(Timestamp, xAcc)) +
     geom_line() +
     labs(x = 't') +
     scale_x_datetime(labels = DF$Date)

But then I get this:

Error: Invalid input: time_trans works with objects of class POSIXct only

Which I find strange, since ?seq.POSIXt says

Value A vector of class "POSIXct".

Does the problem have something to do with

> class(DF$Date)
[1] "POSIXct" "POSIXt"

I found a similar question there combined use of geom_boxplot and scale_x_datetime and tried different variations of

... + scale_x_discrete(labels = format.Date(DF$Date, "%S"))

But then there's no scale at all.

Any help would be appreciated.

Body:
You can map Date, which is POSIXct, to x.

reprex::reprex_info()
#> Created by the reprex package v0.1.1.9000 on 2017-11-14

library(ggplot2)

DF <- read.table(text = "        Date Timestamp        xAcc        yAcc       zAcc
17:42:20.361   1866703 -0.03526625 -0.01266312 -0.9679290
17:42:20.381   1866713 -0.02735012 -0.02082901 -0.9759240
17:42:20.381   1866723 -0.05109851 -0.01674607 -0.9599340", header = TRUE)

diff <- as.difftime("00:00:00.010001", "%H:%M:%OS")
start <- as.POSIXct("1970-01-01 00:00:00.000", "", format="%Y-%m-%d %H:%M:%OS")
DF$Date <- seq.POSIXt(start, by=diff, length.out=length(DF$Date))

p <- ggplot(DF, aes(Date, xAcc)) +
  geom_line() +
  labs(x = 't')
p

If you want more control on breaks and labels, you can specify them on scale_x_datetime():

p +  scale_x_datetime(breaks = DF$Date, labels = DF$Date)


问:
Regex for my custom URL
Good Day,

I cant create the regex exact for my url:

any-any.test.test2.com or ALL CAPS

http://any-any.test.test2.com or ALL CAPS

https://any-any.test.test2.com or ALL CAPS

can someone please help me how can I make a regex that can accept this url's.

Useful Link:
https://regex101.com/

Note: any means user can input any characters and after first any should have "-" , then all must contain :

.test.test2.com  or

.TEST.TEST2.COM

at the end.

答:
Try this pattern:

```<code>var pattern = "(?i)(https?://)?.+-.+(.test.test2.com)"
</code>```

Usage:

```<code>var test1 = "any-any.test.test2.com";
var test2 = "ANY-ANY.TEST.TEST2.COM";
var test3 = "http://any-any.test.test2.com";
var test4 = "https://any-any.test.test2.com";

var result1 = Regex.Match(test1, pattern);
var result2 = Regex.Match(test2, pattern);
var result3 = Regex.Match(test3, pattern);
var result4 = Regex.Match(test4, pattern);

Console.WriteLine(result1);
Console.WriteLine(result2);
Console.WriteLine(result3);
Console.WriteLine(result4);
</code>```

Output:

```<code>any-any.test.test2.com
ANY-ANY.TEST.TEST2.COM
http://any-any.test.test2.com
https://any-any.test.test2.com
</code>```

Title: Regex for my custom URL

Body:
Try this pattern:

var pattern = "(?i)(https?://)?.+-.+(.test.test2.com)"

Usage:

var test1 = "any-any.test.test2.com";
var test2 = "ANY-ANY.TEST.TEST2.COM";
var test3 = "http://any-any.test.test2.com";
var test4 = "https://any-any.test.test2.com";

var result1 = Regex.Match(test1, pattern);
var result2 = Regex.Match(test2, pattern);
var result3 = Regex.Match(test3, pattern);
var result4 = Regex.Match(test4, pattern);

Console.WriteLine(result1);
Console.WriteLine(result2);
Console.WriteLine(result3);
Console.WriteLine(result4);

Output:

any-any.test.test2.com
ANY-ANY.TEST.TEST2.COM
http://any-any.test.test2.com
https://any-any.test.test2.com


问:
How to deploy an Angular4 + Webpack app on Azure web app without any source repository?
I have angular 4 + webpack app which don't want to be checked in to any source repository such as git . I was wondering how i can deploy it to azure web app ? </p>

答:
First, you should build your angular4 app locally, if you are using angular-cli you can use the command ng build to do that. Next, upload those files located in dist/ folder to your Azure App Service via FTP.

Check out this post to see how you can publish using FTP:

https://learn.microsoft.com/en-us/azure/app-service/app-service-deploy-ftp


问:
Removing keyboard focus from edit control
Is there anyway to kill the focus from edit control whenever it receives a keyboard focus?</p>

答: Create it with the ES_READONLY style, or call EnableWindow(hctl,FALSE); to prevent the control receiving focus.</p>


问:
RSA256 for Google JWT
Looking at integrating with Google Cloud Framework IoT for a project. Running into an issue where GCF needs either RSA256 or ES256 for the signature of the JSON Web Token (signature appears to be the head and payload of the JWT encrypted and GCF will use the public key to verify). However, I don't see RSA256 supported in crypto.

I'm not well versed in crypto so can anyone help enlighten me here.

Am I just looking for the algo name in crypto or is this just plain not supported?

Is there a JWT module for nodemcu?

答:
May have found my own answer. From https://cloud.google.com/iot/docs/how-tos/credentials/jwts

"Cloud IoT Core supports the following signing algorithms:

JWT RS256 (RSASSA-PKCS1-v1_5 using SHA-256 RFC 7518 sec 3.3). This is expressed as RS256 in the alg field in the JWT header."

Title: RSA256 for Google JWT


问:
Python - Double backslash is not passed to command
I need to pass the following user login to a bash subprocess command, however when its passed through it returns as "domain\test" rather than a single backslash. But when i print it, it will return as a single.

```<code>usr = "domain\\"
u = "test"
usrLogin = ''.join([usr,u])
</code>```

I have tried the following variations of assigning usr:

```<code>usr = "domain\\"
usr = 'domain\\'
usr = r'domain\'
usr = r"domain\\"
usr = str(r('domain\\'))
</code>```

The string is passed to the following command:
    subprocess.call(["chown", "-R", usrLogin, usrLocation])

The output i need is:

```<code>domain\test
</code>```

however at the moment, when it is being passed to the subprocess call it is showing as:

```<code>domain\\usr
</code>```

However when i call print it will only show with 1 backslash:

```<code>print('usrLogin)
domain\test
</code>```

Edit: Sorry for the confusion, i have added more detail that hopefully helps.

答:
Just like Van Peer already said the backslash is an escape character for the second backslash. So \\ will result in \.

If you want to have double backslashes as a result you will need to write \\\\.

Body:
I need to pass the following user login to a bash subprocess command, however when its passed through it returns as "domain\test" rather than a single backslash. But when i print it, it will return as a single.

usr = "domain\\"
u = "test"
usrLogin = ''.join([usr,u])

I have tried the following variations of assigning usr:

usr = "domain\\"
usr = 'domain\\'
usr = r'domain\'
usr = r"domain\\"
usr = str(r('domain\\'))

The string is passed to the following command:
    subprocess.call(["chown", "-R", usrLogin, usrLocation])

The output i need is:

domain\test

however at the moment, when it is being passed to the subprocess call it is showing as:

domain\\usr

However when i call print it will only show with 1 backslash:

print('usrLogin)
domain\test

Edit: Sorry for the confusion, i have added more detail that hopefully helps.