问:
How do I view the XML produced by the python-docx package
For the purposes of unit testing, I want to check that the XML produced for a Word paragraph is what I expect when I parse an HTML paragraph.

How do I extract the XML itself instead of writing to a file, unzipping the file, and re-reading the word/document.xml file it contains?

e.g.

```<code>from docx import Document
import bs4

def add_parsed_html_to_paragraph(p, s):
    soup = bs4.BeautifulSoup(s)
    para = soup.find('p')
    for e in para.children:
        if type(e) == bs4.element.NavigableString:
            r = p.add_run(str(e))
        else:
            r = p.add_run(e.text)
        if e.name == 'sub':
            r.font.subscript = True
        elif e.name == 'sup':
            r.font.superscript = True

title = 'A formula: H<sub>2</sub>O.'

document = Document()
p = document.add_paragraph()
add_parsed_html_to_paragraph(p, title)

# ... Now I want to check p or document for the correct XML
</code>```

答:
Each so-called oxml element object in python-docx has an .xml property for precisely this use case. It's used for the internal unit tests.

All you need is access to the internal variable used for the XML element, which is generally available by clicking the [source] link next to that object in the docs, like here: https://python-docx.readthedocs.io/en/latest/api/text.html#paragraph-objects

Clicking through that link, you can find that for a paragraph, the underlying XML element is available on ._p. Usually it's the tagname of the element without the namespace prefix, although sometimes its the generic ._element. This latter one is a good one to try in a pinch if you need to guess.

So using it is as simple as:

```<code>>>> paragraph._p.xml
<w:p>
  <w:pPr>
    <w:jc w:val="right"/>
  </w:pPr>
  <w:r>
    <w:t>Right-aligned</w:t>
  </w:r>
</w:p>
</code>```

There is a companion domain-specific language (DSL) in the unit-test utilities called CXML (compact XML) which allows you to take care of namespacing, which is otherwise a big pain. It looks something like this:

```<code>expected_xml = cxml.xml('w:p(w:pPr/w:jc{w:val=right},w:r/w:t"Right-aligned")')
</code>```

You can see examples throughout the unit tests like here: https://github.com/python-openxml/python-docx/blob/master/tests/text/test_paragraph.py#L113 and ask more specific questions here with the "python-docx" tag if you need help.

Body:
For the purposes of unit testing, I want to check that the XML produced for a Word paragraph is what I expect when I parse an HTML paragraph.

How do I extract the XML itself instead of writing to a file, unzipping the file, and re-reading the word/document.xml file it contains?

e.g.

from docx import Document
import bs4

def add_parsed_html_to_paragraph(p, s):
    soup = bs4.BeautifulSoup(s)
    para = soup.find('p')
    for e in para.children:
        if type(e) == bs4.element.NavigableString:
            r = p.add_run(str(e))
        else:
            r = p.add_run(e.text)
        if e.name == 'sub':
            r.font.subscript = True
        elif e.name == 'sup':
            r.font.superscript = True

title = 'A formula: H2O.'

document = Document()
p = document.add_paragraph()
add_parsed_html_to_paragraph(p, title)

# ... Now I want to check p or document for the correct XML

Body:
Each so-called oxml element object in python-docx has an .xml property for precisely this use case. It's used for the internal unit tests.

All you need is access to the internal variable used for the XML element, which is generally available by clicking the [source] link next to that object in the docs, like here: https://python-docx.readthedocs.io/en/latest/api/text.html#paragraph-objects

Clicking through that link, you can find that for a paragraph, the underlying XML element is available on ._p. Usually it's the tagname of the element without the namespace prefix, although sometimes its the generic ._element. This latter one is a good one to try in a pinch if you need to guess.

So using it is as simple as:

>>> paragraph._p.xml
<w:p>
  <w:pPr>
    <w:jc w:val="right"/>
  </w:pPr>
  <w:r>
    <w:t>Right-aligned</w:t>
  </w:r>
</w:p>

There is a companion domain-specific language (DSL) in the unit-test utilities called CXML (compact XML) which allows you to take care of namespacing, which is otherwise a big pain. It looks something like this:

expected_xml = cxml.xml('w:p(w:pPr/w:jc{w:val=right},w:r/w:t"Right-aligned")')

You can see examples throughout the unit tests like here: https://github.com/python-openxml/python-docx/blob/master/tests/text/test_paragraph.py#L113 and ask more specific questions here with the "python-docx" tag if you need help.


来源: stackexchange

问:
EditText is growing as text entered
I have an edittext that is 80% of the screen across and a button that should take the remaining 20%, but when text is entered into the box or removed the edittext grows and shrinks.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical">

   <LinearLayout
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:orientation="horizontal"
      android:weightSum="100">

      <Button
         android:id="@+id/people_relationFilterB"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_weight="20" />

      <EditText
         android:id="@+id/people_searchBoxET"
         android:text="Search Known"
         android:singleLine="true"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_weight="80" />
   </LinearLayout>

   <ListView
     android:id="@+id/people_listLV"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content" />

</LinearLayout>
</code>```

Any Clues? Thanks!

答:
I believe your issue is you are setting the layout width of the EditText as wrap_content.  I had this problem when I started Android development as well. You are essentially telling Android that you want your EditText to size itself to fit the text you entered.

The solution is to set the layout width as fill_parent and then if needed wrap a LinearLayout around it to contain the size.

ContentLicense: CC BY-SA 3.0

Title: EditText is growing as text entered

Body:
I have an edittext that is 80% of the screen across and a button that should take the remaining 20%, but when text is entered into the box or removed the edittext grows and shrinks.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical">

   <LinearLayout
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:orientation="horizontal"
      android:weightSum="100">

      <Button
         android:id="@+id/people_relationFilterB"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_weight="20" />

      <EditText
         android:id="@+id/people_searchBoxET"
         android:text="Search Known"
         android:singleLine="true"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_weight="80" />
   </LinearLayout>

   <ListView
     android:id="@+id/people_listLV"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content" />

</LinearLayout>

Any Clues? Thanks!


问:
How to avoid "Sharing is only supported for boot loader classes because bootstrap classpath has been appended" warning during debug with Java 11?
Recently I switched to the Java 11 and start to debug my app and saw this message:

OpenJDK 64-Bit Server VM warning: Sharing is only supported for boot
  loader classes because bootstrap classpath has been appended

Found only this commit and ticket, but it doesn't tell me much.

Do I need to worry about it?

答:
For me, the issue occurred only when I ran in Docker, and when I used a java command line agent like the DataDog APM agent (-javaagent:/dd-java-agent.jar).
When I ran in my JDK11 runtime environment (without the agent) I did not get the warnings.

ContentLicense: CC BY-SA 4.0


问:
How to do a Mapper and return Single<MyObject>?
I was using a mapper for other object and that's a List and I could do something like :

```<code>return myResponse.getData().map(myMapper(it))
</code>```

And it works, but now, I'm not returning a List<Object> I'm returning an Object but I want to map the object to another object as :

```<code>data class PersonResponse(val id: Int, val name: String, val surname: String, val age: Int, val street: String....)
</code>```

So now I want a PersonViewModel that only contains the name and surname how can I do it? My method is :

```<code>fun execute() : Single<PersonViewModel> { return myResponse.getData() //this returns a Single<PersonResponse>}
</code>```

How do I map this? Or it's not necessary to do that?

Thanks.

答:
just use map:

```<code>fun execute() : Single<PersonViewModel> {
    return myResponse.getData()
        .map { PersonViewModel(it.name, it.surname) }
}
</code>```

or if you have a mapper from PersonResponse to PersonViewModel:

```<code>fun execute() : Single<PersonViewModel> {
    return myResponse.getData()
        .map { personMapper.map(it) }
}
</code>```

Body:
I was using a mapper for other object and that's a List and I could do something like :

return myResponse.getData().map(myMapper(it))

And it works, but now, I'm not returning a List<Object> I'm returning an Object but I want to map the object to another object as :

data class PersonResponse(val id: Int, val name: String, val surname: String, val age: Int, val street: String....)

So now I want a PersonViewModel that only contains the name and surname how can I do it? My method is :

fun execute() : Single<PersonViewModel> { return myResponse.getData() //this returns a Single<PersonResponse>}

How do I map this? Or it's not necessary to do that?

Thanks.

Body:
just use map:

fun execute() : Single<PersonViewModel> {
    return myResponse.getData()
        .map { PersonViewModel(it.name, it.surname) }
}

or if you have a mapper from PersonResponse to PersonViewModel:

fun execute() : Single<PersonViewModel> {
    return myResponse.getData()
        .map { personMapper.map(it) }
}


问:
How to delete edittext dynamically everytime I click a button
I'm trying to add a new food with some add ons, basically everytime the add field button is press it will create two edittext which is the name and price of the add on, there will be a scenario whereby users wants to delete the edittext name and price. I've successfully created two edittexts also setting them with the IDs that i'm giving them in integer. But I'm having problem with deleting the two edittext with a button whenever i click the delete field button.

```<code>
// Add On
        addOnLayout.removeAllViews();
        addFields.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AddOnCounters++;

                etFoodName = new EditText(addfoodAddOn.this);
                etFoodName.setId(ETFoodID);

                etFoodName.setHint("Enter your AddOn Name");

                etPrice = new EditText(addfoodAddOn.this);
                etPrice.setId(ETPriceID);
                etPrice.setHint("Enter your AddOn Price");

                Log.d("-------","-------------------what is edittext name id " + ETFoodID);
                Log.d("-------","-------------------what is edittext price id " + ETPriceID);

                ETFoodID++;
                ETPriceID++;

                addOnLayout.addView(etFoodName);
                addOnLayout.addView(etPrice);

            }
        });

        removeFields.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(AddOnCounters>=1 && ETFoodID > 0 && ETPriceID > 10){

                    addOnLayout.removeViewAt(ETFoodID);
                    addOnLayout.removeViewAt(ETPriceID);
                    ETFoodID--;
                    ETPriceID--;

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

I'm expecting the result to be whenever i click the delete field button, it will delete the very bottom last two edittexts which is the name and price.

答:
Remove it from its parent.</p>

```<code>removeFields.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                removeFromParent(etFoodName);
                removeFromParent(etPrice);
            }
        });

static void removeFromParent(View view) {
    ((ViewGroup)view.getParent()).removeView(view);
}
</code>```

Body:
I'm trying to add a new food with some add ons, basically everytime the add field button is press it will create two edittext which is the name and price of the add on, there will be a scenario whereby users wants to delete the edittext name and price. I've successfully created two edittexts also setting them with the IDs that i'm giving them in integer. But I'm having problem with deleting the two edittext with a button whenever i click the delete field button.

// Add On
        addOnLayout.removeAllViews();
        addFields.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AddOnCounters++;

                etFoodName = new EditText(addfoodAddOn.this);
                etFoodName.setId(ETFoodID);

                etFoodName.setHint("Enter your AddOn Name");

                etPrice = new EditText(addfoodAddOn.this);
                etPrice.setId(ETPriceID);
                etPrice.setHint("Enter your AddOn Price");

                Log.d("-------","-------------------what is edittext name id " + ETFoodID);
                Log.d("-------","-------------------what is edittext price id " + ETPriceID);

                ETFoodID++;
                ETPriceID++;

                addOnLayout.addView(etFoodName);
                addOnLayout.addView(etPrice);

            }
        });

        removeFields.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(AddOnCounters>=1 && ETFoodID > 0 && ETPriceID > 10){

                    addOnLayout.removeViewAt(ETFoodID);
                    addOnLayout.removeViewAt(ETPriceID);
                    ETFoodID--;
                    ETPriceID--;

                }
            }
        });

I'm expecting the result to be whenever i click the delete field button, it will delete the very bottom last two edittexts which is the name and price.

Body:
Remove it from its parent.

removeFields.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                removeFromParent(etFoodName);
                removeFromParent(etPrice);
            }
        });

static void removeFromParent(View view) {
    ((ViewGroup)view.getParent()).removeView(view);
}


问:
how to get descriptive error messages from embedded cassandra
I am using embedded cassandra to run unit tests. I notice that if any cql statements fail, then I don't see any descriptive reason for failure. For eg. I am running the following two statements which fails because I am trying to add a table without switching to a keyspace

```<code>val statement1 =
        """
          |CREATE KEYSPACE test
          |  WITH REPLICATION = {
          |   'class' : 'SimpleStrategy',
          |   'replication_factor' : 1
          |  };
        """.stripMargin

      val statement3 =
        """
            |CREATE TABLE users (
            |    bucket int,
            |    email text,
            |    firstname text,
            |    lastname text,
            |    authprovider text,
            |    password text,
            |    confirmed boolean,
            |    id UUID,
            |    hasher text,
            |    salt text,
            |    PRIMARY KEY ((bucket, email), authprovider,firstname, lastname) )
        """.stripMargin

val cqlStatements:CqlStatements = new CqlStatements(statement1,statement3)

")
      val testCassandra = repoTestEnv.testCassandra

      try {
        testCassandra.start()
        testCassandra.executeScripts(cqlStatements)
      } finally testCassandra.stop()
</code>```

But I don't see correct error. I see the following which doesn't tell exactly what is the problem

```<code>[info] c.g.n.e.c.l.WindowsCassandraNode - Apache Cassandra Node '7276' is started
[info] c.g.n.e.c.l.LocalCassandraDatabase - Apache Cassandra '3.11.1' is started (20811 ms)
[warn] c.d.d.c.Connection - /127.0.0.1:9042 did not send an authentication challenge; This is suspicious because the driver expects authentication (configured auth provider = com.datastax.driver.core.PlainTextAuthProvider)
[warn] c.d.d.c.Connection - /127.0.0.1:9042 did not send an authentication challenge; This is suspicious because the driver expects authentication (configured auth provider = com.datastax.driver.core.PlainTextAuthProvider)
[debug] c.g.n.e.c.t.u.CqlUtils - Executing Script: CqlStatements [
CREATE KEYSPACE test
  WITH REPLICATION = {
   'class' : 'SimpleStrategy',
   'replication_factor' : 1
  };
        ,
CREATE TABLE users (
    bucket int,
    email text,
    firstname text,
    lastname text,
    authprovider text,
    password text,
    confirmed boolean,
    id UUID,
    hasher text,
    salt text,
    PRIMARY KEY ((bucket, email), authprovider,firstname, lastname) )
        ]
[debug] c.g.n.e.c.t.u.CqlUtils - Executing Statement:
CREATE KEYSPACE test
  WITH REPLICATION = {
   'class' : 'SimpleStrategy',
   'replication_factor' : 1
  };

[info] c.g.n.e.c.Cassandra - INFO  [Native-Transport-Requests-1] 2019-05-29 07:50:00,788 MigrationManager.java:310 - Create new Keyspace: KeyspaceMetadata{name=test, params=KeyspaceParams{durable_writes=true, replication=ReplicationParams{class=org.apache.cassandra.locator.SimpleStrategy, replication_factor=1}}, tables=[], views=[], functions=[], types=[]}
[debug] c.g.n.e.c.t.u.CqlUtils - Executing Statement:
CREATE TABLE users (
    bucket int,
    email text,
    firstname text,
    lastname text,
    authprovider text,
    password text,
    confirmed boolean,
    id UUID,
    hasher text,
    salt text,
    PRIMARY KEY ((bucket, email), authprovider,firstname, lastname) )

[debug] c.g.n.e.c.t.TestCassandra - Stop TestCassandra 3.11.1
[info] c.g.n.e.c.l.LocalCassandraDatabase - Stop Apache Cassandra '3.11.1'
[debug] c.g.n.e.c.l.RunProcess - Execute 'powershell -ExecutionPolicy Unrestricted C:\Users\manu\AppData\Local\Temp\embedded-cassandra\3.11.1\0d155e04-97d5-4927-87ac-d46824a77c32\bin\stop-server.ps1 -p C:\Users\manu\AppData\Local\Temp\embedded-cassandra\3.11.1\0d155e04-97d5-4927-87ac-d46824a77c32\1da63488-2624-4141-a49e-174203b7edc4' within a directory 'C:\Users\manu\AppData\Local\Temp\embedded-cassandra\3.11.1\0d155e04-97d5-4927-87ac-d46824a77c32'
[info] c.g.n.e.c.Cassandra - INFO  [StorageServiceShutdownHook] 2019-05-29 07:50:03,926 HintsService.java:220 - Paused hints dispatch
[info] c.g.n.e.c.Cassandra - INFO  [StorageServiceShutdownHook] 2019-05-29 07:50:03,933 Server.java:176 - Stop listening for CQL clients
[info] c.g.n.e.c.Cassandra - INFO  [StorageServiceShutdownHook] 2019-05-29 07:50:03,934 Gossiper.java:1532 - Announcing shutdown
[info] c.g.n.e.c.Cassandra - INFO  [StorageServiceShutdownHook] 2019-05-29 07:50:03,938 StorageService.java:2268 - Node localhost/127.0.0.1 state jump to shutdown
[info] c.g.n.e.c.Cassandra - INFO  [StorageServiceShutdownHook] 2019-05-29 07:50:05,941 MessagingService.java:984 - Waiting for messaging service to quiesce
[info] c.g.n.e.c.Cassandra - INFO  [ACCEPT-localhost/127.0.0.1] 2019-05-29 07:50:05,948 MessagingService.java:1338 - MessagingService has terminated the accept() thread
[info] c.g.n.e.c.Cassandra - INFO  [StorageServiceShutdownHook] 2019-05-29 07:50:06,076 HintsService.java:220 - Paused hints dispatch
[info] c.g.n.e.c.l.WindowsCassandraNode - Successfully sent ctrl+c to process with id: 7276.
[info] c.g.n.e.c.l.WindowsCassandraNode - Apache Cassandra Node '7276' is stopped
[info] c.g.n.e.c.l.LocalCassandraDatabase - Apache Cassandra '3.11.1' is stopped (3490 ms)
[info] c.g.n.e.c.l.LocalCassandraDatabase - The working directory 'C:\Users\manu\AppData\Local\Temp\embedded-cassandra\3.11.1\0d155e04-97d5-4927-87ac-d46824a77c32' was deleted.
[debug] c.g.n.e.c.t.TestCassandra - TestCassandra 3.11.1 is stopped

Unable to start TestCassandra 3.11.1
com.github.nosan.embedded.cassandra.CassandraException: Unable to start TestCassandra 3.11.1
    at com.github.nosan.embedded.cassandra.test.TestCassandra.start(TestCassandra.java:128)
    at UnitSpecs.RepositorySpecs.UsersRepositorySpecs.$anonfun$new$3(UsersRepositorySpecs.scala:146)
    at org.scalatest.OutcomeOf.outcomeOf(OutcomeOf.scala:85)
</code>```

Ideally I should get the error similar to what I would get if I was using cqlsh

Is there a way to get more descriptive errors?

答:
I found the reason. I wasn't using TestCassandra correctly it seems. I didn't realize that if I create TestCassandra and also specify the cql statements at time of instantiation, the start method runs the queries as well. In my code, I was creating TestCassandra as follows

new TestCassandra(factory,cqlStatements)})

and was calling both start and executeScripts

```<code>testCassandra.start()
testCassandra.executeScripts(cqlStatements)
</code>```

I commented that executeScripts line and I now see both Exception and Caused

I think it would be better if the APIs clearly mention that start has side effect of executing statements as well.

Body:
I am using embedded cassandra to run unit tests. I notice that if any cql statements fail, then I don't see any descriptive reason for failure. For eg. I am running the following two statements which fails because I am trying to add a table without switching to a keyspace

val statement1 =
        """
          |CREATE KEYSPACE test
          |  WITH REPLICATION = {
          |   'class' : 'SimpleStrategy',
          |   'replication_factor' : 1
          |  };
        """.stripMargin

      val statement3 =
        """
            |CREATE TABLE users (
            |    bucket int,
            |    email text,
            |    firstname text,
            |    lastname text,
            |    authprovider text,
            |    password text,
            |    confirmed boolean,
            |    id UUID,
            |    hasher text,
            |    salt text,
            |    PRIMARY KEY ((bucket, email), authprovider,firstname, lastname) )
        """.stripMargin

val cqlStatements:CqlStatements = new CqlStatements(statement1,statement3)

")
      val testCassandra = repoTestEnv.testCassandra

      try {
        testCassandra.start()
        testCassandra.executeScripts(cqlStatements)
      } finally testCassandra.stop()

But I don't see correct error. I see the following which doesn't tell exactly what is the problem

[info] c.g.n.e.c.l.WindowsCassandraNode - Apache Cassandra Node '7276' is started
[info] c.g.n.e.c.l.LocalCassandraDatabase - Apache Cassandra '3.11.1' is started (20811 ms)
[warn] c.d.d.c.Connection - /127.0.0.1:9042 did not send an authentication challenge; This is suspicious because the driver expects authentication (configured auth provider = com.datastax.driver.core.PlainTextAuthProvider)
[warn] c.d.d.c.Connection - /127.0.0.1:9042 did not send an authentication challenge; This is suspicious because the driver expects authentication (configured auth provider = com.datastax.driver.core.PlainTextAuthProvider)
[debug] c.g.n.e.c.t.u.CqlUtils - Executing Script: CqlStatements [
CREATE KEYSPACE test
  WITH REPLICATION = {
   'class' : 'SimpleStrategy',
   'replication_factor' : 1
  };
        ,
CREATE TABLE users (
    bucket int,
    email text,
    firstname text,
    lastname text,
    authprovider text,
    password text,
    confirmed boolean,
    id UUID,
    hasher text,
    salt text,
    PRIMARY KEY ((bucket, email), authprovider,firstname, lastname) )
        ]
[debug] c.g.n.e.c.t.u.CqlUtils - Executing Statement:
CREATE KEYSPACE test
  WITH REPLICATION = {
   'class' : 'SimpleStrategy',
   'replication_factor' : 1
  };

[info] c.g.n.e.c.Cassandra - INFO  [Native-Transport-Requests-1] 2019-05-29 07:50:00,788 MigrationManager.java:310 - Create new Keyspace: KeyspaceMetadata{name=test, params=KeyspaceParams{durable_writes=true, replication=ReplicationParams{class=org.apache.cassandra.locator.SimpleStrategy, replication_factor=1}}, tables=[], views=[], functions=[], types=[]}
[debug] c.g.n.e.c.t.u.CqlUtils - Executing Statement:
CREATE TABLE users (
    bucket int,
    email text,
    firstname text,
    lastname text,
    authprovider text,
    password text,
    confirmed boolean,
    id UUID,
    hasher text,
    salt text,
    PRIMARY KEY ((bucket, email), authprovider,firstname, lastname) )

[debug] c.g.n.e.c.t.TestCassandra - Stop TestCassandra 3.11.1
[info] c.g.n.e.c.l.LocalCassandraDatabase - Stop Apache Cassandra '3.11.1'
[debug] c.g.n.e.c.l.RunProcess - Execute 'powershell -ExecutionPolicy Unrestricted C:\Users\manu\AppData\Local\Temp\embedded-cassandra\3.11.1\0d155e04-97d5-4927-87ac-d46824a77c32\bin\stop-server.ps1 -p C:\Users\manu\AppData\Local\Temp\embedded-cassandra\3.11.1\0d155e04-97d5-4927-87ac-d46824a77c32\1da63488-2624-4141-a49e-174203b7edc4' within a directory 'C:\Users\manu\AppData\Local\Temp\embedded-cassandra\3.11.1\0d155e04-97d5-4927-87ac-d46824a77c32'
[info] c.g.n.e.c.Cassandra - INFO  [StorageServiceShutdownHook] 2019-05-29 07:50:03,926 HintsService.java:220 - Paused hints dispatch
[info] c.g.n.e.c.Cassandra - INFO  [StorageServiceShutdownHook] 2019-05-29 07:50:03,933 Server.java:176 - Stop listening for CQL clients
[info] c.g.n.e.c.Cassandra - INFO  [StorageServiceShutdownHook] 2019-05-29 07:50:03,934 Gossiper.java:1532 - Announcing shutdown
[info] c.g.n.e.c.Cassandra - INFO  [StorageServiceShutdownHook] 2019-05-29 07:50:03,938 StorageService.java:2268 - Node localhost/127.0.0.1 state jump to shutdown
[info] c.g.n.e.c.Cassandra - INFO  [StorageServiceShutdownHook] 2019-05-29 07:50:05,941 MessagingService.java:984 - Waiting for messaging service to quiesce
[info] c.g.n.e.c.Cassandra - INFO  [ACCEPT-localhost/127.0.0.1] 2019-05-29 07:50:05,948 MessagingService.java:1338 - MessagingService has terminated the accept() thread
[info] c.g.n.e.c.Cassandra - INFO  [StorageServiceShutdownHook] 2019-05-29 07:50:06,076 HintsService.java:220 - Paused hints dispatch
[info] c.g.n.e.c.l.WindowsCassandraNode - Successfully sent ctrl+c to process with id: 7276.
[info] c.g.n.e.c.l.WindowsCassandraNode - Apache Cassandra Node '7276' is stopped
[info] c.g.n.e.c.l.LocalCassandraDatabase - Apache Cassandra '3.11.1' is stopped (3490 ms)
[info] c.g.n.e.c.l.LocalCassandraDatabase - The working directory 'C:\Users\manu\AppData\Local\Temp\embedded-cassandra\3.11.1\0d155e04-97d5-4927-87ac-d46824a77c32' was deleted.
[debug] c.g.n.e.c.t.TestCassandra - TestCassandra 3.11.1 is stopped

Unable to start TestCassandra 3.11.1
com.github.nosan.embedded.cassandra.CassandraException: Unable to start TestCassandra 3.11.1
    at com.github.nosan.embedded.cassandra.test.TestCassandra.start(TestCassandra.java:128)
    at UnitSpecs.RepositorySpecs.UsersRepositorySpecs.$anonfun$new$3(UsersRepositorySpecs.scala:146)
    at org.scalatest.OutcomeOf.outcomeOf(OutcomeOf.scala:85)

Ideally I should get the error similar to what I would get if I was using cqlsh

Is there a way to get more descriptive errors?

Body:
I found the reason. I wasn't using TestCassandra correctly it seems. I didn't realize that if I create TestCassandra and also specify the cql statements at time of instantiation, the start method runs the queries as well. In my code, I was creating TestCassandra as follows

new TestCassandra(factory,cqlStatements)})

and was calling both start and executeScripts

testCassandra.start()
testCassandra.executeScripts(cqlStatements)

I commented that executeScripts line and I now see both Exception and Caused

I think it would be better if the APIs clearly mention that start has side effect of executing statements as well.


问:
How to convert parts of a line to uppercase in a file
I have a file file.txt and it has the lines below. I want the queuename to be converted to uppercase, like this: queuename=SP00245B

```<code>    # Queue name
    #
    queuename=sp00245b
</code>```

答:
A simple Perl solution:

```<code>perl -i -pe 's/^\s*queuename=\K(.*)/\U$1/' file.txt
</code>```

(Remove -i if you don't want to modify the file in place.)

Body:
I have a file file.txt and it has the lines below. I want the queuename to be converted to uppercase, like this: queuename=SP00245B

    # Queue name
    #
    queuename=sp00245b

Body:
A simple Perl solution:

perl -i -pe 's/^\s*queuename=\K(.*)/\U$1/' file.txt

(Remove -i if you don't want to modify the file in place.)


问:
Dropdown onchange isn't fired
I need help with this select, it's populated with db and I need to get the item selected when change the item.

<select class="custom-select col-md-12" id="operation" name="operation" formControlName="operation">
  <option *ngFor="let operation of operations" [ngValue]="operation.id" (ngModelChange)="show(operation)">{{ operation.value}}</option>
</select>```
</div>
</div>
</p>

```show(value){
   ...
}
```

I already tried with (change) and [(ngModel)] but it doesn't work.

答:
The change event should be in <select> tag:

<select class="custom-select col-md-12" id="operation"
(ngModelChange)="show($event)" name="operation" formControlName="operation">
  <option *ngFor="let operation of operations" [ngValue]="operation.id" \>
  {{ operation.value}}
  </option>
</select>```

Title: Dropdown onchange isn't fired

Body:
I need help with this select, it's populated with db and I need to get the item selected when change the item.

<select class="custom-select col-md-12" id="operation" name="operation" formControlName="operation">
  <option *ngFor="let operation of operations" [ngValue]="operation.id" (ngModelChange)="show(operation)">{{ operation.value}}</option>
</select>

show(value){
   ...
}

I already tried with (change) and [(ngModel)] but it doesn't work.


问:
How do I insert into non-default Google Calendar using Zend / PHP
I'm trying to insert a new event into Google Calendar, which I can do fine by the following:

```<code>$sname = Zend_Gdata_Calendar::AUTH_SERVICE_NAME; // predefined service name for calendar
$client = Zend_Gdata_ClientLogin::getHttpClient($userName,$password,$sname);
$service = new Zend_Gdata_Calendar($client);

$event = $service->newEventEntry();
$event->title = $service->newTitle($name);
$event->when = array($when);
$newEvent = $service->insertEvent($event);
</code>```

However, this will only insert into the default calendar.  I am trying to use the URI argument of insertEvent to get where I need to go:

```<code>$uri = "http://www.google.com/calendar/feeds/default/something@somethingelse.com/private/full";
$newEvent = $service->insertEvent($event, $uri);
</code>```

This hasn't worked.  I've tried encoding and decoding the URI, which gives me different error messages, but I just can't get this to work.  I've been Googling solutions for hours now with no luck.  Can anyone help?

Thanks.
- Dave

答:
Found the issue:
The URI above doesn't work:
"http://www.google.com/calendar/feeds/default/something@somethingelse.com/private/full";

should not have the default section there.

Also, the @ sign should be replaced by encoding.  So it should be:
"http://www.google.com/calendar/feeds/something%40somethingelse.com/private/full";

OwnerDisplayName: davearchie

Body:
I'm trying to insert a new event into Google Calendar, which I can do fine by the following:

$sname = Zend_Gdata_Calendar::AUTH_SERVICE_NAME; // predefined service name for calendar
$client = Zend_Gdata_ClientLogin::getHttpClient($userName,$password,$sname);
$service = new Zend_Gdata_Calendar($client);

$event = $service->newEventEntry();
$event->title = $service->newTitle($name);
$event->when = array($when);
$newEvent = $service->insertEvent($event);

However, this will only insert into the default calendar.  I am trying to use the URI argument of insertEvent to get where I need to go:

$uri = "http://www.google.com/calendar/feeds/default/something@somethingelse.com/private/full";
$newEvent = $service->insertEvent($event, $uri);

This hasn't worked.  I've tried encoding and decoding the URI, which gives me different error messages, but I just can't get this to work.  I've been Googling solutions for hours now with no luck.  Can anyone help?

Thanks.
- Dave

ContentLicense: CC BY-SA 2.5


问:
Why does my Selenium command not work?
I'm writing a selenium script that should only start testing after all ajax calls have completed.

Several forums have suggested that I use the following condition (in the waitForCondition command):

```<code>selenium.browserbot.getCurrentWindow().jQuery.active == 0
</code>```

Unfortunately this keeps throwing an error:

jQuery is undefined

JQuery is definitely defined on my site. I have also tried substituting the jQuery with $, but get the same error.

Any ideas?

答:
You might need to wait for jQuery to have finished loading, try waiting until

```<code>typeof selenium.browserbot.getCurrentWindow().jQuery == 'function'
</code>```

is true, before checking active.

Title: Why does my Selenium command not work?

Body:
I'm writing a selenium script that should only start testing after all ajax calls have completed.

Several forums have suggested that I use the following condition (in the waitForCondition command):

selenium.browserbot.getCurrentWindow().jQuery.active == 0

Unfortunately this keeps throwing an error:

jQuery is undefined

JQuery is definitely defined on my site. I have also tried substituting the jQuery with $, but get the same error.

Any ideas?

Body:
You might need to wait for jQuery to have finished loading, try waiting until

typeof selenium.browserbot.getCurrentWindow().jQuery == 'function'

is true, before checking active.


问:
JS: delete first element from array by value
I have an array:

```<code>arr = [50, 40, 50, 50];
</code>```

I need to delete first element, that equal 50 and dont touch another.
This code return only [40].

```<code>arr = arr.filter(function(e) {return e !== 50}) // [40]
</code>```

But I need

```<code>arr = arr.somefunction(function(e) {return e !== 50}) // [40, 50, 50]
</code>```

I would be grateful for any help.

答:
You could take a flag and change it of the first value is found.

var array = [40, 40, 50, 40, 50, 40, 50],
    found = false;

array = array.filter(v => found || !(found = v === 50));

console.log(array);```
</div>
</div>
</p>

<p>With a counter, you could specify the amount of value for filtering out.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var array = [40, 40, 50, 40, 50, 40, 50],
    count = 1;

array = array.filter(v => !count || (count -= v === 50));

console.log(array);</code>```

Body:
I have an array:

arr = [50, 40, 50, 50];

I need to delete first element, that equal 50 and dont touch another.
This code return only [40].

arr = arr.filter(function(e) {return e !== 50}) // [40]

But I need

arr = arr.somefunction(function(e) {return e !== 50}) // [40, 50, 50]

I would be grateful for any help.

Body:
You could take a flag and change it of the first value is found.

var array = [40, 40, 50, 40, 50, 40, 50],
    found = false;

array = array.filter(v => found || !(found = v === 50));

console.log(array);

With a counter, you could specify the amount of value for filtering out.

var array = [40, 40, 50, 40, 50, 40, 50],
    count = 1;

array = array.filter(v => !count || (count -= v === 50));

console.log(array);


问:
Wordpress too many redirects issue on localhost
I am facing the issue as described in the title. I am working on a Woocommerce site with default WP Twenty Nineteen. Everything was working fine but I have mistyped https in the WP admin General Settings Site Url field. This caused too_many_redirects error on both Chrome and Mozilla. I have tried clearing cookies and complete browsing data, disabling plugins, changing permalinks and deleting htaccess file but none of this worked. Maybe this can help but strangely I can access admin but cannot see none of the pages. Any help would be appreciated. Thanks! </p>

答:
In wp-config.php add this 2 lines (with your protocol+domain_name):</p>

```<code>define('WP_HOME','https://yourdomain.com');
define('WP_SITEURL','https://yourdomain.com');
</code>```

Body:
In wp-config.php add this 2 lines (with your protocol+domain_name):

define('WP_HOME','https://yourdomain.com');
define('WP_SITEURL','https://yourdomain.com');


问:
SQLite update sets column's value instead of given value. How to fix it?
I'm trying to update some values in a sqlite table. In the update query if some of the fields has the name of a table's column, the value ends up as the value of that column instead of the given value.

I tried looking for an answer on other question but didn't find any. I don't know if I'm mising a concept here or there is a sqlite limitation.

My table looks like this:

```<code>CREATE TABLE product (
    id INTEGER PRIMARY KEY,
    name TEXT,
    barcode TEXT,
    sku TEXT
)
</code>```

Lets say I add an example product with the following query:

INSERT INTO product (id, name, barcode, sku) VALUES (1, "Product Example", "2095063206626", "SKU912132151")

Whenever I try to update it with a query that includes a value that references a column name, for example:

UPDATE product SET name = "Product edited", barcode = "ID", sku = "BARCODE" WHERE id = 1

It sets the value as the column's current value for the given row, and I end up with this object on the database:

```<code>{
    "id" = 1
    "name" = "Product edited"
    "barcode" = 1
    "sku" = "2095063206626"
}
</code>```

And I'm actually expecting this:

```<code>{
    "id" = 1
    "name" = "Product edited"
    "barcode" = "ID"
    "sku" = "BARCODE"
}
</code>```

Any ideas?

答: Problem was caused by using double quotes for strings in the query. Double quotes are used for identifiers in sqlite, as pointed out by @Shawn.</p>

Body:
I'm trying to update some values in a sqlite table. In the update query if some of the fields has the name of a table's column, the value ends up as the value of that column instead of the given value.

I tried looking for an answer on other question but didn't find any. I don't know if I'm mising a concept here or there is a sqlite limitation.

My table looks like this:

CREATE TABLE product (
    id INTEGER PRIMARY KEY,
    name TEXT,
    barcode TEXT,
    sku TEXT
)

Lets say I add an example product with the following query:

INSERT INTO product (id, name, barcode, sku) VALUES (1, "Product Example", "2095063206626", "SKU912132151")

Whenever I try to update it with a query that includes a value that references a column name, for example:

UPDATE product SET name = "Product edited", barcode = "ID", sku = "BARCODE" WHERE id = 1

It sets the value as the column's current value for the given row, and I end up with this object on the database:

{
    "id" = 1
    "name" = "Product edited"
    "barcode" = 1
    "sku" = "2095063206626"
}

And I'm actually expecting this:

{
    "id" = 1
    "name" = "Product edited"
    "barcode" = "ID"
    "sku" = "BARCODE"
}

Any ideas?


问:
Get character and string from the user
I'm trying to get the character and string from the user.But it gets only character and doesn't get the string.</p>

```<code>    Scanner in=new Scanner(System.in);
    String s;
    System.out.println("Enter a string");
    char c = in.next().charAt(0);
    System.out.println(c);
    s = in.nextLine();
    System.out.println(s);
</code>```

答:
When you call next() with the scanner, you are getting the entire string until the next complete token. The next time you call nextLine(), the string you were after is gone. Assuming the character you want is at the start of the string, you should get the string, and then get the character from the string.

```<code>s = in.nextLine();

char c = s.charAt(0);
</code>```

Title: Get character and string from the user

Body:
I'm trying to get the character and string from the user.But it gets only character and doesn't get the string.

    Scanner in=new Scanner(System.in);
    String s;
    System.out.println("Enter a string");
    char c = in.next().charAt(0);
    System.out.println(c);
    s = in.nextLine();
    System.out.println(s);

Body:
When you call next() with the scanner, you are getting the entire string until the next complete token. The next time you call nextLine(), the string you were after is gone. Assuming the character you want is at the start of the string, you should get the string, and then get the character from the string.

s = in.nextLine();

char c = s.charAt(0);


答:
Try with this: </p>

```<code>    public static void main(String args[]) // start of main
     {
      Scanner in=new Scanner(System.in);
      String s;
      System.out.println("Enter a char");
      char c = in.next().charAt(0);
      System.out.println(c);
      System.out.println("Enter the String");
      s = in.next();
      System.out.println(s);
   }
</code>```

Title: Get character and string from the user

Body:
Try with this:

    public static void main(String args[]) // start of main
     {
      Scanner in=new Scanner(System.in);
      String s;
      System.out.println("Enter a char");
      char c = in.next().charAt(0);
      System.out.println(c);
      System.out.println("Enter the String");
      s = in.next();
      System.out.println(s);
   }


问:
sql stores different value then I store
I am using sql server 2005 and .NET.
I have a table with float column named "price".
When I stores 1890 it store 1889.99966796875.

What is the reason?

答:
A floating point number is a special data type used for storing numbers of widely varying ranges. The trade off is in precision - which is what you are seeing as a problem.
Floating point numbers

You may want to store your values with the decimal data type, or money instead.

Title: sql stores different value then I store


问:
How to fix has_one / through association problem?
I'm working on a new project. My structure of data :
-Audits
-Actions
-Reponses

A audit is composed of actions.
Each action have one reponse.
Each reponse is referenced to a action and a audit.

Audit

```<code>class Audit < ApplicationRecord

  belongs_to :entreprise
  has_many :reponse
  has_many :action, through: :reponse

  validates :numero, presence: true, uniqueness: true

end
</code>```

Action

```<code>class Action < ApplicationRecord

  has_one :reponse
  has_many :audits, through: :reponse

  validates :numero, :titre, presence: true, uniqueness: true
  validates :description, :kpi, :priority, :scale, :effectSocial, :effectEnvironmental, :effectFinancial, :impactCC, :impactD, :impactE, :impactRNN, presence: true

end
</code>```

Reponse

```<code>class Reponse < ApplicationRecord

  belongs_to :audit
  belongs_to :action

end
</code>```

I think I am pretty close, but when I launch rails console, add some data and try to add a reponse with :

Action.first.create_reponse(etat: "fine", kpi: 2, commentaire: "")

I got this :

```<code>Action Load (2.0ms)  SELECT  "actions".* FROM "actions" ORDER BY "actions"."id" ASC LIMIT ?  [["LIMIT", 1]]
   (0.5ms)  begin transaction
   (0.1ms)  rollback transaction
  Reponse Load (0.2ms)  SELECT  "reponses".* FROM "reponses" WHERE "reponses"."action_id" = ? LIMIT ?  [["action_id", 1], ["LIMIT", 1]]
 => #<Reponse id: nil, commentaire: "", etat: "fine", kpi: 2, created_at: nil, updated_at: nil, action_id: 1, audit_id: nil> ```
```

答:
If an object belongs_to another object, it needs that object's ID. So in your case, a Response would need an audit_id and an action_id.

When you try and create a response, it's failing because it doesn't have an audit_id. Your two options are to either add one into the line where you create the response:

```<code>Action.first.create_reponse(etat: "fine", kpi: 2, commentaire: "", audit_id: Audit.first.id)
</code>```

Or to change your belongs_to to belongs_to, required: false. This will allow you to save the response without an audit ID, however given how you've laid out your data, it appears you want to enforce this relationship and go with the first option.

Body:
I'm working on a new project. My structure of data :
-Audits
-Actions
-Reponses

A audit is composed of actions.
Each action have one reponse.
Each reponse is referenced to a action and a audit.

Audit

class Audit < ApplicationRecord

  belongs_to :entreprise
  has_many :reponse
  has_many :action, through: :reponse

  validates :numero, presence: true, uniqueness: true

end

Action

class Action < ApplicationRecord

  has_one :reponse
  has_many :audits, through: :reponse

  validates :numero, :titre, presence: true, uniqueness: true
  validates :description, :kpi, :priority, :scale, :effectSocial, :effectEnvironmental, :effectFinancial, :impactCC, :impactD, :impactE, :impactRNN, presence: true

end

Reponse

class Reponse < ApplicationRecord

  belongs_to :audit
  belongs_to :action

end

I think I am pretty close, but when I launch rails console, add some data and try to add a reponse with :

Action.first.create_reponse(etat: "fine", kpi: 2, commentaire: "")

I got this :

Action Load (2.0ms)  SELECT  "actions".* FROM "actions" ORDER BY "actions"."id" ASC LIMIT ?  [["LIMIT", 1]]
   (0.5ms)  begin transaction
   (0.1ms)  rollback transaction
  Reponse Load (0.2ms)  SELECT  "reponses".* FROM "reponses" WHERE "reponses"."action_id" = ? LIMIT ?  [["action_id", 1], ["LIMIT", 1]]
 => #<Reponse id: nil, commentaire: "", etat: "fine", kpi: 2, created_at: nil, updated_at: nil, action_id: 1, audit_id: nil> ```

Body:
If an object belongs_to another object, it needs that object's ID. So in your case, a Response would need an audit_id and an action_id.

When you try and create a response, it's failing because it doesn't have an audit_id. Your two options are to either add one into the line where you create the response:

Action.first.create_reponse(etat: "fine", kpi: 2, commentaire: "", audit_id: Audit.first.id)

Or to change your belongs_to to belongs_to, required: false. This will allow you to save the response without an audit ID, however given how you've laid out your data, it appears you want to enforce this relationship and go with the first option.


问:
Getting RowID after inserting in Room Persistence Library Android Studio
I've been using the codelabs for my Room Database Persistence. Now I am trying to get the latest rowID after inserting data into my room database. However, I am stuck in my repository trying to return the rowID from my AsyncTask.

LogEntity.java

```<code>@Entity
public class LogEntity {
    @PrimaryKey(autoGenerate = true)
    private int id;
</code>```

LogDao.java

```<code>public interface LogDao {
    @Insert
    long insert(LogEntity logEntity);
</code>```

LogDatabase.java

```<code>@Database(entities = LogEntity.class, version = 1)
public abstract class LogDatabase extends RoomDatabase {

    private static LogDatabase instance;
    public abstract  LogDao logDao();

    public static synchronized LogDatabase getInstance(Context context){
        if (instance == null){
            instance = Room.databaseBuilder(context.getApplicationContext(),
                    LogDatabase.class, "log_database").
                    fallbackToDestructiveMigration().build();
        }
        return instance;
    }
}
</code>```

LogRepository.java

```<code>    public long insertLogs(LogEntity logEntity) {
        new InsertLogAsyncTask(logDao).execute(logEntity);
        return **
    }
    private static class InsertLogAsyncTask extends AsyncTask<LogEntity, Void, Long>{
        private LogDao logDao;
        private InsertLogAsyncTask(LogDao logDao){
            this.logDao = logDao;
        }
        @Override
        protected Long doInBackground(LogEntity... logEntities) {
            logDao.insert(logEntities[0]);
            return logDao.insert(logEntities[0]);
        }
    }
</code>```

I put two asterisks because I'm not sure what to do here in order to get the insert RowID and whether my AsyncTask is completely correct.

LogViewModel.java

```<code>    public long insertLog(LogEntity logEntity){
        return repository.insertLogs(logEntity);
    }
</code>```

MainActivity.java

```<code>        long id = logViewModel.insertLog(logEntity);
</code>```

I want to be able to use this final id variable for future use.

答:
You are on the right track but not quite there.
You should declare the AsyncTask class as an inner class of the ViewModel and not the DB.

In the ViewModel add an ID variable and in the AsyncTask add the onPostExecute override to handle the execution result.

LogViewModel.java

```<code>long mLastInsertedID;

private static class InsertLogAsyncTask extends AsyncTask<LogEntity, Void, Long>{
    private LogDao logDao;
    private InsertLogAsyncTask(LogDao logDao){
        this.logDao = logDao;
    }
    @Override
    protected Long doInBackground(LogEntity... logEntities) {
        //you are now off the UI thread
        logDao.insert(logEntities[0]);
        return logDao.insert(logEntities[0]);
    }

    @Override
    protected void onPostExecute(Long result) {
        //Do whatever you like with the result as you are back on the UI thread
        mLastInsertedID = result;
    }
}
</code>```

Body:
I've been using the codelabs for my Room Database Persistence. Now I am trying to get the latest rowID after inserting data into my room database. However, I am stuck in my repository trying to return the rowID from my AsyncTask.

LogEntity.java

@Entity
public class LogEntity {
    @PrimaryKey(autoGenerate = true)
    private int id;

LogDao.java

public interface LogDao {
    @Insert
    long insert(LogEntity logEntity);

LogDatabase.java

@Database(entities = LogEntity.class, version = 1)
public abstract class LogDatabase extends RoomDatabase {

    private static LogDatabase instance;
    public abstract  LogDao logDao();

    public static synchronized LogDatabase getInstance(Context context){
        if (instance == null){
            instance = Room.databaseBuilder(context.getApplicationContext(),
                    LogDatabase.class, "log_database").
                    fallbackToDestructiveMigration().build();
        }
        return instance;
    }
}

LogRepository.java

    public long insertLogs(LogEntity logEntity) {
        new InsertLogAsyncTask(logDao).execute(logEntity);
        return **
    }
    private static class InsertLogAsyncTask extends AsyncTask<LogEntity, Void, Long>{
        private LogDao logDao;
        private InsertLogAsyncTask(LogDao logDao){
            this.logDao = logDao;
        }
        @Override
        protected Long doInBackground(LogEntity... logEntities) {
            logDao.insert(logEntities[0]);
            return logDao.insert(logEntities[0]);
        }
    }

I put two asterisks because I'm not sure what to do here in order to get the insert RowID and whether my AsyncTask is completely correct.

LogViewModel.java

    public long insertLog(LogEntity logEntity){
        return repository.insertLogs(logEntity);
    }

MainActivity.java

        long id = logViewModel.insertLog(logEntity);

I want to be able to use this final id variable for future use.

Body:
You are on the right track but not quite there.
You should declare the AsyncTask class as an inner class of the ViewModel and not the DB.

In the ViewModel add an ID variable and in the AsyncTask add the onPostExecute override to handle the execution result.

LogViewModel.java

long mLastInsertedID;

private static class InsertLogAsyncTask extends AsyncTask<LogEntity, Void, Long>{
    private LogDao logDao;
    private InsertLogAsyncTask(LogDao logDao){
        this.logDao = logDao;
    }
    @Override
    protected Long doInBackground(LogEntity... logEntities) {
        //you are now off the UI thread
        logDao.insert(logEntities[0]);
        return logDao.insert(logEntities[0]);
    }

    @Override
    protected void onPostExecute(Long result) {
        //Do whatever you like with the result as you are back on the UI thread
        mLastInsertedID = result;
    }
}


问:
How does my MVC controller query one database table before writing to another?
I am working on a custom Joomla MVC component.

My view has a form where the user enters an ID. I have retrieved the ID ($input_id) in the controller. Now I need to query the database to get the name WHERE ID = $input_id, then write the name to a different database table.

Can this all be done within the controller or do I have to pass my variables to the model somehow? Not sure of the correct way to achieve this within the MVC framework.

答:
All data and data manipulation should be done in the model (e.g. model your data). The controller is there to determine the path of execution and which methods should be called (e.g. the manager aka controller determines what needs to be done).

Have a look at this tutorial which will help you understand MVC for Joomla better by taking you through the development of a simple component.


问:
how to check the jira workflow
can we know the issue is working under the workflow or not in jira ..?
We have tried creating workflows and assigned them to the issues but not able to know if the issue is working according to the workflow assigned or not.</p>

答: Take a look at the View Workflow link in an issue</p>

Title: how to check the jira workflow


问:
Dependencies for using Model Validation in ASP.NET Core App
I make use of the the model validation feature like this:

```<code>[StringLength(60, MinimumLength = 3)]
[Required]
</code>```

But when I start the application I get this:

```<code>Author.cs(8,6): error CS0246: The type or namespace name 'StringLengthAttribute' could not be found (are you missing a using directive or an assembly reference?)
Author.cs(8,6): error CS0246: The type or namespace name 'StringLength' could not be found (are you missing a using directive or an assembly reference?)
Author.cs(9,6): error CS0246: The type or namespace name 'RequiredAttribute' could not be found (are you missing a using directive or an assembly reference?)
Author.cs(9,6): error CS0246: The type or namespace name 'Required' could not be found (are you missing a using directive or an assembly reference?)
Author.cs(8,23): error CS0246: The type or namespace name 'MinimumLength' could not be found (are you missing a using directive or an assembly reference?)
Author.cs(11,6): error CS0246: The type or namespace name 'StringLengthAttribute' could not be found (are you missing a using directive or an assembly reference?)
Author.cs(11,6): error CS0246: The type or namespace name 'StringLength' could not be found (are you missing a using directive or an assembly reference?)
Author.cs(12,6): error CS0246: The type or namespace name 'RequiredAttribute' could not be found (are you missing a using directive or an assembly reference?)
Author.cs(12,6): error CS0246: The type or namespace name 'Required' could not be found (are you missing a using directive or an assembly reference?)
Author.cs(11,23): error CS0246: The type or namespace name 'MinimumLength' could not be found (are you missing a using directive or an assembly reference?)
</code>```

I cannot find out what package I'm missing. My guess was Microsoft.AspNetCore.Mvc.DataAnnotations but that seems not to be it.

So what dependency do I need here?

答: You have to first install entity framework from the nuget package then only you will be able to get the using System.ComponentModel.Annotations.</p>

Body:
I make use of the the model validation feature like this:

[StringLength(60, MinimumLength = 3)]
[Required]

But when I start the application I get this:

Author.cs(8,6): error CS0246: The type or namespace name 'StringLengthAttribute' could not be found (are you missing a using directive or an assembly reference?)
Author.cs(8,6): error CS0246: The type or namespace name 'StringLength' could not be found (are you missing a using directive or an assembly reference?)
Author.cs(9,6): error CS0246: The type or namespace name 'RequiredAttribute' could not be found (are you missing a using directive or an assembly reference?)
Author.cs(9,6): error CS0246: The type or namespace name 'Required' could not be found (are you missing a using directive or an assembly reference?)
Author.cs(8,23): error CS0246: The type or namespace name 'MinimumLength' could not be found (are you missing a using directive or an assembly reference?)
Author.cs(11,6): error CS0246: The type or namespace name 'StringLengthAttribute' could not be found (are you missing a using directive or an assembly reference?)
Author.cs(11,6): error CS0246: The type or namespace name 'StringLength' could not be found (are you missing a using directive or an assembly reference?)
Author.cs(12,6): error CS0246: The type or namespace name 'RequiredAttribute' could not be found (are you missing a using directive or an assembly reference?)
Author.cs(12,6): error CS0246: The type or namespace name 'Required' could not be found (are you missing a using directive or an assembly reference?)
Author.cs(11,23): error CS0246: The type or namespace name 'MinimumLength' could not be found (are you missing a using directive or an assembly reference?)

I cannot find out what package I'm missing. My guess was Microsoft.AspNetCore.Mvc.DataAnnotations but that seems not to be it.

So what dependency do I need here?


问:
Bit Difference between 2 binary numbers in MIPS Assembly
So I have to create an MIPS assembly program that reads 2 numbers out of 2 registers ($s0 & $s1) and calculates the number of bits that these 2 numbers differ by. And stores the result in the $s2 register.
I also have to fulfill all the above with the least amount of commands possible.
I have tried a few things on paper with XOR operations but I can't quite figure how to calculate the amount of different bits.

If anyone can help, you're more than welcome to.
Thanks in advance

答:
Here is a way that avoids looping over the 32 bits. It repetitively clears all bits, but the left most one, while counting their number.

```<code>  // x and y are the bits to compare
  int z=x^y;  // only bits different between x and y are set
  int w;
  int cnt=0;
  while(w=z&-z) { //w only has the left bit in z set
    cnt++;
    z^=w; // clear the processed bit
  }
</code>```

It is based on the well known property that x&-x is equal to the lower weight set bit in x.

The inner loop requires 5 mips instructions.

Body:
Here is a way that avoids looping over the 32 bits. It repetitively clears all bits, but the left most one, while counting their number.

  // x and y are the bits to compare
  int z=x^y;  // only bits different between x and y are set
  int w;
  int cnt=0;
  while(w=z&-z) { //w only has the left bit in z set
    cnt++;
    z^=w; // clear the processed bit
  }

It is based on the well known property that x&-x is equal to the lower weight set bit in x.

The inner loop requires 5 mips instructions.


问:
Call to a member function details() on null?
My code is:

```<code>$user = User::create([
   'email' => $request->email,
    'password' => Hash::make($request->password),
 ]);

$user_details = [
            'name' => $request->name,
            'address' => $request->address,
            'lastname' => $request->lastname,
            'secondname' => $request->secondname,
            'inn' => $request->inn,
            'fincode' => $request->fincode,
        ];

$user->details()->create($user_details);
</code>```

Model User is:

```<code>class User extends Authenticatable implements JWTSubject
{
    use Notifiable;

    public function details()
    {
        return $this->hasOne(UserDetails::class, 'user_id', 'id');
    }

}
</code>```

UserDetails model is:

```<code>namespace App;

use Illuminate\Database\Eloquent\Model;

class UserDetails extends Model
{

    protected $table = 'enterprise';

    protected $fillable = ['name', 'lastname', 'secondname', 'address', 'inn', 'fincode'];
}
</code>```

答:
I believe that your $user has not been persisted, hence having the error, in your case $user is null, that's why you cannot call details on null object. Make sure that you use all the required fields on your user.

You might be missing the fillable array in the User model if the one that you shared is the full content, then add this:

```<code>protected $fillable = [ 'email', 'password'];
</code>```

Body:
My code is:

$user = User::create([
   'email' => $request->email,
    'password' => Hash::make($request->password),
 ]);

$user_details = [
            'name' => $request->name,
            'address' => $request->address,
            'lastname' => $request->lastname,
            'secondname' => $request->secondname,
            'inn' => $request->inn,
            'fincode' => $request->fincode,
        ];

$user->details()->create($user_details);

Model User is:

class User extends Authenticatable implements JWTSubject
{
    use Notifiable;

    public function details()
    {
        return $this->hasOne(UserDetails::class, 'user_id', 'id');
    }

}

UserDetails model is:

namespace App;

use Illuminate\Database\Eloquent\Model;

class UserDetails extends Model
{

    protected $table = 'enterprise';

    protected $fillable = ['name', 'lastname', 'secondname', 'address', 'inn', 'fincode'];
}

Body:
I believe that your $user has not been persisted, hence having the error, in your case $user is null, that's why you cannot call details on null object. Make sure that you use all the required fields on your user.

You might be missing the fillable array in the User model if the one that you shared is the full content, then add this:

protected $fillable = [ 'email', 'password'];


问:
std::vector::erase() erases the wrong element
So I search for an element in a vector, I store it in an iterator and I call the erase() on it. Unfortunately, when I set the breakpoints and check what's happening, I see that even if the closestObjectIt points to the right element, that element still remains in the vector, some other element being deleted. I have no clue what is wrong here; why the right iterator is not deleted?

I also had in my project some implicit conversions from std::vector to cv::vector (from OpenCV) and vice-versa, but I eliminated them, being suspicious.

```<code>DetectedObject Head:: findTheClosestObjectFromObjects(std::vector<DetectedObject>& objects)
{
  float minDistance = 10000;
  std::vector<DetectedObject>::iterator closestObjectIt;
  DetectedObject closestObject = objects[0];

  for(std::vector<DetectedObject>::iterator it = objects.begin(); it != objects.end(); ++it)
  {
    float distance = computeDistance2((*it));
    if (distance < minDistance)
    {
        minDistance = distance;
        closestObject = (*it);
        closestObjectIt = it;
    }
  }
  std::cout << "Before erease: " << std::endl;
  objects.erase(closestObjectIt);
  std::cout << "After erease: " << std::endl;

  return closestObject;
}
</code>```

答:
vector::erase(it) doesn't remove the element pointed by it. It calls to copy assignment of managed object to assign the element pointed by it with the next one. This step is done for the next one too, and continue until it reach the end element and it will really delete the memory of end element.
So, remember to write copy assignment operator for Class that will be managed in vector and will be used with erase() method. The second ways to overcome this issue is use std::vector of Pointer.

```<code>#include <iostream>
#include <vector>
using namespace std;

class BarcodeTagging {
    int value_;
    public:
    BarcodeTagging(int value) : value_(value) {
    }

    ~BarcodeTagging() {
        std::cout << "Delete " << this << "\n";
    }

    const BarcodeTagging& operator=(const BarcodeTagging& other) {
        std::cout << "Call to this \n";
        std::cout << "who calling: " << this << "\n";
        std::cout << "who is called: " << &other << "\n";
        value_ = other.value_;
        return *this;
    }

    int GetValue() const {
        return value_;
    }

};

int main() {
    // your code goes here
    std::vector<BarcodeTagging> taggings;
    BarcodeTagging tag1(1);
    BarcodeTagging tag2(2);
    BarcodeTagging tag3(3);
    taggings.push_back(tag1);
    taggings.push_back(tag2);
    taggings.push_back(tag3);

    std::cout << "Before erase \n";
    for (int i = 0; i < taggings.size(); ++i) {
        std::cout << "element " << i << ": " << &(taggings[i]) << ", with value: " <<
        taggings[i].GetValue() << "\n";
    }
    taggings.erase(taggings.begin());
    std::cout << "After erase \n";

    for (int i = 0; i < taggings.size(); ++i) {
        std::cout << "element " << i << ": " << &(taggings[i]) << ", with value: " <<
        taggings[i].GetValue() << "\n";
    }
    return 0;
}
</code>```

And the output:

```<code>Delete 0x55faf3c98c20
Delete 0x55faf3c98c40
Delete 0x55faf3c98c44
Before erase
element 0: 0x55faf3c98c20, with value: 1
element 1: 0x55faf3c98c24, with value: 2
element 2: 0x55faf3c98c28, with value: 3
Call to this
who calling: 0x55faf3c98c20
who is called: 0x55faf3c98c24
Call to this
who calling: 0x55faf3c98c24
who is called: 0x55faf3c98c28
Delete 0x55faf3c98c28
After erase
element 0: 0x55faf3c98c20, with value: 2
element 1: 0x55faf3c98c24, with value: 3
Delete 0x7ffe1d958b40
Delete 0x7ffe1d958b30
Delete 0x7ffe1d958b20
Delete 0x55faf3c98c20
Delete 0x55faf3c98c24
</code>```

Body:
So I search for an element in a vector, I store it in an iterator and I call the erase() on it. Unfortunately, when I set the breakpoints and check what's happening, I see that even if the closestObjectIt points to the right element, that element still remains in the vector, some other element being deleted. I have no clue what is wrong here; why the right iterator is not deleted?

I also had in my project some implicit conversions from std::vector to cv::vector (from OpenCV) and vice-versa, but I eliminated them, being suspicious.

DetectedObject Head:: findTheClosestObjectFromObjects(std::vector<DetectedObject>& objects)
{
  float minDistance = 10000;
  std::vector<DetectedObject>::iterator closestObjectIt;
  DetectedObject closestObject = objects[0];

  for(std::vector<DetectedObject>::iterator it = objects.begin(); it != objects.end(); ++it)
  {
    float distance = computeDistance2((*it));
    if (distance < minDistance)
    {
        minDistance = distance;
        closestObject = (*it);
        closestObjectIt = it;
    }
  }
  std::cout << "Before erease: " << std::endl;
  objects.erase(closestObjectIt);
  std::cout << "After erease: " << std::endl;

  return closestObject;
}

Body:
vector::erase(it) doesn't remove the element pointed by it. It calls to copy assignment of managed object to assign the element pointed by it with the next one. This step is done for the next one too, and continue until it reach the end element and it will really delete the memory of end element.
So, remember to write copy assignment operator for Class that will be managed in vector and will be used with erase() method. The second ways to overcome this issue is use std::vector of Pointer.

#include <iostream>
#include <vector>
using namespace std;

class BarcodeTagging {
    int value_;
    public:
    BarcodeTagging(int value) : value_(value) {
    }

    ~BarcodeTagging() {
        std::cout << "Delete " << this << "\n";
    }

    const BarcodeTagging& operator=(const BarcodeTagging& other) {
        std::cout << "Call to this \n";
        std::cout << "who calling: " << this << "\n";
        std::cout << "who is called: " << &other << "\n";
        value_ = other.value_;
        return *this;
    }

    int GetValue() const {
        return value_;
    }

};

int main() {
    // your code goes here
    std::vector<BarcodeTagging> taggings;
    BarcodeTagging tag1(1);
    BarcodeTagging tag2(2);
    BarcodeTagging tag3(3);
    taggings.push_back(tag1);
    taggings.push_back(tag2);
    taggings.push_back(tag3);

    std::cout << "Before erase \n";
    for (int i = 0; i < taggings.size(); ++i) {
        std::cout << "element " << i << ": " << &(taggings[i]) << ", with value: " <<
        taggings[i].GetValue() << "\n";
    }
    taggings.erase(taggings.begin());
    std::cout << "After erase \n";

    for (int i = 0; i < taggings.size(); ++i) {
        std::cout << "element " << i << ": " << &(taggings[i]) << ", with value: " <<
        taggings[i].GetValue() << "\n";
    }
    return 0;
}

And the output:

Delete 0x55faf3c98c20
Delete 0x55faf3c98c40
Delete 0x55faf3c98c44
Before erase
element 0: 0x55faf3c98c20, with value: 1
element 1: 0x55faf3c98c24, with value: 2
element 2: 0x55faf3c98c28, with value: 3
Call to this
who calling: 0x55faf3c98c20
who is called: 0x55faf3c98c24
Call to this
who calling: 0x55faf3c98c24
who is called: 0x55faf3c98c28
Delete 0x55faf3c98c28
After erase
element 0: 0x55faf3c98c20, with value: 2
element 1: 0x55faf3c98c24, with value: 3
Delete 0x7ffe1d958b40
Delete 0x7ffe1d958b30
Delete 0x7ffe1d958b20
Delete 0x55faf3c98c20
Delete 0x55faf3c98c24


问:
Reassign Pandas DataFrame column values
I have a csv that has incorrect datetime formatting. I've worked out how to convert those values into the format I need, but now I need to reassign all the values in a column to the new, converted values.

For example, I'm hoping that there's something I can put into the following FOR loop that will insert the values back into the dataframe at the correct location:

```<code>for i in df[df.columns[1]]:
    t = pd.Timestamp(i)
    short_date = t.date().strftime('%m/%d/%Y').lstrip('0')
    # Insert back into dataframe?
</code>```

As always, your help is very much appreciated!

Part of the column in question:
Part of the dataframe in question:

```<code>Created Date
2019-02-27 22:55:16
2019-01-29 22:57:12
2018-11-29 00:13:31
2019-01-30 21:35:15
2018-12-20 21:14:45
2018-11-01 16:20:15
2019-04-11 16:38:07
2019-01-24 00:23:17
2018-12-21 19:30:10
2018-12-19 22:33:04
2018-11-07 19:54:19
2019-05-10 21:15:00
</code>```

答:
In the simplest, but most instructive, possible terms:

df = pd.DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]})
df
#    x  y
# 0  1  4
# 1  2  5
# 2  3  6

df[:] = df[:].astype(float)
df
#      x    y
# 0  1.0  4.0
# 1  2.0  5.0
# 2  3.0  6.0
```

<p>Let <code>pandas</code> do the work for you.</p>

<p>Or, for only one column:</p>

<pre class="lang-py prettyprint-override"><code>df.x = df.x.astype(float)
df
#      x  y
# 0  1.0  4
# 1  2.0  5
# 2  3.0  6
</code>```

You'll, of course, replace astype(float) with .date().strftime('%m/%d/%Y').lstrip('0').

Title: Reassign Pandas DataFrame column values

Body:
I have a csv that has incorrect datetime formatting. I've worked out how to convert those values into the format I need, but now I need to reassign all the values in a column to the new, converted values.

For example, I'm hoping that there's something I can put into the following FOR loop that will insert the values back into the dataframe at the correct location:

for i in df[df.columns[1]]:
    t = pd.Timestamp(i)
    short_date = t.date().strftime('%m/%d/%Y').lstrip('0')
    # Insert back into dataframe?

As always, your help is very much appreciated!

Part of the column in question:
Part of the dataframe in question:

Created Date
2019-02-27 22:55:16
2019-01-29 22:57:12
2018-11-29 00:13:31
2019-01-30 21:35:15
2018-12-20 21:14:45
2018-11-01 16:20:15
2019-04-11 16:38:07
2019-01-24 00:23:17
2018-12-21 19:30:10
2018-12-19 22:33:04
2018-11-07 19:54:19
2019-05-10 21:15:00

Body:
In the simplest, but most instructive, possible terms:

df = pd.DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]})
df
#    x  y
# 0  1  4
# 1  2  5
# 2  3  6

df[:] = df[:].astype(float)
df
#      x    y
# 0  1.0  4.0
# 1  2.0  5.0
# 2  3.0  6.0

Let pandas do the work for you.

Or, for only one column:

df.x = df.x.astype(float)
df
#      x  y
# 0  1.0  4
# 1  2.0  5
# 2  3.0  6

You'll, of course, replace astype(float) with .date().strftime('%m/%d/%Y').lstrip('0').


问:
Dropdown onchange isn't fired
I need help with this select, it's populated with db and I need to get the item selected when change the item.

<select class="custom-select col-md-12" id="operation" name="operation" formControlName="operation">
  <option *ngFor="let operation of operations" [ngValue]="operation.id" (ngModelChange)="show(operation)">{{ operation.value}}</option>
</select>```
</div>
</div>
</p>

```show(value){
   ...
}
```

I already tried with (change) and [(ngModel)] but it doesn't work.

答:
If you are binding formcontrolName then you no need bind the change event in html. You can subscribe the change event in ts itself. But if you want to bind the change event via html then remove the formcontrolName binding and bind change event in html.

Component

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular';
  operations = [{ id: 1, value: 'test' }, { id: 2, value: 'test2' }, { id: 3, value: 'test3' }];

  show(event){
    console.log(event.target.value);
  }
}
</code>```

<select class="custom-select col-md-12" id="operation" name="operation" (change)="show($event)">
  <option *ngFor="let operation of operations" [value]="operation.id" >{{ operation.value}}</option>
</select>
```

Example:
StackBlitz

Title: Dropdown onchange isn't fired

Body:
I need help with this select, it's populated with db and I need to get the item selected when change the item.

<select class="custom-select col-md-12" id="operation" name="operation" formControlName="operation">
  <option *ngFor="let operation of operations" [ngValue]="operation.id" (ngModelChange)="show(operation)">{{ operation.value}}</option>
</select>

show(value){
   ...
}

I already tried with (change) and [(ngModel)] but it doesn't work.

Body:
If you are binding formcontrolName then you no need bind the change event in html. You can subscribe the change event in ts itself. But if you want to bind the change event via html then remove the formcontrolName binding and bind change event in html.

Component

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular';
  operations = [{ id: 1, value: 'test' }, { id: 2, value: 'test2' }, { id: 3, value: 'test3' }];

  show(event){
    console.log(event.target.value);
  }
}

<select class="custom-select col-md-12" id="operation" name="operation" (change)="show($event)">
  <option *ngFor="let operation of operations" [value]="operation.id" >{{ operation.value}}</option>
</select>

Example:
StackBlitz


问:
How to calculate age (in years) based on Date of Birth and getDate()
I have a table listing people along with their date of birth (currently a nvarchar(25))

How can I convert that to a date, and then calculate their age in years?

My data looks as follows

```<code>ID    Name   DOB
1     John   1992-01-09 00:00:00
2     Sally  1959-05-20 00:00:00
</code>```

I would like to see:

```<code>ID    Name   AGE  DOB
1     John   17   1992-01-09 00:00:00
2     Sally  50   1959-05-20 00:00:00
</code>```

答:
select floor((datediff(day,0,@today) - datediff(day,0,@birthdate)) / 365.2425) as age
```

There are a lot of 365.25 answers here. Remember how leap years are defined:

Every four years

except every 100 years

except every 400 years

Body:
I have a table listing people along with their date of birth (currently a nvarchar(25))

How can I convert that to a date, and then calculate their age in years?

My data looks as follows

ID    Name   DOB
1     John   1992-01-09 00:00:00
2     Sally  1959-05-20 00:00:00

I would like to see:

ID    Name   AGE  DOB
1     John   17   1992-01-09 00:00:00
2     Sally  50   1959-05-20 00:00:00

Body:
select floor((datediff(day,0,@today) - datediff(day,0,@birthdate)) / 365.2425) as age

There are a lot of 365.25 answers here. Remember how leap years are defined:

Every four years

except every 100 years

except every 400 years


问:
How to convert parts of a line to uppercase in a file
I have a file file.txt and it has the lines below. I want the queuename to be converted to uppercase, like this: queuename=SP00245B

```<code>    # Queue name
    #
    queuename=sp00245b
</code>```

答:
With GNU sed:

```<code>sed -i 's/\(^[[:blank:]]*queuename=\)\(.*\)/\1\U\2/' file.txt
</code>```

This uses two captures groups and the \U sequence to toggle uppercase substitution for the second group.

Body:
I have a file file.txt and it has the lines below. I want the queuename to be converted to uppercase, like this: queuename=SP00245B

    # Queue name
    #
    queuename=sp00245b

Body:
With GNU sed:

sed -i 's/\(^[[:blank:]]*queuename=\)\(.*\)/\1\U\2/' file.txt

This uses two captures groups and the \U sequence to toggle uppercase substitution for the second group.


问:
How to 'convert' amount of Hz to appropriate byte/bit format?
I am programming an IR camera. But the internal register for storing the refreshrate (bits 9, 8 and 7 of 16 in total) only accepts 1's and 0's of course. For example, a value of 0b110 means 32Hz and 0b111, 64Hz. How can I best convert a given integer (refresh_rate) value between 0.5Hz and 64Hz to 0b000 - 0b111 when looking at the Refresh rate control picture?

To be honest, I haven't tried anything yet because I think it requires a weird hack. However I have been thinking of a lookuptable, I think that is possible but requires more memory and it has to be memory efficient since it is programmed on an Arduino Due.

Note: You can see that the refresh_rate is an uint16_t which does not accept floating point values such as 0.5Hz, however, I am probably not going to use the 0.5Hz setting.

// the end-user currently has to pass a value between 7 and 0
void mlx90650::set_refresh_rate(uint16_t refresh_rate) {
    // So the refresh rate may not be higher than 7 (0b111) since this register only
accepts 3 bits. The memory map is:
/*
    | decimal | bits  |
    (decimal 0) 0 0 0 IR refresh rate = 0.5Hz
    (decimal 1) 0 0 1 IR refresh rate = 1Hz
    (decimal 2) 0 1 0 IR refresh rate = 2Hz (default)
    (decimal 3) 0 1 1 IR refresh rate = 4Hz
    (decimal 4) 1 0 0 IR refresh rate = 8Hz
    (decimal 5) 1 0 1 IR refresh rate = 16Hz
    (decimal 6) 1 1 0 IR refresh rate = 32Hz
    (decimal 7) 1 1 1 IR refresh rate = 64H
*/
}
```

I want that this function converts for example 64Hz to 0b111.

答:
However you map actual Hz to bit patterns, you set them like this:</p>

```<code>void set_hz(uint16_t& control_reg, uint8_t hz)  // here hz is 0 for .5 Hz, 1 for 1Hz,.. 7 for 64Hz
{
     constexpr int hz_shift = 7;
     constexpr uint16_t hz_mask = static_cast<uint16_t>(0x07) << hz_shift;
     control_reg &= ~hz_mask;
     control_reg |= static_cast<uint16_t>(hz) << hz_shift;
}
</code>```

Body:
I am programming an IR camera. But the internal register for storing the refreshrate (bits 9, 8 and 7 of 16 in total) only accepts 1's and 0's of course. For example, a value of 0b110 means 32Hz and 0b111, 64Hz. How can I best convert a given integer (refresh_rate) value between 0.5Hz and 64Hz to 0b000 - 0b111 when looking at the Refresh rate control picture?

To be honest, I haven't tried anything yet because I think it requires a weird hack. However I have been thinking of a lookuptable, I think that is possible but requires more memory and it has to be memory efficient since it is programmed on an Arduino Due.

Note: You can see that the refresh_rate is an uint16_t which does not accept floating point values such as 0.5Hz, however, I am probably not going to use the 0.5Hz setting.

// the end-user currently has to pass a value between 7 and 0
void mlx90650::set_refresh_rate(uint16_t refresh_rate) {
    // So the refresh rate may not be higher than 7 (0b111) since this register only
accepts 3 bits. The memory map is:
/*
    | decimal | bits  |
    (decimal 0) 0 0 0 IR refresh rate = 0.5Hz
    (decimal 1) 0 0 1 IR refresh rate = 1Hz
    (decimal 2) 0 1 0 IR refresh rate = 2Hz (default)
    (decimal 3) 0 1 1 IR refresh rate = 4Hz
    (decimal 4) 1 0 0 IR refresh rate = 8Hz
    (decimal 5) 1 0 1 IR refresh rate = 16Hz
    (decimal 6) 1 1 0 IR refresh rate = 32Hz
    (decimal 7) 1 1 1 IR refresh rate = 64H
*/
}

I want that this function converts for example 64Hz to 0b111.

Body:
However you map actual Hz to bit patterns, you set them like this:

void set_hz(uint16_t& control_reg, uint8_t hz)  // here hz is 0 for .5 Hz, 1 for 1Hz,.. 7 for 64Hz
{
     constexpr int hz_shift = 7;
     constexpr uint16_t hz_mask = static_cast<uint16_t>(0x07) << hz_shift;
     control_reg &= ~hz_mask;
     control_reg |= static_cast<uint16_t>(hz) << hz_shift;
}


问:
Is it possible to configure a link to open a page that contains an iframe, and have that iframe query an URL?
I am setting up a registration confirmation email system.

The sign-up process usually takes place on my platform, and upon receiving the confirmation email, the link redirects to the same website the new user has signed-up on.

But the sign-up page I'm having trouble with is contained in an iframe on a website that I have no control over. I can only change what's inside of the iframe.

I would need the link sent through email to redirect to the page that contains the aforementionned iframe, while still activating the user in the iframe.

I work with django templates. I can change the body of the email, the registration page and the confirmation page, that's about it.

答:
Not possible.

However, in your HTML you can detect that you are in an iframe using javascript and use that to add a parameter to the form (e.g. a hidden input field) so that in Django you will know this comes from the iframe and you also know via the Referer header the address of the parent website.

Once you know that, you could make the email confirmation page tailored for the parent website, e.g. add a link back to it or make it look different than your normal confirmation page.


问:
Use setTimeout to periodically make autocomplete AJAX calls?
I would like to use a setTimeout function so that Ajax calls are only made at the most every 1 second.

Here is what I have. This is clearly not correct, but I am not sure how the setTimeout function works.

```<code>function autoComplete(q, succ)
{

    setTimeout(

    if(q != "") {
        $.ajax({type:"GET",
            url: "php/search.php",
            data: "q="+q,
            success: succ
        });
    }

    , 1000);
}
</code>```

I think that I should use clearTimeout so that if another call is made, it will reset the timer and wait another 1 second, but when I tried to implement this it stopped running the function.

答:
You can try this way also,

var textInput = document.getElementById('input');
var timeout = null; // default set
textInput.onkeyup = function (e) {

    // If it has already been set cleared first.
    clearTimeout(timeout);

    // set timeout to 500ms
    timeout = setTimeout(function () {
        console.log('Input Value:', textInput.value);
    }, 500);
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="input"></code>```

Body:
I would like to use a setTimeout function so that Ajax calls are only made at the most every 1 second.

Here is what I have. This is clearly not correct, but I am not sure how the setTimeout function works.

function autoComplete(q, succ)
{

    setTimeout(

    if(q != "") {
        $.ajax({type:"GET",
            url: "php/search.php",
            data: "q="+q,
            success: succ
        });
    }

    , 1000);
}

I think that I should use clearTimeout so that if another call is made, it will reset the timer and wait another 1 second, but when I tried to implement this it stopped running the function.

Body:
You can try this way also,

var textInput = document.getElementById('input');
var timeout = null; // default set
textInput.onkeyup = function (e) {

    // If it has already been set cleared first.
    clearTimeout(timeout);

    // set timeout to 500ms
    timeout = setTimeout(function () {
        console.log('Input Value:', textInput.value);
    }, 500);
};

<input type="text" id="input">


问:
I found an error in the compilation of GNAT in the Command Line
source code

```<code>with Ada.Text_IO;
procedure hello_world is
begin
    Ada.Text_IO.Put_line(“Hello World”);
    Ada.Text_IO.Put(“by Jeffy Fifa”);
    Ada.Text_IO.New_Line;
end hello_world;
</code>```

enter image description here

答:
Well, as Simon Wright already stated in a comment, ensure that GNAT is installed correctly. You can download the community edition here. Then, after the installation succeeded:

Ensure that C:\GNAT\2018\bin is in the search path:

```<code>C:\> echo %PATH%
[...];C:\GNAT\2018\bin;[...]
</code>```

Ensure that gnatmake executes:

```<code>C:\> gnatmake --version
GNATMAKE Community 2018 (20180523-73)
Copyright (C) 1995-2018, Free Software Foundation, Inc.
This is free software; see the source for copying conditions.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
</code>```

Switch to the folder where the file hello_world.adb is located, and try to compile the file using:

```<code>E:\> gnatmake -g hello_world.adb
gcc -c -g hello_world.adb
gnatbind -x hello_world.ali
gnatlink hello_world.ali -g
</code>```

Body:
source code

with Ada.Text_IO;
procedure hello_world is
begin
    Ada.Text_IO.Put_line(“Hello World”);
    Ada.Text_IO.Put(“by Jeffy Fifa”);
    Ada.Text_IO.New_Line;
end hello_world;

enter image description here

Body:
Well, as Simon Wright already stated in a comment, ensure that GNAT is installed correctly. You can download the community edition here. Then, after the installation succeeded:

Ensure that C:\GNAT\2018\bin is in the search path:

C:\> echo %PATH%
[...];C:\GNAT\2018\bin;[...]

Ensure that gnatmake executes:

C:\> gnatmake --version
GNATMAKE Community 2018 (20180523-73)
Copyright (C) 1995-2018, Free Software Foundation, Inc.
This is free software; see the source for copying conditions.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Switch to the folder where the file hello_world.adb is located, and try to compile the file using:

E:\> gnatmake -g hello_world.adb
gcc -c -g hello_world.adb
gnatbind -x hello_world.ali
gnatlink hello_world.ali -g


问:
How can I filter an Iterable based upon a Predicate?
I want to do a string list filter function using an Iterable<String> and a predicate to select the strings to keep, the other ones must be removed from the list, but I'm not understating how I do the remove.

```<code>static <T> Iterable<T> select(Iterable<T> it, Predicate<T> pred) {
    for (T s: it) {
        if (pred.test(s)==false) {
            // what to do here?
        }
    }
    return ...;
}
</code>```

For this input:

```<code>{"a","","b",""}
</code>```

I expect

```<code>{"a","b"}
</code>```

答:
Since any Collection is Iterable, just add the qualified items to a new collection and return it later:

```<code>static <T> Iterable<T> select(Iterable<T> it, Predicate<T> pred) {
    Collection<T> collection = new ArrayList<>();
    for (T s: it) {
        if (!pred.test(s)) {
            collection.add(s);
        }
    }
    return collection;
}
</code>```

Few insights:

The pred.test(s)==false expression shall be rather simplified to !pred.test(s)

The whole content of method could be shortened using java-stream in this way:

```<code>static <T> Iterable<T> select(Iterable<T> it, Predicate<T> pred) {
    return StreamSupport.stream(it.spliterator(), false)
        .filter(pred)
        .collect(Collectors.toList());
}
</code>```

Body:
I want to do a string list filter function using an Iterable<String> and a predicate to select the strings to keep, the other ones must be removed from the list, but I'm not understating how I do the remove.

static <T> Iterable<T> select(Iterable<T> it, Predicate<T> pred) {
    for (T s: it) {
        if (pred.test(s)==false) {
            // what to do here?
        }
    }
    return ...;
}

For this input:

{"a","","b",""}

I expect

{"a","b"}

Body:
Since any Collection is Iterable, just add the qualified items to a new collection and return it later:

static <T> Iterable<T> select(Iterable<T> it, Predicate<T> pred) {
    Collection<T> collection = new ArrayList<>();
    for (T s: it) {
        if (!pred.test(s)) {
            collection.add(s);
        }
    }
    return collection;
}

Few insights:

The pred.test(s)==false expression shall be rather simplified to !pred.test(s)

The whole content of method could be shortened using java-stream in this way:

static <T> Iterable<T> select(Iterable<T> it, Predicate<T> pred) {
    return StreamSupport.stream(it.spliterator(), false)
        .filter(pred)
        .collect(Collectors.toList());
}


问:
iPhone: Setting the SelectedTabIndex does not highlight TabItem
When in code I set the SelectedTabIndex of a uitabbarcontroller, it faithfully changes the displayed tab, but the TabItem does not highlight. I have to manually touch it to turn the TabItem "Blue" and highlighted.

Is there a way to force the TabItem to be highlighted?

We've tried this:

```<code>    public override void ViewWillAppear (bool animated)
    {
        base.ViewWillAppear (animated);
        this.SelectedIndex = 0;
        this.SelectedViewController = this.ViewControllers[0];
        this.TabBar.SetNeedsDisplay ();
    }
</code>```

答: Set the UITabBarController selectedViewController property instead.

Body:
When in code I set the SelectedTabIndex of a uitabbarcontroller, it faithfully changes the displayed tab, but the TabItem does not highlight. I have to manually touch it to turn the TabItem "Blue" and highlighted.

Is there a way to force the TabItem to be highlighted?

We've tried this:

    public override void ViewWillAppear (bool animated)
    {
        base.ViewWillAppear (animated);
        this.SelectedIndex = 0;
        this.SelectedViewController = this.ViewControllers[0];
        this.TabBar.SetNeedsDisplay ();
    }


问:
Coinpayments IPN is not redirecting user back
The code:

```<code>$CP->setFormElement('currency', 'LTCT');
$CP->setFormElement('amountf',0.0002);
$CP->setFormElement('item_name', 'Test Item');
$CP->setFormElement('custom', 'customValue235');
$CP->setFormElement('ipn_url', 'http://middleman.pw/CoinPayments-master/callback.php');
</code>```

I still just get the following:

Just to clarify, the user won't be redirected back to my website.

答:
IPN is for Instant Payment Notification
To redirect user after successful payment, use

```<code>$CP->setFormElement('success_url', 'http://middleman.pw/CoinPayments-master/callback.php');
</code>```

From https://www.coinpayments.net/apidoc-create-transaction , success_url   Sets a URL to go to if the buyer does complete payment. (Only if you use the returned 'checkout_url', no effect/need if designing your own checkout page.)

Body:
The code:

$CP->setFormElement('currency', 'LTCT');
$CP->setFormElement('amountf',0.0002);
$CP->setFormElement('item_name', 'Test Item');
$CP->setFormElement('custom', 'customValue235');
$CP->setFormElement('ipn_url', 'http://middleman.pw/CoinPayments-master/callback.php');

I still just get the following:

Just to clarify, the user won't be redirected back to my website.

Body:
IPN is for Instant Payment Notification
To redirect user after successful payment, use

$CP->setFormElement('success_url', 'http://middleman.pw/CoinPayments-master/callback.php');

From https://www.coinpayments.net/apidoc-create-transaction , success_url   Sets a URL to go to if the buyer does complete payment. (Only if you use the returned 'checkout_url', no effect/need if designing your own checkout page.)


问:
In wiremock, is it possible to record cookies on the request?
In wiremock, is it possible to record cookies on the request?

I'd like to know if a certain cookie is set on the request that I'm performing, and would also like it to be absent.

```<code> "cookies" : {
      "cookiename" : {
        "absent" : true
      }
  }
</code>```

答:
In WireMock.Net (C# .NET version), you can define that a cookie must be absent.

"Cookies": [
  {
    "Name": "cooky",
    "Matchers": [
      {
        "Name": "WildcardMatcher",
        "Pattern": "*",
        "IgnoreCase": true,
        "RejectOnMatch": true
      }
    ]
  }
],

```

Body:
In wiremock, is it possible to record cookies on the request?

I'd like to know if a certain cookie is set on the request that I'm performing, and would also like it to be absent.

 "cookies" : {
      "cookiename" : {
        "absent" : true
      }
  }


问:
Cannot format datetime in SQL Server Reporting Services report builder
None of the previous questions/answers on this topic are working for me; I'm a bit baffled. I've inherited my first SQL Server Reporting Services Report Builder report and was given the seemingly simple task of changing what was a date to a datetime. As you can see below I've successfully modified the underlying query and am getting back datetime types but I cannot FORMAT them as such on the report.

Results of my query:

My first instinct was that simply changing the type of the column (FirstProcessorCompletedDate) from date to datetime would make cue the report tool in on displaying date and time, but no luck. So...

Previous experience with report building tools told me to take the existing reference to the field and replace it with a format statement for that field, kind of like this:

Unfortunately, whatever I add here is getting interpreted as LITERALS by the report builder upon execution.  AND YES, I DID TRY AN "=" IN FRONT OF THE FORMAT STATEMENT.  This is just one variation of what I've tried.

Clearly this is not the old SSRS-type report building I am used to.  I've Googled the heck out of this and searched Stack Overflow but no joy on the answer.  I've looked a little at Calculated Fields but this seems like overkill.  I don't want to calculate something, just format it.

What am I missing?

答:
Don't modify the underlying query, that was your first mistake. date(time) data types don't have a format, they are binary values and your presentation layer changes that to a readable format. Once you change the "format" of a date(time) data type in SQL Server it is no longer a date(time) datatype, it's a varchar, and Format does not work on a varchar. How would you format the varchar value 'Hello, my name is Jane.' to the style MM/dd/yyyy hh:mm tt? You can't, and the same applies to a string representing a date.

Return the value of your column as a datetime to SSRS (don't convert it), and then change the Format Property of your cell in SSRS (hit F4 when you have the cell selected and you'll open up the cell's property pane) and change the format to MM/dd/yyyy hh:mm tt.


问:
Python: Why does Python TCP-client receive data so slowly on different compared to same PC?
I have two Python scripts, one TCP-server sending data (at a rate of 1/256 times a second) and a TCP-client receiving data. In the client script, I print the length of the received data.
I sent the string "5.8" from the server (thus data of length 3).

When client and server are on the same machine:
The length of data received is always 3.
When client and server are on different machines in the same local network:
The length of data differs but is around 39 (13 times the data sent).

Is there a possible explanation for this discrepancy?

I think the network adding this much latency is unlikely, because the command line "ping" prints at most 2 ms latency with the largest amount of data.

IMPORTANT: I'm using Python 2.7.

import socket

def server():
    host = 'localhost' # replace with IP address in case client is on another machine
    port = 5051

    s = socket.socket()
    s.bind((host, port))
    s.listen(1)
    client_socket, adress = s.accept()

    while True:
        client_socket.send('a'.encode())
    client_socket.close()

if __name__ == '__main__':
    server()
```

<pre class="lang-py prettyprint-override"><code>import socket, random, time

def client():
    host = 'localhost' # replace with IP address in case client is on another machine
    port = 5051

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s_err = s.connect_ex((host, port))
    print(s_err)

    while True:
        data = s.recv(2048)
        print(len(data)) # returns different values depending on client location
    s.close()

if __name__ == '__main__':
    client()
</code>```

答:
Is there a possible explanation for this discrepancy?

TCP doesn't have a concept of a message. Data sent using multiple send calls can be received with one recv call and vice versa.

TCP is a stream where you need to delimit the messages yourself, so that the reader can determine message boundaries. Most common ways:

Prefix messages with fixed message length.

Read until a message delimiter is encountered, e.g. \n.

Body:
I have two Python scripts, one TCP-server sending data (at a rate of 1/256 times a second) and a TCP-client receiving data. In the client script, I print the length of the received data.
I sent the string "5.8" from the server (thus data of length 3).

When client and server are on the same machine:
The length of data received is always 3.
When client and server are on different machines in the same local network:
The length of data differs but is around 39 (13 times the data sent).

Is there a possible explanation for this discrepancy?

I think the network adding this much latency is unlikely, because the command line "ping" prints at most 2 ms latency with the largest amount of data.

IMPORTANT: I'm using Python 2.7.

import socket

def server():
    host = 'localhost' # replace with IP address in case client is on another machine
    port = 5051

    s = socket.socket()
    s.bind((host, port))
    s.listen(1)
    client_socket, adress = s.accept()

    while True:
        client_socket.send('a'.encode())
    client_socket.close()

if __name__ == '__main__':
    server()

import socket, random, time

def client():
    host = 'localhost' # replace with IP address in case client is on another machine
    port = 5051

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s_err = s.connect_ex((host, port))
    print(s_err)

    while True:
        data = s.recv(2048)
        print(len(data)) # returns different values depending on client location
    s.close()

if __name__ == '__main__':
    client()