问:
Sort button issueing new and unwanted API call for boostrap-vue table elements
I'm developing in Vue2 using the 1 file = 1 component scheme.

Using a Bootstrap-Vue Table Component, I'm using the provider to pass it an items.

The issue is that when I use the sort button the sort one time out of a couple (if I press sort too fast) the sort fails because the API call for the list is called again and the list is displayed anew.

How would I correct this.

Do I need to design it another way?

my code :

```<code><b-table small fixed bordered striped hover show-empty
             :no-provider-paging="true"
             :no-provider-sorting="false"
             :no-provider-filtering="true"
             :busy.sync="isBusy"
             :items="allergyIntolerance"
             :fields="fields"
             :current-page="currentPage"
             :per-page="perPage"
             :filter="filter"
             :sort-by.sync="sortBy"
             :sort-desc.sync="sortDesc"
             @filtered="onFiltered"
    >
      <template slot="identifiant" slot-scope="row">{{row.item.content._id}}</template>
      <template slot="patient" slot-scope="row">{{row.item.content.patient.reference}}</template>
      <template slot="practitioner" slot-scope="row">{{row.item.content.recorder.reference}}</template>
      <template slot="category" slot-scope="row">{{row.item.content.category}}</template>
      <template slot="status" slot-scope="row">{{row.item.content.clinicalStatus}}</template>
      <template slot="critical" slot-scope="row">{{row.item.content.criticality}}</template>
      <template slot="actions" slot-scope="row">
      <button class="btn btn-xs btn-success" @click.stop="details(row.item,row.index,$event.target)">
        <span class="glyphicon glyphicon-search"></span>
      </button>
      <button class="btn btn-xs btn-primary" @click.stop="edit(row.item,row.index,$event.target)">
            <span class="glyphicon glyphicon-pencil"></span>
      </button>
      <button class="btn btn-xs btn-danger" @click.stop="del(row.item,row.index,$event.target)">
            <span class="glyphicon glyphicon-trash"></span>
      </button>
      </template>
    </b-table>
</code>```

note that if I pass :no-provider-sorting to true it no longer sorts.

every other option is working as intended.

```<code>allergyIntolerance (ctx) {
      var token = 'JWT eyJtokentokentokens'
      let promise = axios.get('http://localhost:3000/api/allergyintolerance/', {headers: { 'Authorization': token }})

      return promise.then(response => {
        const items = response.data.entry
        this.totalRows = items.length
        return (items)
      })
      .catch(error => {
        console.log(error.response)
        return []
      })
    }
</code>```

答:
I recommend moving the data provision out of the table component itself. You may create a wrapper component which loads the table in a default state, fetches the data and updates the table on complete.
The table should otherwise be pretty dumb and not care about much else than rendering the data its given.

If you need a managed way to do this have a look at vuex, which also supports async actions.

Edit: I've attached a simple example. It should be pretty straightforward to translate to your setup.

HTML

```<code><div id="app">
  <my-container></my-container>
</div>

<script type="text/template" id="my-table-template">
<div>
  <b-table
    :sort-by.sync="sortBy"
    :sort-desc.sync="sortDesc"
    :items="items"
    :fields="fields"
  >
  </b-table>
</div>
</script>

<script type="text/template" id="my-container-template">
<my-table :items="items"></my-table>
</script>
</code>```

JavaScript

```<code>Vue.component('my-table', {
  template: document.getElementById('my-table-template'),
  data() {
    return {
      sortBy: 'age',
      sortDesc: false,
      fields: [
        { key: 'last_name', sortable: true },
        { key: 'first_name', sortable: true },
        { key: 'age', sortable: true },
        { key: 'isActive', sortable: false }
      ]
    }
  },
  props: {
    items: Array
  }
})

Vue.component('my-container', {
  template: document.getElementById('my-container-template'),
  data() {
    return {
      items: []
    }
  },
  created() {
    // of course, there could be other events that would cause a data refresh
    this.fetchData()
  },
  methods: {
    fetchData() {
      // you should use your real request instead of a timeout here
      setTimeout(() => {
        this.items = [
        { isActive: true,  age: 40, first_name: 'Dickerson', last_name: 'Macdonald' },
        { isActive: false, age: 21, first_name: 'Larsen', last_name: 'Shaw' },
        { isActive: false, age: 89, first_name: 'Geneva', last_name: 'Wilson' },
        { isActive: true,  age: 38, first_name: 'Jami', last_name: 'Carney' }
        ]
      }, 1000)
    }
  }
})

const app = new Vue({
  el: '#app'
})
</code>```

As I said, it's a good idea to separate responsibility in your app broadly into components responsible for fetching and providing data (container components) and components that just render any data they are given, without any side-effects (presentational components).

You can think of container components' role as context providers - just consider how in the example above you can have more than one table (or varied other components) use the same data.

Body:
I'm developing in Vue2 using the 1 file = 1 component scheme.

Using a Bootstrap-Vue Table Component, I'm using the provider to pass it an items.

The issue is that when I use the sort button the sort one time out of a couple (if I press sort too fast) the sort fails because the API call for the list is called again and the list is displayed anew.

How would I correct this.

Do I need to design it another way?

my code :

<b-table small fixed bordered striped hover show-empty
             :no-provider-paging="true"
             :no-provider-sorting="false"
             :no-provider-filtering="true"
             :busy.sync="isBusy"
             :items="allergyIntolerance"
             :fields="fields"
             :current-page="currentPage"
             :per-page="perPage"
             :filter="filter"
             :sort-by.sync="sortBy"
             :sort-desc.sync="sortDesc"
             @filtered="onFiltered"
    >
      <template slot="identifiant" slot-scope="row">{{row.item.content._id}}</template>
      <template slot="patient" slot-scope="row">{{row.item.content.patient.reference}}</template>
      <template slot="practitioner" slot-scope="row">{{row.item.content.recorder.reference}}</template>
      <template slot="category" slot-scope="row">{{row.item.content.category}}</template>
      <template slot="status" slot-scope="row">{{row.item.content.clinicalStatus}}</template>
      <template slot="critical" slot-scope="row">{{row.item.content.criticality}}</template>
      <template slot="actions" slot-scope="row">
      <button class="btn btn-xs btn-success" @click.stop="details(row.item,row.index,$event.target)">

      </button>
      <button class="btn btn-xs btn-primary" @click.stop="edit(row.item,row.index,$event.target)">

      </button>
      <button class="btn btn-xs btn-danger" @click.stop="del(row.item,row.index,$event.target)">

      </button>
      </template>

note that if I pass :no-provider-sorting to true it no longer sorts.

every other option is working as intended.

allergyIntolerance (ctx) {
      var token = 'JWT eyJtokentokentokens'
      let promise = axios.get('http://localhost:3000/api/allergyintolerance/', {headers: { 'Authorization': token }})

      return promise.then(response => {
        const items = response.data.entry
        this.totalRows = items.length
        return (items)
      })
      .catch(error => {
        console.log(error.response)
        return []
      })
    }

Body:
I recommend moving the data provision out of the table component itself. You may create a wrapper component which loads the table in a default state, fetches the data and updates the table on complete.
The table should otherwise be pretty dumb and not care about much else than rendering the data its given.

If you need a managed way to do this have a look at vuex, which also supports async actions.

Edit: I've attached a simple example. It should be pretty straightforward to translate to your setup.

HTML

<div id="app">
  <my-container></my-container>
</div>

<script type="text/template" id="my-table-template">
<div>
  <b-table
    :sort-by.sync="sortBy"
    :sort-desc.sync="sortDesc"
    :items="items"
    :fields="fields"
  >
  </b-table>
</div>
</script>

<script type="text/template" id="my-container-template">
<my-table :items="items"></my-table>
</script>

JavaScript

Vue.component('my-table', {
  template: document.getElementById('my-table-template'),
  data() {
    return {
      sortBy: 'age',
      sortDesc: false,
      fields: [
        { key: 'last_name', sortable: true },
        { key: 'first_name', sortable: true },
        { key: 'age', sortable: true },
        { key: 'isActive', sortable: false }
      ]
    }
  },
  props: {
    items: Array
  }
})

Vue.component('my-container', {
  template: document.getElementById('my-container-template'),
  data() {
    return {
      items: []
    }
  },
  created() {
    // of course, there could be other events that would cause a data refresh
    this.fetchData()
  },
  methods: {
    fetchData() {
      // you should use your real request instead of a timeout here
      setTimeout(() => {
        this.items = [
        { isActive: true,  age: 40, first_name: 'Dickerson', last_name: 'Macdonald' },
        { isActive: false, age: 21, first_name: 'Larsen', last_name: 'Shaw' },
        { isActive: false, age: 89, first_name: 'Geneva', last_name: 'Wilson' },
        { isActive: true,  age: 38, first_name: 'Jami', last_name: 'Carney' }
        ]
      }, 1000)
    }
  }
})

const app = new Vue({
  el: '#app'
})

As I said, it's a good idea to separate responsibility in your app broadly into components responsible for fetching and providing data (container components) and components that just render any data they are given, without any side-effects (presentational components).

You can think of container components' role as context providers - just consider how in the example above you can have more than one table (or varied other components) use the same data.


来源: stackexchange

问:
How to run Postgres tests in parallel with NodeJS, Jest and Knex?
I have a project that was developed using Postgres in production/staging and Sqlite in development. With Sqlite we were able to run all our tests in parallel in 13 seconds.

This was a great strategy for the initial development, but there are some things that Sqlite just can't do that we need (Eg. dropping columns and adding new foreign keys). So I'm thinking that we should drop Sqlite and just use Postgres.

The test suite takes about a minute to run and if a test fails I routinely have to manually remove the migration tables. It doesn't provide a good testing experience.

Do you have any suggestions for running tests on a Postgres database in parallel using NodeJS, Knex and Jest?

答:
Running migrations and rolling them back before every test is really slow, it might take even seconds to run. So you might not need to be able to run tests parallel to reach good enough speed.

If you setup your tests in a way that you just drop / create / migrate once before starting to run tests and between tests just truncate all data from the tables and populate it with fresh data it should be 10x faster (truncate takes usually around less than 50ms). You can truncate all the tables easily for example with knex-db-manager package.

If you really like to run postgresql tests parallel, you need as many test databases that you are running parallel tests. You could create "pool" of test databases (testdb-1, testdb-2, testdb-3,...) and in each jest test you first have to request database from your test database pool so that you can really run multiple tests at the same time and they wont be interfering with the same database.

Lastly one more pretty fast method to reset data in test database is to use pg-dump / pg-restore and binary db dumps. It might be faster or easier to handle in some cases than just running population scripts. Especially in case, where you are using the same initial data in every test.

In this way you create initial state for the test database before starting to run tests and take dump of it. For dumping and restoring I wrote these small helpers, which I might add to knex-db-manager at some point.

Parameter for dumping / restoring are a bit tricky (specially setting the password) so these snippets might help:

Dumping:

```<code>      shelljs.env.PGPASSWORD = config.knex.connection.password;
      const leCommand = [
        `pg_dump -a -O -x -F c`,
        `-f '${dumpFileName}'`,
        `-d ${config.knex.connection.database}`,
        `-h ${config.knex.connection.host}`,
        `-p ${config.knex.connection.port}`,
        `-U ${config.knex.connection.user}`,
      ].join(' ');

      console.log('>>>>>>>> Command started:', leCommand);
      shelljs.rm('-f', dumpFileName);
      shelljs.exec(leCommand, (code, stdout, stderr) => {
        console.log('======= Command ready:', leCommand, 'with exit code:', code);
        if (code === 0) {
          console.log('dump ready:', stdout);
        } else {
          console.log('dump failed:', stderr);
        }
      });
</code>```

Restore:

```<code>  shelljs.env.PGPASSWORD = config.knex.connection.password;
  const leCommand = [
    `pg_restore -a -O -x -F c`,
    `-d ${config.knex.connection.database}`,
    `-h ${config.knex.connection.host}`,
    `-p ${config.knex.connection.port}`,
    `-U ${config.knex.connection.user}`,
    `--disable-triggers`,
    `'${dumpFileName}'`,
  ].join(' ');

  console.log('>>>>>>>> Command started:', leCommand);
  shelljs.exec(leCommand, (code, stdout, stderr) => {
    console.log('======= Command ready:', leCommand, 'with exit code:', code);
    if (code === 0) {
      console.log('restore ready:', stdout);
    } else {
      console.log('restore failed:', stderr);
    }
  });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Running migrations and rolling them back before every test is really slow, it might take even seconds to run. So you might not need to be able to run tests parallel to reach good enough speed.

If you setup your tests in a way that you just drop / create / migrate once before starting to run tests and between tests just truncate all data from the tables and populate it with fresh data it should be 10x faster (truncate takes usually around less than 50ms). You can truncate all the tables easily for example with knex-db-manager package.

If you really like to run postgresql tests parallel, you need as many test databases that you are running parallel tests. You could create "pool" of test databases (testdb-1, testdb-2, testdb-3,...) and in each jest test you first have to request database from your test database pool so that you can really run multiple tests at the same time and they wont be interfering with the same database.

Lastly one more pretty fast method to reset data in test database is to use pg-dump / pg-restore and binary db dumps. It might be faster or easier to handle in some cases than just running population scripts. Especially in case, where you are using the same initial data in every test.

In this way you create initial state for the test database before starting to run tests and take dump of it. For dumping and restoring I wrote these small helpers, which I might add to knex-db-manager at some point.

Parameter for dumping / restoring are a bit tricky (specially setting the password) so these snippets might help:

Dumping:

      shelljs.env.PGPASSWORD = config.knex.connection.password;
      const leCommand = [
        `pg_dump -a -O -x -F c`,
        `-f '${dumpFileName}'`,
        `-d ${config.knex.connection.database}`,
        `-h ${config.knex.connection.host}`,
        `-p ${config.knex.connection.port}`,
        `-U ${config.knex.connection.user}`,
      ].join(' ');

      console.log('>>>>>>>> Command started:', leCommand);
      shelljs.rm('-f', dumpFileName);
      shelljs.exec(leCommand, (code, stdout, stderr) => {
        console.log('======= Command ready:', leCommand, 'with exit code:', code);
        if (code === 0) {
          console.log('dump ready:', stdout);
        } else {
          console.log('dump failed:', stderr);
        }
      });

Restore:

  shelljs.env.PGPASSWORD = config.knex.connection.password;
  const leCommand = [
    `pg_restore -a -O -x -F c`,
    `-d ${config.knex.connection.database}`,
    `-h ${config.knex.connection.host}`,
    `-p ${config.knex.connection.port}`,
    `-U ${config.knex.connection.user}`,
    `--disable-triggers`,
    `'${dumpFileName}'`,
  ].join(' ');

  console.log('>>>>>>>> Command started:', leCommand);
  shelljs.exec(leCommand, (code, stdout, stderr) => {
    console.log('======= Command ready:', leCommand, 'with exit code:', code);
    if (code === 0) {
      console.log('restore ready:', stdout);
    } else {
      console.log('restore failed:', stderr);
    }
  });


问:
What is the better way of including a header file? #include<> followed by #include"" or the otherwise?

Possible Duplicates:

  what is the difference between #include <filename> and #include “filename”

  C/C++ include file order/best practices

In what order should the include statements in a header file and source file come in C++? #include <> followed by #include "" or the otherwise?

Also, should the header file of a source file precede all include statements in source file?

答:
A general rule of thumb is to include headers in an order so as to maximize the chance of detecting that one of your own headers fails to itself include all that it needs. I.e. include that first. But since it's impossible to do that for all headers that you include, this is just a kind of vague guideline that doesn't hurt and might do some good.

When you have many headers, try to be a bit more systematic.

Like, group them by what they achieve (like [windows.h] followed by some MS header that requires [windows.h]), and/or alphabetically.

In the end, just don't use too much time on this. :-)

Cheers & hth.,

ContentLicense: CC BY-SA 2.5


问:
PHP Laravel 5 elseif not behaving as expected
I have 2 variables that can either be filled with a value, be 'all' or be 'null'

Variable 1 is $type and variable 2 is $brand.

So if the user selects a type and a brand I want to query the cars accordingly. If the users selects nothing then the value is 'null' if the user selects 'all' then the value is 'all' obviously.

I've wrote the 4 scenario's out in commented code as follows:

```<code>//brand                 and type                -> get cars of brand and type
//brand = all or null   and type = all or null  -> get all cars
//brand                 and type = all or null  -> get cars of all types and brand
//brand = all or null   and type                -> get cars of all brands and type
</code>```

this is my if structure:

```<code>if ($brand && $type) {
            $cars = Cars::where([
                ['cost', '<=', $budget],
                ['brand', '=', $brand],
                ['type', '=', $type]
            ])->get();
} elseif($brand == 'all' || $brand === null && $type == 'all' || $type === null) {
            $cars = Cars::where('cost', '<=', $budget)
                ->get();
} elseif($brand && $type == 'all' || $type === null) {
            $cars = Cars::where([
                ['cost', '<=', $budget],
                ['brand', '=', $brand],
            ])->get();
} elseif ($brand == 'all' || $brand === null && $type) {
            $cars = Cars::where([
                ['cost', '<=', $budget],
                ['type', '=', $type]
            ])->get();
}
</code>```

Now when I check the value of $brand it's filled with Audi and $type is null.

Can someone please explain to me why I get the result of the first elseif?
So my code thinks this is the case:

elseif($brand == 'all' || $brand === null && $type == 'all' || $type === null) {

Which is weird because $brand is neither 'all' or 'null' since it's 'Audi'

Hope it's clear.

答:
According to operators precedence table, your first elseif condition

```<code>$brand == 'all' || $brand === null && $type == 'all' || $type === null
</code>```

is treated as:

```<code>($brand == 'all') || ($brand === null && $type == 'all') || ($type === null)
</code>```

With values $brand = Audi and $type = null it is true:

```<code>(false || false || true) -> true
</code>```

That's why you need to put parentheses so php can understand your logic and not apply it's own.

Body:
I have 2 variables that can either be filled with a value, be 'all' or be 'null'

Variable 1 is $type and variable 2 is $brand.

So if the user selects a type and a brand I want to query the cars accordingly. If the users selects nothing then the value is 'null' if the user selects 'all' then the value is 'all' obviously.

I've wrote the 4 scenario's out in commented code as follows:

//brand                 and type                -> get cars of brand and type
//brand = all or null   and type = all or null  -> get all cars
//brand                 and type = all or null  -> get cars of all types and brand
//brand = all or null   and type                -> get cars of all brands and type

this is my if structure:

if ($brand && $type) {
            $cars = Cars::where([
                ['cost', '<=', $budget],
                ['brand', '=', $brand],
                ['type', '=', $type]
            ])->get();
} elseif($brand == 'all' || $brand === null && $type == 'all' || $type === null) {
            $cars = Cars::where('cost', '<=', $budget)
                ->get();
} elseif($brand && $type == 'all' || $type === null) {
            $cars = Cars::where([
                ['cost', '<=', $budget],
                ['brand', '=', $brand],
            ])->get();
} elseif ($brand == 'all' || $brand === null && $type) {
            $cars = Cars::where([
                ['cost', '<=', $budget],
                ['type', '=', $type]
            ])->get();
}

Now when I check the value of $brand it's filled with Audi and $type is null.

Can someone please explain to me why I get the result of the first elseif?
So my code thinks this is the case:

elseif($brand == 'all' || $brand === null && $type == 'all' || $type === null) {

Which is weird because $brand is neither 'all' or 'null' since it's 'Audi'

Hope it's clear.

Body:
According to operators precedence table, your first elseif condition

$brand == 'all' || $brand === null && $type == 'all' || $type === null

is treated as:

($brand == 'all') || ($brand === null && $type == 'all') || ($type === null)

With values $brand = Audi and $type = null it is true:

(false || false || true) -> true

That's why you need to put parentheses so php can understand your logic and not apply it's own.


问:
Description of for-break code
It is much appreciated if describe this code for each line</p>

```<code>count = 20
for x in range(0,10):
      count = count - 1
      if x == 2: break
print(count)
</code>```

答:
Line 1: Variable Assignement, click here

Line 2a: a for loop, click here

Line 2b: range function, click here

Line 3: Variable Assignment, see same link as Line 1

Line 4a: if statement, see same link as Line 2a

Line 4b: break function, see same link as Line 2a

Line 5: print function, click here

Title: Description of for-break code

Body:
It is much appreciated if describe this code for each line

count = 20
for x in range(0,10):
      count = count - 1
      if x == 2: break
print(count)


问:
Java how a class A can have multiple potential extends
Hello i have a problematic about inheritance.

Let's have this three :

```<code>           A
         /   \
        /     \
       B       C
       \       /
        \     /
           ?
           |
           D

    abstract class A {
        public abstract void print();
        public abstract int getInt();
    }

    abstract class B extends A {
        @Override
        public int getInt() {
          return 5;
        }
    }

    abstract class C extends A {
        @Override
        public int getInt() {
           return 1;
        }
    }

    class D extends B || C {
        @Override
        public void print() {
         console.log(this.getInt());
       }
    }
</code>```

I want add a class D who can herit from B or C.

And when i create a new D(), i could choose the parent. I don't want use multiple inheritance (well java can't do it too), i would like to use a way to add specific comportment on a class by changing the implementation of his parent.

In fact D should herit from A but with the special implementation of B or C that i could choose at runtime. We can consider that B and C doesn't allow to implement other method than A one.

is that possible ?

答:
C++ has multiple inheritance, and when Java was designed, instead of multiple inheritance interfaces were introduced, to provide a code alternative, and prevent ambiguity and other concerns with multiple inheritance.

One could use delegation instead, then the strategy of resolving the correct multiple calls is with the class.

```<code>class D extends A {
    B b;
    C c;

    @Override
    public int getInt() {
      return b.getInt() + c.getInt();
    }
    ...
}

class D extends A {
    A delegatee;

    public final void iAmReally(A a) {
        delegatee = a;
    }

    @Override
    public int getInt() {
      return delegatee.getInt();
    }
    ...
}
</code>```

Body:
Hello i have a problematic about inheritance.

Let's have this three :

           A
         /   \
        /     \
       B       C
       \       /
        \     /
           ?
           |
           D

    abstract class A {
        public abstract void print();
        public abstract int getInt();
    }

    abstract class B extends A {
        @Override
        public int getInt() {
          return 5;
        }
    }

    abstract class C extends A {
        @Override
        public int getInt() {
           return 1;
        }
    }

    class D extends B || C {
        @Override
        public void print() {
         console.log(this.getInt());
       }
    }

I want add a class D who can herit from B or C.

And when i create a new D(), i could choose the parent. I don't want use multiple inheritance (well java can't do it too), i would like to use a way to add specific comportment on a class by changing the implementation of his parent.

In fact D should herit from A but with the special implementation of B or C that i could choose at runtime. We can consider that B and C doesn't allow to implement other method than A one.

is that possible ?

Body:
C++ has multiple inheritance, and when Java was designed, instead of multiple inheritance interfaces were introduced, to provide a code alternative, and prevent ambiguity and other concerns with multiple inheritance.

One could use delegation instead, then the strategy of resolving the correct multiple calls is with the class.

class D extends A {
    B b;
    C c;

    @Override
    public int getInt() {
      return b.getInt() + c.getInt();
    }
    ...
}

class D extends A {
    A delegatee;

    public final void iAmReally(A a) {
        delegatee = a;
    }

    @Override
    public int getInt() {
      return delegatee.getInt();
    }
    ...
}


问:
Problems deploying Hibernate OGM for Mongodb persistence on Wildfly 10.1.0
I am getting an error when deploying an application on Wildfly 10.1.0 when using a Hibernate OGM persistence unit for Mongodb. After trying several combinations of modules and configuration, I am following the answer to this post.

I believe I have the modules organized correctly. The jboss-deployment-structure looks like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<jboss-deployment-structure xmlns="urn:jboss:deployment-structure:1.1">
  <deployment>
    <dependencies>
      <module name="org.hibernate.ogm.mongodb" services="import" />
      <module name="org.hibernate.search.orm" services="import" />
      <module name="org.hibernate.search.engine" slot="5.6" services="import" />
    </dependencies>
  </deployment>
</jboss-deployment-structure>
</code>```

My persistence unit looks like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0">

  <persistence-unit name="ogm-mongodb" transaction-type="JTA">
    <provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider>
    <class>org.secomm.authenticator.persistence.ServerVault</class>
    <properties>
      <property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossAppServerJtaPlatform" />
      <property name="hibernate.ogm.datastore.provider" value="mongodb" />
      <property name="hibernate.ogm.datastore.database" value="mydatabase"/>
      <property name="hibernate.ogm.datastore.host" value="myhost"/>
      <property name="hibernate.ogm.datastore.username" value="***" />
      <property name="hibernate.ogm.datastore.password" value="***"/>
    </properties>
  </persistence-unit>
</persistence>
</code>```

I get an error indicating that the Hibernate 5.1 module is missing:

```<code>ERROR [org.jboss.as.controller.management-operation] (External Management Request Threads -- 1) WFLYCTL0013: Operation ("add") failed - address: ([("deployment" => "secomm-enterprise-ear-1.0-SNAPSHOT.ear")]) - failure description: {
"WFLYCTL0080: Failed services" => {
    "jboss.module.service.\"deployment.secomm-enterprise-ear-1.0-SNAPSHOT.ear.secomm-api-rest-1.0-SNAPSHOT.war\".main" => "org.jboss.msc.service.StartException in service jboss.module.service.\"deployment.secomm-enterprise-ear-1.0-SNAPSHOT.ear.secomm-api-rest-1.0-SNAPSHOT.war\".main: WFLYSRV0179: Failed to load module: deployment.secomm-enterprise-ear-1.0-SNAPSHOT.ear.secomm-api-rest-1.0-SNAPSHOT.war:main
Caused by: org.jboss.modules.ModuleNotFoundException: org.hibernate:5.1"
</code>```

There doesn't seem to be a single, coherent hibernate 5.1 modules package. If I start trying to add in the Hibernate modules manually, it leads down a rabbit hole of search engine dependencies that ends up giving me an error about a SPI integrator class not being a subtype.

Any help with this is appreciated.

答:
This is the module you have to download and add to WildFly:

<groupId>org.hibernate</groupId>
<artifactId>hibernate-orm-modules</artifactId>
<version>5.1.10.Final</version>
<classifier>wildfly-10-dist</classifier>

Extract it in $WILDFLY_HOME/modules and it should work.
If you are not using maven, you can download it from the JBoss Nexus repository: https://repository.jboss.org/nexus/content/groups/public/org/hibernate/hibernate-orm-modules/5.1.10.Final/hibernate-orm-modules-5.1.10.Final-wildfly-10-dist.zip

Body:
I am getting an error when deploying an application on Wildfly 10.1.0 when using a Hibernate OGM persistence unit for Mongodb. After trying several combinations of modules and configuration, I am following the answer to this post.

I believe I have the modules organized correctly. The jboss-deployment-structure looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<jboss-deployment-structure xmlns="urn:jboss:deployment-structure:1.1">
  <deployment>
    <dependencies>
      <module name="org.hibernate.ogm.mongodb" services="import" />
      <module name="org.hibernate.search.orm" services="import" />
      <module name="org.hibernate.search.engine" slot="5.6" services="import" />
    </dependencies>
  </deployment>
</jboss-deployment-structure>

My persistence unit looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0">

  <persistence-unit name="ogm-mongodb" transaction-type="JTA">
    <provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider>
    <class>org.secomm.authenticator.persistence.ServerVault</class>
    <properties>
      <property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossAppServerJtaPlatform" />
      <property name="hibernate.ogm.datastore.provider" value="mongodb" />
      <property name="hibernate.ogm.datastore.database" value="mydatabase"/>
      <property name="hibernate.ogm.datastore.host" value="myhost"/>
      <property name="hibernate.ogm.datastore.username" value="***" />
      <property name="hibernate.ogm.datastore.password" value="***"/>
    </properties>
  </persistence-unit>
</persistence>

I get an error indicating that the Hibernate 5.1 module is missing:

ERROR [org.jboss.as.controller.management-operation] (External Management Request Threads -- 1) WFLYCTL0013: Operation ("add") failed - address: ([("deployment" => "secomm-enterprise-ear-1.0-SNAPSHOT.ear")]) - failure description: {
"WFLYCTL0080: Failed services" => {
    "jboss.module.service.\"deployment.secomm-enterprise-ear-1.0-SNAPSHOT.ear.secomm-api-rest-1.0-SNAPSHOT.war\".main" => "org.jboss.msc.service.StartException in service jboss.module.service.\"deployment.secomm-enterprise-ear-1.0-SNAPSHOT.ear.secomm-api-rest-1.0-SNAPSHOT.war\".main: WFLYSRV0179: Failed to load module: deployment.secomm-enterprise-ear-1.0-SNAPSHOT.ear.secomm-api-rest-1.0-SNAPSHOT.war:main
Caused by: org.jboss.modules.ModuleNotFoundException: org.hibernate:5.1"

There doesn't seem to be a single, coherent hibernate 5.1 modules package. If I start trying to add in the Hibernate modules manually, it leads down a rabbit hole of search engine dependencies that ends up giving me an error about a SPI integrator class not being a subtype.

Any help with this is appreciated.


问:
Idexing pdf files using PDF-Paragraph converter
When i index pdf files and using PDF-Paragraph converter WEX put a default title on all documents the (title). How can i modify this title using xpath?
On the search page all documents has the same title.</p>

答:
It is not possible

http://www-01.ibm.com/support/docview.wss?uid=swg22009088

check it we need to create a new custom java converter for your reqirement


问:
How to get the task's field in the RejectedExecutionHandler?
I want to know the Task which is rejected by the executor.For example,i want to get the name of the rejected task.But in the RejectedExecutionHandler,i can't do this!

Here is my code:

```<code>public static void main(String[] args) throws Exception{
    ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 1L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(),
            (Runnable r, ThreadPoolExecutor executor1) -> {
                //TODO
                //want to get the task name
                System.out.println("in reject:");
    });
    Task t1 = new Task("t1");
    Task t2 = new Task("t2");
    Future<Integer> t1Fe = executor.submit(t1);
    Future<Integer> t2Fe =  executor.submit(t2);

    System.out.println(t1Fe.get());
    System.out.println(t2Fe.get());
}

static class Task implements Callable{
    private String name;

    public Task(String name) {
        this.name = name;
    }

    @Override
    public Object call() throws Exception {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(1);
        return name;
    }
}
</code>```

答:
I override the submit method and override the FutureTask class!

```<code>public static void main(String[] args) throws Exception{
    ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 1L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(),
            (Runnable r, ThreadPoolExecutor executor1) -> {
                //TODO
                //want to get the task name
                MyFutureTask task = (MyFutureTask)r;
                System.out.println("in reject:"+task.name);
    });
    Task t1 = new Task("t1");
    Task t2 = new Task("t2");
    Future<Integer> t1Fe = submit(executor,t1);
    Future<Integer> t2Fe =  submit(executor,t2);

    System.out.println(t1Fe.get());
    System.out.println(t2Fe.get());
}

public static Future submit(ThreadPoolExecutor executor,Callable task) {
    if (task == null) throw new NullPointerException();
    MyFutureTask ftask = new MyFutureTask(task);
    ftask.setName(((Task)task).name);
    executor.execute(ftask);
    return ftask;
}

static class MyFutureTask extends FutureTask{
    private String name;
    public MyFutureTask(Callable callable) {
        super(callable);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
static class Task implements Callable{
    private String name;

    public Task(String name) {
        this.name = name;
    }

    @Override
    public Object call() throws Exception {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(1);
        return name;
    }
}
</code>```

Body:
I want to know the Task which is rejected by the executor.For example,i want to get the name of the rejected task.But in the RejectedExecutionHandler,i can't do this!

Here is my code:

public static void main(String[] args) throws Exception{
    ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 1L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(),
            (Runnable r, ThreadPoolExecutor executor1) -> {
                //TODO
                //want to get the task name
                System.out.println("in reject:");
    });
    Task t1 = new Task("t1");
    Task t2 = new Task("t2");
    Future<Integer> t1Fe = executor.submit(t1);
    Future<Integer> t2Fe =  executor.submit(t2);

    System.out.println(t1Fe.get());
    System.out.println(t2Fe.get());
}

static class Task implements Callable{
    private String name;

    public Task(String name) {
        this.name = name;
    }

    @Override
    public Object call() throws Exception {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(1);
        return name;
    }
}

Body:
I override the submit method and override the FutureTask class!

public static void main(String[] args) throws Exception{
    ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 1L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(),
            (Runnable r, ThreadPoolExecutor executor1) -> {
                //TODO
                //want to get the task name
                MyFutureTask task = (MyFutureTask)r;
                System.out.println("in reject:"+task.name);
    });
    Task t1 = new Task("t1");
    Task t2 = new Task("t2");
    Future<Integer> t1Fe = submit(executor,t1);
    Future<Integer> t2Fe =  submit(executor,t2);

    System.out.println(t1Fe.get());
    System.out.println(t2Fe.get());
}

public static Future submit(ThreadPoolExecutor executor,Callable task) {
    if (task == null) throw new NullPointerException();
    MyFutureTask ftask = new MyFutureTask(task);
    ftask.setName(((Task)task).name);
    executor.execute(ftask);
    return ftask;
}

static class MyFutureTask extends FutureTask{
    private String name;
    public MyFutureTask(Callable callable) {
        super(callable);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
static class Task implements Callable{
    private String name;

    public Task(String name) {
        this.name = name;
    }

    @Override
    public Object call() throws Exception {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(1);
        return name;
    }
}


问:
Defining main page using OWIN static files
I have a self-hosted app with the help of OWIN. Also, I need to serve some static files. It works but recently I faced a problem - default files stopped working. I mean earlier if you go to localhost it would redirect you to "main" page. But now the main page is only accessible with the direct path e.g. https://localhost:4443/index.html

Here is my Startup method:

```<code>public class Startup
{

    // This code configures Web API. The Startup class is specified as a type
    // parameter in the WebApp.Start method.
    public void Configuration(IAppBuilder appBuilder)
    {
        try
        {
            appBuilder.UseOAuthAuthorizationServer(new OAuthOptions());
            appBuilder.UseJwtBearerAuthentication(new JwtOptions());

            var config = new MyHttpsSelfHostConfiguration("https://localhost:4443");

            var start = DateTime.Now;

            config.MapHttpAttributeRoutes();
            var jsonFormatter = new JsonMediaTypeFormatter();
            config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));

            config.Routes.MapHttpRoute(
                name: "WebLabApp",
                routeTemplate: "api/{controller}/{action}/{id}"
            );

            ConfigureUnity(config);
            appBuilder.UseWebApi(config);

            Console.WriteLine($"Configure Unity in {DateTime.Now - start}");
            start = DateTime.Now;

            BusinessServicesHostLibrary.ContainerRegistry.RegisterAllBusinessServicesCommonClassesAndConnectionFactory();
            Console.WriteLine($"Register all in {DateTime.Now - start}");
            #if DEBUG
            var contentDir = Directory.GetParent(Directory.GetCurrentDirectory()).Parent?.FullName;
            #else
            var contentDir = @".";
            #endif
            var fileSystem = new PhysicalFileSystem(contentDir);
            var options = new FileServerOptions
            {
                EnableDefaultFiles = true,
                DefaultFilesOptions = { DefaultFileNames = { "index.html" } },
                FileSystem = fileSystem,
            };
            options.StaticFileOptions.FileSystem = fileSystem;
            options.StaticFileOptions.ServeUnknownFileTypes = true;
            appBuilder.UseFileServer(options);
            config.EnsureInitialized();
        }
        catch (Exception ex)
        {
            if (ex is System.Reflection.ReflectionTypeLoadException)
            {
                var typeLoadException = ex as ReflectionTypeLoadException;
                var loaderExceptions = typeLoadException.LoaderExceptions;
                foreach (var x in loaderExceptions) Console.WriteLine(x);
            }
            throw;
        }
    }
</code>```

What am I doing wrong?

答:
The solution is quite simple - we need to call             appBuilder.UseWebApi(config);
at the end of Configuration method

Body:
I have a self-hosted app with the help of OWIN. Also, I need to serve some static files. It works but recently I faced a problem - default files stopped working. I mean earlier if you go to localhost it would redirect you to "main" page. But now the main page is only accessible with the direct path e.g. https://localhost:4443/index.html

Here is my Startup method:

public class Startup
{

    // This code configures Web API. The Startup class is specified as a type
    // parameter in the WebApp.Start method.
    public void Configuration(IAppBuilder appBuilder)
    {
        try
        {
            appBuilder.UseOAuthAuthorizationServer(new OAuthOptions());
            appBuilder.UseJwtBearerAuthentication(new JwtOptions());

            var config = new MyHttpsSelfHostConfiguration("https://localhost:4443");

            var start = DateTime.Now;

            config.MapHttpAttributeRoutes();
            var jsonFormatter = new JsonMediaTypeFormatter();
            config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));

            config.Routes.MapHttpRoute(
                name: "WebLabApp",
                routeTemplate: "api/{controller}/{action}/{id}"
            );

            ConfigureUnity(config);
            appBuilder.UseWebApi(config);

            Console.WriteLine($"Configure Unity in {DateTime.Now - start}");
            start = DateTime.Now;

            BusinessServicesHostLibrary.ContainerRegistry.RegisterAllBusinessServicesCommonClassesAndConnectionFactory();
            Console.WriteLine($"Register all in {DateTime.Now - start}");
            #if DEBUG
            var contentDir = Directory.GetParent(Directory.GetCurrentDirectory()).Parent?.FullName;
            #else
            var contentDir = @".";
            #endif
            var fileSystem = new PhysicalFileSystem(contentDir);
            var options = new FileServerOptions
            {
                EnableDefaultFiles = true,
                DefaultFilesOptions = { DefaultFileNames = { "index.html" } },
                FileSystem = fileSystem,
            };
            options.StaticFileOptions.FileSystem = fileSystem;
            options.StaticFileOptions.ServeUnknownFileTypes = true;
            appBuilder.UseFileServer(options);
            config.EnsureInitialized();
        }
        catch (Exception ex)
        {
            if (ex is System.Reflection.ReflectionTypeLoadException)
            {
                var typeLoadException = ex as ReflectionTypeLoadException;
                var loaderExceptions = typeLoadException.LoaderExceptions;
                foreach (var x in loaderExceptions) Console.WriteLine(x);
            }
            throw;
        }
    }

What am I doing wrong?


问:
How to prevent fixed positioned element overlapping others elements in css?
Say I have three divs:

```<code><div id="outer"></div>
  <div id="one"></div>
  <div id="two"></div>
  <div id="three"></div>
</div>

#one {
  position:fixed;
  top:0px;
  left:0px;
}

#two {
  width: 80%;
  height:500px;
}

#three {
  width: 80%;
  height:500px;
}
</code>```

Divs "two" and "three" appear to be overlapped by div "one" because of position fixed.

1) What is the best way to make it such that they do not overlap?

2) What is the best way to make it such that my fixed div takes up 100% of the height, even if the user scrolls down? (like a sidebar, preventing any new divs that i want to run along the same side as divs two and three) Does the best way involve floats for #two and #three?

答:
By changing the position from position: fixed; to position: sticky; solved my problem.

```<code>#one{
 position: sticky;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Say I have three divs:

#one {
  position:fixed;
  top:0px;
  left:0px;
}

#two {
  width: 80%;
  height:500px;
}

#three {
  width: 80%;
  height:500px;
}

Divs "two" and "three" appear to be overlapped by div "one" because of position fixed.

1) What is the best way to make it such that they do not overlap?

2) What is the best way to make it such that my fixed div takes up 100% of the height, even if the user scrolls down? (like a sidebar, preventing any new divs that i want to run along the same side as divs two and three) Does the best way involve floats for #two and #three?

Body:
By changing the position from position: fixed; to position: sticky; solved my problem.

#one{
 position: sticky;
}


问:
iPhone - how may I hide a view and let it's space be used by other views (like android visibility = GONE)
Do you know a simple (or not simple) way to hide a view (or anything like a view) and let the other views of the screen use the place left blank ? And make the opposite when showing back that view. Something like Android Visibility = GONE for layers.

Thank you

答: Many UIKit classes have a property hidden that does what you want. It is defined in UIView so you will find it in most visual elements you use.


问:
How to configure a canonical hostname and force https with apache?
I want to always use https and have one canonical domain. The problem is when I make a https connection with a secondary domain everything falls apart because the certificate is for the primary domain. Is there a way to solve this or do I have to buy a certificate all my domains and not just the canonical domain?

Relevant part of my "/etc/apache2/apache2.conf"

```<code># Canonical hostname and always use https
<IfModule mod_rewrite.c>
  RewriteEngine On

  # force https on primary host (works fine)
  # http://primary-host.com -> https://primary-host.com
  RewriteCond %{HTTPS} off
  RewriteCond %{HTTP_HOST} ^primary-host\.com$
  RewriteRule (.*) https://primary-host.com%{REQUEST_URI}

  # force https and redirect to primary host (works fine)
  # http://secondary-host.com -> https://primary-host.com
  RewriteCond %{HTTPS} off
  RewriteCond %{HTTP_HOST} ^secondary-host\.com$
  RewriteRule (.*) https://primary-host.com%{REQUEST_URI}

  # FAIL: Certificate doesn't match and "Bad Request (400)" if accepted!
  # https://secondary-host.com -> https://primary-host.com
  RewriteCond %{HTTPS} on
  RewriteCond %{HTTP_HOST} ^secondary-host\.com$
  RewriteRule (.*) https://primary-host.com%{REQUEST_URI}

</IfModule>
</code>```

答:
Have you tried the following as described here? https://httpd.apache.org/docs/2.4/rewrite/remapping.html

The goal of this rule is to force the use of a particular hostname, in preference to other hostnames which may be used to reach the same site. For example, if you wish to force the use of www.example.com instead of example.com, you might use a variant of the following recipe.

Solution:
  The very best way to solve this doesn't involve mod_rewrite at all, but rather uses the Redirect directive placed in a virtual host for the non-canonical hostname(s).

```<code><VirtualHost *:80>
  ServerName undesired.example.com
  ServerAlias example.com notthis.example.com

   Redirect "/" "http://www.example.com/"
</VirtualHost>

<VirtualHost *:80>
  ServerName www.example.com
</VirtualHost>
</code>```

OR in short

```<code><If "%{HTTP_HOST} != 'www.example.com'">
    Redirect "/" "http://www.example.com/"
</If>
</code>```

Body:
I want to always use https and have one canonical domain. The problem is when I make a https connection with a secondary domain everything falls apart because the certificate is for the primary domain. Is there a way to solve this or do I have to buy a certificate all my domains and not just the canonical domain?

Relevant part of my "/etc/apache2/apache2.conf"

# Canonical hostname and always use https
<IfModule mod_rewrite.c>
  RewriteEngine On

  # force https on primary host (works fine)
  # http://primary-host.com -> https://primary-host.com
  RewriteCond %{HTTPS} off
  RewriteCond %{HTTP_HOST} ^primary-host\.com$
  RewriteRule (.*) https://primary-host.com%{REQUEST_URI}

  # force https and redirect to primary host (works fine)
  # http://secondary-host.com -> https://primary-host.com
  RewriteCond %{HTTPS} off
  RewriteCond %{HTTP_HOST} ^secondary-host\.com$
  RewriteRule (.*) https://primary-host.com%{REQUEST_URI}

  # FAIL: Certificate doesn't match and "Bad Request (400)" if accepted!
  # https://secondary-host.com -> https://primary-host.com
  RewriteCond %{HTTPS} on
  RewriteCond %{HTTP_HOST} ^secondary-host\.com$
  RewriteRule (.*) https://primary-host.com%{REQUEST_URI}

</IfModule>

Body:
Have you tried the following as described here? https://httpd.apache.org/docs/2.4/rewrite/remapping.html

The goal of this rule is to force the use of a particular hostname, in preference to other hostnames which may be used to reach the same site. For example, if you wish to force the use of www.example.com instead of example.com, you might use a variant of the following recipe.

Solution:
  The very best way to solve this doesn't involve mod_rewrite at all, but rather uses the Redirect directive placed in a virtual host for the non-canonical hostname(s).

<VirtualHost *:80>
  ServerName undesired.example.com
  ServerAlias example.com notthis.example.com

   Redirect "/" "http://www.example.com/"
</VirtualHost>

<VirtualHost *:80>
  ServerName www.example.com
</VirtualHost>

OR in short

<If "%{HTTP_HOST} != 'www.example.com'">
    Redirect "/" "http://www.example.com/"
</If>


问:
Form Validation between multiple input fields
So I have a form with multiple input form fields,and a nested form group. In the nested formgroup, the validation should be such that if any one of the three inputs is filled, then the form should be valid. The person can fill either all, or even just one and the form should be valid. My template code is as follows:

```<code> <h3 class="form-title">{{title}}</h3>
<form [formGroup]="formX" novalidate>
    <div formGroupName="brandIdentifier">
        <mat-form-field class="full-width">
            <mat-icon matSuffix color="primary" *ngIf="brandName.valid && brandName.touched">done</mat-icon>
            <mat-icon matSuffix color="primary" *ngIf="brandName.invalid && brandName.touched">close</mat-icon>
            <input matInput type="text" placeholder="Brand Name" formControlName="brandName" />
        </mat-form-field>
        <mat-form-field class="full-width">
            <mat-icon matSuffix color="primary" *ngIf="brandId.valid && brandId.touched">done</mat-icon>
            <mat-icon matSuffix color="primary" *ngIf="brandId.invalid && brandId.touched">close</mat-icon>
            <input matInput type="text" placeholder="Brand Id" formControlName="brandId" />
        </mat-form-field>
        <mat-form-field class="full-width">
            <mat-icon matSuffix color="primary" *ngIf="contentId.valid && contentId.touched">done</mat-icon>
            <mat-icon matSuffix color="primary" *ngIf="contentId.invalid && contentId.touched">close</mat-icon>
            <input matInput type="text" placeholder="Content Id" formControlName="contentId" />
        </mat-form-field>
    </div>
    <mat-form-field class="full-width">
        <mat-icon matSuffix color="primary" *ngIf="startTime.valid && startTime.touched">done</mat-icon>
        <mat-icon matSuffix color="primary" *ngIf="startTime.invalid && startTime.touched">close</mat-icon>
        <input matInput type="text" placeholder="Start Time" formControlName="startTime" />
    </mat-form-field>
    <mat-form-field class="full-width">
        <mat-icon matSuffix color="primary" *ngIf="endTime.valid && endTime.touched">done</mat-icon>
        <mat-icon matSuffix color="primary" *ngIf="endTime.invalid && endTime.touched">close</mat-icon>
        <input matInput type="text" placeholder="End Time" formControlName="endTime" />
    </mat-form-field>

    <button mat-raised-button color="primary" (click)="startAnalysis()" [ngClass]="{'form-valid':formX.valid, 'form-invalid':formX.invalid}">Submit</button>

    ```{{formX.value | json}}```
</form>
</code>```

How would I go about this? using Validator class is a given, but I'm unable to get it optional.

答:
Please follow below steps:

Note: we are just giving idea how you can solve your problem.

import FormsModule, ReactiveFormsModule in module.ts

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
imports: [FormsModule, ReactiveFormsModule]})

Modify your html as given e.g.

                                        User name

                                                User name is required.

                                                User name must be at least 4 characters long.

                                        Password

                                                Password is required.

                                                Password must be at least 6 characters long.

                                        Forget the password ?

```<code>                                <div class="form-group">
                                    <button type="submit" (click)='onSubmit()' dir-btn-click  [disabled]="!loginForm.valid" class="btn btn-inverse btn-block">Sign in</button>
                                </div>

                            </form>
</code>```

Modify code as below in [yourcomponent].ts e.g.:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent {

loginForm: FormGroup;

constructor( private fb: FormBuilder) {
    this.crateLoginForm()
  }

get userName() { return this.loginForm.get('userName'); }
  get password() { return this.loginForm.get('password'); }

crateLoginForm() {
    this.loginForm = this.fb.group({
      userName: ['', [Validators.required, Validators.minLength(4)]],
      password: ['', [Validators.required, Validators.minLength(6)]]
    })
  }

onSubmit() {
    let userName= this.loginForm.value.userName;
    let pwd =this.loginForm.value.password;
  }

}

Body:
So I have a form with multiple input form fields,and a nested form group. In the nested formgroup, the validation should be such that if any one of the three inputs is filled, then the form should be valid. The person can fill either all, or even just one and the form should be valid. My template code is as follows:

{{title}}

<form [formGroup]="formX" novalidate>

        <mat-form-field class="full-width">
            <mat-icon matSuffix color="primary" *ngIf="brandName.valid && brandName.touched">done</mat-icon>
            <mat-icon matSuffix color="primary" *ngIf="brandName.invalid && brandName.touched">close</mat-icon>
            <input matInput type="text" placeholder="Brand Name" formControlName="brandName" />
        </mat-form-field>
        <mat-form-field class="full-width">
            <mat-icon matSuffix color="primary" *ngIf="brandId.valid && brandId.touched">done</mat-icon>
            <mat-icon matSuffix color="primary" *ngIf="brandId.invalid && brandId.touched">close</mat-icon>
            <input matInput type="text" placeholder="Brand Id" formControlName="brandId" />
        </mat-form-field>
        <mat-form-field class="full-width">
            <mat-icon matSuffix color="primary" *ngIf="contentId.valid && contentId.touched">done</mat-icon>
            <mat-icon matSuffix color="primary" *ngIf="contentId.invalid && contentId.touched">close</mat-icon>
            <input matInput type="text" placeholder="Content Id" formControlName="contentId" />
        </mat-form-field>

    <mat-form-field class="full-width">
        <mat-icon matSuffix color="primary" *ngIf="startTime.valid && startTime.touched">done</mat-icon>
        <mat-icon matSuffix color="primary" *ngIf="startTime.invalid && startTime.touched">close</mat-icon>
        <input matInput type="text" placeholder="Start Time" formControlName="startTime" />
    </mat-form-field>
    <mat-form-field class="full-width">
        <mat-icon matSuffix color="primary" *ngIf="endTime.valid && endTime.touched">done</mat-icon>
        <mat-icon matSuffix color="primary" *ngIf="endTime.invalid && endTime.touched">close</mat-icon>
        <input matInput type="text" placeholder="End Time" formControlName="endTime" />
    </mat-form-field>

    <button mat-raised-button color="primary" (click)="startAnalysis()" [ngClass]="{'form-valid':formX.valid, 'form-invalid':formX.invalid}">Submit</button>

{{formX.value | json}}

</form>

How would I go about this? using Validator class is a given, but I'm unable to get it optional.

Body:
Please follow below steps:

Note: we are just giving idea how you can solve your problem.

import FormsModule, ReactiveFormsModule in module.ts

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
imports: [FormsModule, ReactiveFormsModule]})

Modify your html as given e.g.

                                        User name

                                                User name is required.

                                                User name must be at least 4 characters long.

                                        Password

                                                Password is required.

                                                Password must be at least 6 characters long.

                                        Forget the password ?

                                <div class="form-group">
                                    <button type="submit" (click)='onSubmit()' dir-btn-click  [disabled]="!loginForm.valid" class="btn btn-inverse btn-block">Sign in</button>
                                </div>

                            </form>

Modify code as below in [yourcomponent].ts e.g.:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent {

loginForm: FormGroup;

constructor( private fb: FormBuilder) {
    this.crateLoginForm()
  }

get userName() { return this.loginForm.get('userName'); }
  get password() { return this.loginForm.get('password'); }

crateLoginForm() {
    this.loginForm = this.fb.group({
      userName: ['', [Validators.required, Validators.minLength(4)]],
      password: ['', [Validators.required, Validators.minLength(6)]]
    })
  }

onSubmit() {
    let userName= this.loginForm.value.userName;
    let pwd =this.loginForm.value.password;
  }

}


问:
JQuery Datatables Table-tools, remove PDF export
I use the table-tools when creating my datatables. This creates the export functionality for Excel, CSV, PDF and Print. I want to remove the PDF options. How is this done?</p>

```<code><TABLE aria-describedby="DataTables_Table_1_info" role="grid" id="DataTables_Table_1" class="table table-tools table-dynamic dataTable   " style="">
</code>```

答:
This solution has worked for me put it in fnDrawCallback function</p>

```<code>$(tableName).dataTable({

 "fnDrawCallback":function () {
                   var table = $(tableName).DataTable();
                   table.buttons('.buttons-pdf').disable();
                      //or

               $(table.buttons('.buttons-pdf').nodes()).css("display", "none");

            }
});
</code>```

Body:
This solution has worked for me put it in fnDrawCallback function

$(tableName).dataTable({

 "fnDrawCallback":function () {
                   var table = $(tableName).DataTable();
                   table.buttons('.buttons-pdf').disable();
                      //or

               $(table.buttons('.buttons-pdf').nodes()).css("display", "none");

            }
});


问:
How do I use Google Analytics custom events inside my rails controller?
What I want to do is use google analytic's custom event tracking from within my controllers, where the logic is done. I'm not quite sure how to put javascript code in my controller or if it is possible at all. How would I go about putting something like this inside my controller:

```<code>_trackEvent(category, action, opt_label, opt_value, opt_noninteraction)
</code>```

or

```<code>_gaq.push(['_trackEvent', 'Videos', 'Play', 'Gone With the Wind']);
</code>```

thanks! And which one of these should I be using?
EDIT:

Here's how I set it up based on the suggestion:

tracking code partial:

```<code><script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-ACCOUNT']);
  _gaq.push(['_setDomainName', 'sitename.com']);
  _gaq.push(['_trackPageview']);
  <%= render "layouts/ga_events" %>

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
</code>```

_ga_events.html.erb (I added in the "value" parameter)

```<code><% unless session[:events].nil? %>
  <% session[:events].each do |event|%>
     _gaq.push(['_trackEvent', '<%= event[:category]%>', '<%= event[:action]%>', '<%= event[:label]%>', '<%= event[:value]%>']);
  <% end %>
<% end %>

<% session[:events] = Array.new %>
</code>```

application controller (added "value param)

```<code>  protected
    # GA event logger
    def log_event(category, action, label = nil, value = nil)
      session[:events] ||= Array.new
      session[:events] << {:category => category, :action => action, :label => label, :value => value}
    end
</code>```

testing it in my Tasks controller:

```<code>def create
    @task = @user.tasks.build(params[:task])
    @task.author = current_user unless @user == current_user

    if @task.save
        log_event("Tasks", "Created", current_user.email, "123")
        redirect_back tasks_path, :notice => t('tasks.created')
    else
        redirect_back tasks_path, :alert => @task.errors.full_messages
    end
end
</code>```

EDIT: here my GA output code, looks like everything is correct:

```<code><script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA_CODE']);
  _gaq.push(['_setDomainName', 'SUBDOMAIN']);
  _gaq.push(['_trackPageview']);
       _gaq.push(['_trackEvent', 'Priority', 'Created (day)', 'Label info', '']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
</code>```

答:
You can use this great little gem that is called Rack Tracker. It allows you to attach a bunch of popular trackers (GA, GTM, FB Pixel, etc.) to it, and fire associated events through controllers like so:

```<code>def show
  tracker do |t|
    t.google_analytics :send, { type: 'event', category: 'button', action: 'click', label: 'nav-buttons', value: 'X' }
  end
end
</code>```

which becomes:

```<code>ga('send', { 'hitType': 'event', 'eventCategory': 'button', 'eventAction': 'click', 'eventLabel': 'nav-buttons', 'value': 'X' })
</code>```

OR you could use another gem - Gabba, which works in similar fashion:

```<code>Gabba::Gabba.new("UT-1234", "mydomain.com").page_view("something", "track/me")
</code>```

Body:
What I want to do is use google analytic's custom event tracking from within my controllers, where the logic is done. I'm not quite sure how to put javascript code in my controller or if it is possible at all. How would I go about putting something like this inside my controller:

_trackEvent(category, action, opt_label, opt_value, opt_noninteraction)

or

_gaq.push(['_trackEvent', 'Videos', 'Play', 'Gone With the Wind']);

thanks! And which one of these should I be using?
EDIT:

Here's how I set it up based on the suggestion:

tracking code partial:

_ga_events.html.erb (I added in the "value" parameter)

<% unless session[:events].nil? %>
  <% session[:events].each do |event|%>
     _gaq.push(['_trackEvent', '<%= event[:category]%>', '<%= event[:action]%>', '<%= event[:label]%>', '<%= event[:value]%>']);
  <% end %>
<% end %>

<% session[:events] = Array.new %>

application controller (added "value param)

  protected
    # GA event logger
    def log_event(category, action, label = nil, value = nil)
      session[:events] ||= Array.new
      session[:events] << {:category => category, :action => action, :label => label, :value => value}
    end

testing it in my Tasks controller:

def create
    @task = @user.tasks.build(params[:task])
    @task.author = current_user unless @user == current_user

    if @task.save
        log_event("Tasks", "Created", current_user.email, "123")
        redirect_back tasks_path, :notice => t('tasks.created')
    else
        redirect_back tasks_path, :alert => @task.errors.full_messages
    end
end

EDIT: here my GA output code, looks like everything is correct:

Body:
You can use this great little gem that is called Rack Tracker. It allows you to attach a bunch of popular trackers (GA, GTM, FB Pixel, etc.) to it, and fire associated events through controllers like so:

def show
  tracker do |t|
    t.google_analytics :send, { type: 'event', category: 'button', action: 'click', label: 'nav-buttons', value: 'X' }
  end
end

which becomes:

ga('send', { 'hitType': 'event', 'eventCategory': 'button', 'eventAction': 'click', 'eventLabel': 'nav-buttons', 'value': 'X' })

OR you could use another gem - Gabba, which works in similar fashion:

Gabba::Gabba.new("UT-1234", "mydomain.com").page_view("something", "track/me")


问:
Google ReCaptcha V2 ERR_EMPTY_RESPONSE
I try to implement Google's ReCaptcha V2 on my website.

On validate captcha and submit my form I got that error (I replaced IP address) :

Here is my code

```<code><?php
# https://github.com/google/recaptcha - 1.1.3
require_once('autoload.php');
if ($_REQUEST['submit']) {
    //  captcha
        $privatekey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
        $recaptcha = new ReCaptcha\ReCaptcha($privatekey,new ReCaptcha\RequestMethod\CurlPost());

        $resp = $recaptcha->verify($_POST["g-recaptcha-response"], $_SERVER["REMOTE_ADDR"]);
        $class_captcha = ($resp->isSuccess() ? "ok" : "formerreur");
}
?>
<form name="myform" method="post">
    <span class="<?=$class_captcha?>">Anti spam</span>
    <script type="text/javascript" src='https://www.google.com/recaptcha/api.js'></script>
    <div class="g-recaptcha" data-sitekey="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"></div>
    <input type="submit" value="Valider" class="form_acces_ok" />
    <input type="hidden" name="submit" value="1">
</form>
</code>```

This is very hard to debug because there is no messages in logs, no error in console, nothing that can help me.

I also want to clarify that this code is used in others of my websites and ReCaptcha works perfectly.

答:
Ok, guys, we've found the error : nss crashing php-fpm process
For this reason, the curlPost method used in Google's ReCaptcha cause php crash.

hope this help !!

Title: Google ReCaptcha V2 ERR_EMPTY_RESPONSE

Body:
I try to implement Google's ReCaptcha V2 on my website.

On validate captcha and submit my form I got that error (I replaced IP address) :

Here is my code

<?php
# https://github.com/google/recaptcha - 1.1.3
require_once('autoload.php');
if ($_REQUEST['submit']) {
    //  captcha
        $privatekey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
        $recaptcha = new ReCaptcha\ReCaptcha($privatekey,new ReCaptcha\RequestMethod\CurlPost());

        $resp = $recaptcha->verify($_POST["g-recaptcha-response"], $_SERVER["REMOTE_ADDR"]);
        $class_captcha = ($resp->isSuccess() ? "ok" : "formerreur");
}
?>
<form name="myform" method="post">
    <span class="<?=$class_captcha?>">Anti spam

    <input type="submit" value="Valider" class="form_acces_ok" />
    <input type="hidden" name="submit" value="1">
</form>

This is very hard to debug because there is no messages in logs, no error in console, nothing that can help me.

I also want to clarify that this code is used in others of my websites and ReCaptcha works perfectly.


问:
calendar view onclick listener for todays date does not work
How to set a onclick listener for a calendar view for "TODAYS DATE" ? the code is working for onclick yesterdays date or tomorrows date, but it does not work for todays date ? can somebody help on this please ?

Code:

MainActivity.java:

```<code>final CalendarView calendarview=(CalendarView)findViewById(R.id.Calendarview);
final Button selectDate=(Button)findViewById(R.id.Date_seletcion_btn);

selectDate.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub

calendarview.setVisibility(View.VISIBLE);

}
});

calendarview.setClickable(true);

//calendarview.getSelectedDateVerticalBar();
/*calendarview.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {

@Override
public void onSelectedDayChange(CalendarView calendarview, int year, int month,
int day) {
// TODO Auto-generated method stub
int day1, month1, year1;

day1=day;
month1=month;
year1=year;

Calendar calendar=Calendar.getInstance();

clickeddate=calendarview.getDate();
calendar.setTimeInMillis(clickeddate);

//ArrayList<> array=calendar.getTouchables();

Toast.makeText(getApplicationContext(), "Date Selected: " + day,Toast.LENGTH_LONG).show();

Intent homein=new Intent(getApplicationContext(),HomePageActivity.class);

homein.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

homein.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

startActivity(homein);
finish();

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

**XML Code:**

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/Calendar_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="120dp"
android:gravity="center_horizontal"
android:orientation="vertical" >

<!--
<LinearLayout
android:id="@+id/Calendar_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"></LinearLayout>
-->

<Button
android:id="@+id/Date_seletcion_btn"
style="?android:attr/borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:layout_marginTop="20dp"
android:background="@drawable/button_states"
android:text="@string/calendarselection" />

<!--
<DatePicker
android:id="@+id/datepicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
/>
-->

<CalendarView
android:id="@+id/Calendarview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:visibility="gone"
android:clickable="true" />

</LinearLayout>
</code>```

答:
```<code>Calendar disabledCal = Calendar.getInstance();
disabledCal.set(Calendar.DATE, disabledCal.get(Calendar.DATE) - 1);
</code>```

Body:
How to set a onclick listener for a calendar view for "TODAYS DATE" ? the code is working for onclick yesterdays date or tomorrows date, but it does not work for todays date ? can somebody help on this please ?

Code:

MainActivity.java:

final CalendarView calendarview=(CalendarView)findViewById(R.id.Calendarview);
final Button selectDate=(Button)findViewById(R.id.Date_seletcion_btn);

selectDate.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub

calendarview.setVisibility(View.VISIBLE);

}
});

calendarview.setClickable(true);

//calendarview.getSelectedDateVerticalBar();
/*calendarview.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {

@Override
public void onSelectedDayChange(CalendarView calendarview, int year, int month,
int day) {
// TODO Auto-generated method stub
int day1, month1, year1;

day1=day;
month1=month;
year1=year;

Calendar calendar=Calendar.getInstance();

clickeddate=calendarview.getDate();
calendar.setTimeInMillis(clickeddate);

//ArrayList<> array=calendar.getTouchables();

Toast.makeText(getApplicationContext(), "Date Selected: " + day,Toast.LENGTH_LONG).show();

Intent homein=new Intent(getApplicationContext(),HomePageActivity.class);

homein.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

homein.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

startActivity(homein);
finish();

}
}); */

**XML Code:**

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/Calendar_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="120dp"
android:gravity="center_horizontal"
android:orientation="vertical" >

<Button
android:id="@+id/Date_seletcion_btn"
style="?android:attr/borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:layout_marginTop="20dp"
android:background="@drawable/button_states"
android:text="@string/calendarselection" />

<CalendarView
android:id="@+id/Calendarview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:visibility="gone"
android:clickable="true" />

</LinearLayout>


问:
Types of licence in odoo manifest descriptor
Odoo Manifest

I want to know how many types of licence are available in odoo for adding in manifest descriptor. as we see an example below 'license': 'OEEL-1',

```<code>{
    'name': 'Module Name',
    'version': '1.1',
    'installable': True,
    'auto_install': True,
    'license': 'OEEL-1',
}
</code>```

答:
According to the source code, the following values are supported:

GPL-2

GPL-2 or any later version

GPL-3

GPL-3 or any later version

AGPL-3

LGPL-3

Other OSI approved licence

OEEL-1

OPL-1

Other proprietary

Body:
Odoo Manifest

I want to know how many types of licence are available in odoo for adding in manifest descriptor. as we see an example below 'license': 'OEEL-1',

{
    'name': 'Module Name',
    'version': '1.1',
    'installable': True,
    'auto_install': True,
    'license': 'OEEL-1',
}


问:
Select column and exact string match from binary output
I'm looking for an equivalent command in PowerShell:

Linux/macOS:

```<code>cat mmls.txt | awk '{print $3}' | egrep -o '[0,9]{10}' | awk 'NR==1' | sed -e 's/^[0]*//'
</code>```

Source (output of mmls.exe):

```<code>GUID Partition Table (EFI)
Offset Sector: 0
Units are in 512-byte sectors

Slot            Start        End          Length       Description
000:  Meta      0000000000   0000000000   0000000001   Safety Table
001:  -------   0000000000   0000002047   0000002048   Unallocated
002:  Meta      0000000001   0000000001   0000000001   GPT Header
003:  Meta      0000000002   0000000033   0000000032   Partition Table
004:  000       0000002048   0000616447   0000614400   Basic data partition
005:  001       0000616448   0001665023   0001048576   EFI system partition
006:  002       0001665024   0001927167   0000262144   Microsoft reserved partition
007:  003       0001927168   0300832767   0298905600   Basic data partition
008:  004       0300832768   0500117503   0199284736   Basic data partition
009:  -------   0500117504   0500118191   0000000688   Unallocated
</code>```

I would like to extract only the start offset without leading zeroes. With awk 'NR==x' I choose the line number. The columns are separated with 2-3 spaces.

Thanks in advance!

答:
Following selects the first number as per your example

```<code>Select-String -Pattern '\d{10}' -Path mmls.txt |
    ForEach-Object { $PSItem.Matches[0].Value -replace '^0+', '' } |
    Where-Object { $PSItem -ne '' } |
    Select -First 1
</code>```

or a bit more concise

```<code>sls '\d{10}' mmls.txt |
   %{$_.Matches[0].Value -replace '^0+', ''} |
   ? {$_ -ne ''} |
   select -f 1
</code>```

alternative

```<code>gc mmls.txt|%{($_ -split '\s+')[2]}|?{$_.Length -eq 10}|%{$_ -replace '^0+'}|?{$_ -ne ''}|select -first 1
</code>```

Body:
I'm looking for an equivalent command in PowerShell:

Linux/macOS:

cat mmls.txt | awk '{print $3}' | egrep -o '[0,9]{10}' | awk 'NR==1' | sed -e 's/^[0]*//'

Source (output of mmls.exe):

GUID Partition Table (EFI)
Offset Sector: 0
Units are in 512-byte sectors

Slot            Start        End          Length       Description
000:  Meta      0000000000   0000000000   0000000001   Safety Table
001:  -------   0000000000   0000002047   0000002048   Unallocated
002:  Meta      0000000001   0000000001   0000000001   GPT Header
003:  Meta      0000000002   0000000033   0000000032   Partition Table
004:  000       0000002048   0000616447   0000614400   Basic data partition
005:  001       0000616448   0001665023   0001048576   EFI system partition
006:  002       0001665024   0001927167   0000262144   Microsoft reserved partition
007:  003       0001927168   0300832767   0298905600   Basic data partition
008:  004       0300832768   0500117503   0199284736   Basic data partition
009:  -------   0500117504   0500118191   0000000688   Unallocated

I would like to extract only the start offset without leading zeroes. With awk 'NR==x' I choose the line number. The columns are separated with 2-3 spaces.

Thanks in advance!

Body:
Following selects the first number as per your example

Select-String -Pattern '\d{10}' -Path mmls.txt |
    ForEach-Object { $PSItem.Matches[0].Value -replace '^0+', '' } |
    Where-Object { $PSItem -ne '' } |
    Select -First 1

or a bit more concise

sls '\d{10}' mmls.txt |
   %{$_.Matches[0].Value -replace '^0+', ''} |
   ? {$_ -ne ''} |
   select -f 1

alternative

gc mmls.txt|%{($_ -split '\s+')[2]}|?{$_.Length -eq 10}|%{$_ -replace '^0+'}|?{$_ -ne ''}|select -first 1


问:
PHP line break inside of cell remove qoute
This is my PHP

```<code>$val = "";
foreach($data as $v){
  $val .= '"' . $v . "\n" . '"';
}
</code>```

The result is

```<code>//this is inside of cell
sample
"sample
"sample
</code>```

This is correct but I cant figure out how to remove the double quote in "sample. Only the first value dont have a double quote the rest will have a double quote.

EDIT

This is the result of my code

This is what I want

答:
Somthing like this should do the trick </p>

```<code>$i = 0
foreach($data as $v){
  $val .= '"' . $v . "\n" . (count($data) !== $i) ? '"' : '';
  $i++;
}
</code>```

Body:
This is my PHP

$val = "";
foreach($data as $v){
  $val .= '"' . $v . "\n" . '"';
}

The result is

//this is inside of cell
sample
"sample
"sample

This is correct but I cant figure out how to remove the double quote in "sample. Only the first value dont have a double quote the rest will have a double quote.

EDIT

This is the result of my code

This is what I want

Body:
Somthing like this should do the trick

$i = 0
foreach($data as $v){
  $val .= '"' . $v . "\n" . (count($data) !== $i) ? '"' : '';
  $i++;
}


问:
Pythonic way to loop two lists
I have two arrays:

```<code>Array_a = [20, 30, 50, 20]
Array_b = [1 ,2  ,3  , 4]
</code>```

would like to have the following output:

(20, '(1,Days Learning)')
(30, '(2,Days Learning)')
(50, '(3,Days Learning)')
(20, '(4,Days Learning)')
```

<p>My code looks like the following:</p>

```for i,j in zip(Array_a, Array_b):
    msg = (i, "(" + str(j) + ",Days Learning)")
    print(msg)
```

<p>but I would like to have it somehow easier like the way:</p>

```for a, b in []
```

答:
Try this one:

```<code>msg = [(a, '({}, Days Learning)'.format(b)) for a, b in zip(Array_a, Array_b)]
print(msg)
</code>```

Will output:

```<code>[(20, '(1, Days Learning)'), (30, '(2, Days Learning)'), (50, '(3, Days Learning)'), (20, '(4, Days Learning)')]
</code>```

NOTE:

To print the elements line by line you can use print with join and another list-comprehension:

```<code>print('\n'.join(str(m) for m in msg))
</code>```

Title: Pythonic way to loop two lists

Body:
I have two arrays:

Array_a = [20, 30, 50, 20]
Array_b = [1 ,2  ,3  , 4]

would like to have the following output:

(20, '(1,Days Learning)')
(30, '(2,Days Learning)')
(50, '(3,Days Learning)')
(20, '(4,Days Learning)')

My code looks like the following:

for i,j in zip(Array_a, Array_b):
    msg = (i, "(" + str(j) + ",Days Learning)")
    print(msg)

but I would like to have it somehow easier like the way:

for a, b in []

Body:
Try this one:

msg = [(a, '({}, Days Learning)'.format(b)) for a, b in zip(Array_a, Array_b)]
print(msg)

Will output:

[(20, '(1, Days Learning)'), (30, '(2, Days Learning)'), (50, '(3, Days Learning)'), (20, '(4, Days Learning)')]

NOTE:

To print the elements line by line you can use print with join and another list-comprehension:

print('\n'.join(str(m) for m in msg))


问:
Chrome/Internet explorer browser refresh (F5, ctrl+R, refresh arrow etc.) not working using Angular (2+) project on remote server
I have a problem with a simple manual refresh (F5, ctrl+R, refresh arrow etc.) action for a deployed Angular (2+) project on a remote server.

Testing the project locally (development and build prod testet) works perfectly, even when deployed to our intern server, refresh works normally.

On the remote server, any refresh (F5, ctrl+R etc.) is ignored. I get no errors, no page not found, nothing - the browser just stays on the current page with no change or refresh.

In the network tab, it doesn't even send a request to the server.

I can see that the favicon blinks for a millisecond (so something is registered front-end).

The only way I can force the refresh is to change the URL manually.

PS. The only visible differnce is that the remote server runs on https:// protocol.

I have searched for hours on google without any help.

答:
Okay found the problem:

The route request was not handled by the server NginX-configuration which resolved in a body-less 204 which Chrome Developer Tools discarded as invalid, making it look like no request was made.

After removing the 204 error-handling, the error showed in Chrome as a 404, so not an Angular problem :)


问:
Check if all children of div have class
I want to check if all children of different divs (with same id/class) have the class active. A typical if/else sentence but I can't quite wrap my head around it.

See the example here, this would be true as all children have the same class:

```<code><div class="parent">
   <div class="child active"></div>
   <div class="child active"></div>
   <div class="child active"></div>
   <div class="child active"></div>
</div>
</code>```

And this would be false as not all children have the same class:

```<code><div class="parent">
   <div class="child active"></div>
   <div class="child"></div>
   <div class="child active"></div>
   <div class="child"></div>
</div>
</code>```

There are many divs alike but the amount of children vary. It's important that it's 100% of the children that have the class before it is true.

How would you make the code?

Thanks.

答:
You can easily do a count of children with selectors

var $parent1 = $('.parent');
var $parent2 = $('.parent2');

var areAllActive = function ($node) {
  var $childrenActive = $node.children('div.active');
  console.log($childrenActive.length);
  var $allChildren = $node.children('div');
  console.log($allChildren.length);

  return $childrenActive.length === $allChildren.length;
};

console.log(areAllActive($parent1));
console.log(areAllActive($parent2));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
   <div class="child active"></div>
   <div class="child active"></div>
   <div class="child active"></div>
   <div class="child active"></div>
</div>

<div class="parent2">
   <div class="child active"></div>
   <div class="child"></div>
   <div class="child active"></div>
   <div class="child"></div>
</div></code>```

Title: Check if all children of div have class

Body:
I want to check if all children of different divs (with same id/class) have the class active. A typical if/else sentence but I can't quite wrap my head around it.

See the example here, this would be true as all children have the same class:

And this would be false as not all children have the same class:

There are many divs alike but the amount of children vary. It's important that it's 100% of the children that have the class before it is true.

How would you make the code?

Thanks.

Body:
You can easily do a count of children with selectors

var $parent1 = $('.parent');
var $parent2 = $('.parent2');

var areAllActive = function ($node) {
  var $childrenActive = $node.children('div.active');
  console.log($childrenActive.length);
  var $allChildren = $node.children('div');
  console.log($allChildren.length);

  return $childrenActive.length === $allChildren.length;
};

console.log(areAllActive($parent1));
console.log(areAllActive($parent2));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
   <div class="child active"></div>
   <div class="child active"></div>
   <div class="child active"></div>
   <div class="child active"></div>
</div>

<div class="parent2">
   <div class="child active"></div>
   <div class="child"></div>
   <div class="child active"></div>
   <div class="child"></div>
</div>


问:
Loading multiple fxml in javafx
I've been searching for a while and I haven't been able to get what I wanted to do. I've been using the javafx framework to switch fxml in javafx in this thread 'Loading new fxml in the same scene' with some success. I mean, I have a main window, and this window have two different areas, the MAIN area, and the CONTENT area.

The MAIN area will remain the same in the whole application, but the CONTENT area, will be changing constantly. My MAIN area has just a toolbar, and depending which button in the toolbar you click, the fxml (and the behavior) in the CONTENT area will change.

I already have that behavior and it works like a charm using that said framework.

The thing is, that I want that all my CONTENT areas could have their own MAIN areas too, and an own CONTENT areas too. And depending on what you do in that second MAIN areas, the fxml and the behavior in that second CONTENT areas changes too.

I don't know if the framework I'm using is enough and if I will be able to get what I want to do using it.

Do you know another different framework that could help me to get that functionality?

Thanks a lot in advance!

答:
Every .fxml that you load can have its own controller. Every controller can have custom action and loading code just like your main one does.

Basically, JavaFX is modular. If something is possible in your main pane, then it's possible in all its children too.

Generally, in UI-based frameworks, it is a wise idea to keep a hierarchy of controllers that mirrors the hierarchy of their respective components. If you want to get the child controller for the child element (for example, in order to pass the reference to the parent controller), then you can't rely on the FXML.load() shortcut, you have to use the longer syntax of:

```<code>FXMLLoader loader = new FXMLLoader(getClass().getResource("your.fxml"));
YourPaneType pane = loader.load();
YourControllerType controller = loader.getController();
</code>```

Title: Loading multiple fxml in javafx

Body:
Every .fxml that you load can have its own controller. Every controller can have custom action and loading code just like your main one does.

Basically, JavaFX is modular. If something is possible in your main pane, then it's possible in all its children too.

Generally, in UI-based frameworks, it is a wise idea to keep a hierarchy of controllers that mirrors the hierarchy of their respective components. If you want to get the child controller for the child element (for example, in order to pass the reference to the parent controller), then you can't rely on the FXML.load() shortcut, you have to use the longer syntax of:

FXMLLoader loader = new FXMLLoader(getClass().getResource("your.fxml"));
YourPaneType pane = loader.load();
YourControllerType controller = loader.getController();


问:
php file_get_contents() converts html entities like ö to ö
I try to display the contents of a php file in a textarea with

```<code><textarea ...>
<?php echo file_get_contents("file.php"); ?>
</textarea>
</code>```

but it converts the html entities like ö to ö. As it is php code I can not use a conversion like htmlspecialchars because it would brick the <> and quotes etc.

EDIT:

I checked the sourcecode with the browser and there is really an ö.

Please help, thank you!

答:
I think there is some non-UTF-8 character in your file.php.  Try this:

```<code>     $content = file_get_contents('/tmp/file.php');
     $content = mb_convert_encoding($content, 'UTF-8',mb_detect_encoding($content, 'UTF-8, ISO-8859-1', true));
     print_r($content);
</code>```

You can refer this comment http://php.net/manual/en/function.file-get-contents.php#85008.

Body:
I try to display the contents of a php file in a textarea with

<textarea ...>
<?php echo file_get_contents("file.php"); ?>
</textarea>

but it converts the html entities like ö to ö. As it is php code I can not use a conversion like htmlspecialchars because it would brick the <> and quotes etc.

EDIT:

I checked the sourcecode with the browser and there is really an ö.

Please help, thank you!

Body:
I think there is some non-UTF-8 character in your file.php.  Try this:

     $content = file_get_contents('/tmp/file.php');
     $content = mb_convert_encoding($content, 'UTF-8',mb_detect_encoding($content, 'UTF-8, ISO-8859-1', true));
     print_r($content);

You can refer this comment http://php.net/manual/en/function.file-get-contents.php#85008.


问:
The version of clr.dll does not match the one mscordacwks.dll was built for
I have a C# console app in Visual Studio 2010 that I can run just fine.  When I attempt to run the process in debug mode, I am presented with the following error:

I have tried searching for any information, but I haven't been able to find anything.  Can anyone provide clues as to why I can't run this with the debugger?

EDIT:  I should clarify that I have been able to successfully debug a console app previously, this is a new situation.

答: Simply. Restarting Visual Studio solved the problem in my case.</p>


问:
update remaining balance to 0 if payment is greater than remaining balance
using this query i can easily deduct the payment to the remaining balance

let say that my rem_balance is 3000  and my payment is 5000 so basically the change would be 2000.

```<code>UPDATE tbl_users SET rem_balance = (rem_balance - '5000') WHERE user_id = '2017001002'
</code>```

but since i use this query what happen is the rem_balance updates to -2000 what i wanted to achieve is that if payment is > rem_balance, rem_balance becomes 0 and it will separate the change.

答:
Something like this should work

```<code>UPDATE tbl_users
SET rem_balance = (CASE WHEN rem_balance < 5000 THEN 0 ELSE rem_balance - 5000 END)
WHERE user_id = '2017001002'
</code>```

Please be aware of the fact that you use implicit conversion in your SQL ('5000' instead of 5000). It is a bad habit and it can harm performance of your queries in certain cases. For example, if tbl_users.user_id is integer as well then the update will be unable to use indexes to search the row with the specific user_id and it will do a sequential scan which is very slow.

Body:
using this query i can easily deduct the payment to the remaining balance

let say that my rem_balance is 3000  and my payment is 5000 so basically the change would be 2000.

UPDATE tbl_users SET rem_balance = (rem_balance - '5000') WHERE user_id = '2017001002'

but since i use this query what happen is the rem_balance updates to -2000 what i wanted to achieve is that if payment is > rem_balance, rem_balance becomes 0 and it will separate the change.

Body:
Something like this should work

UPDATE tbl_users
SET rem_balance = (CASE WHEN rem_balance < 5000 THEN 0 ELSE rem_balance - 5000 END)
WHERE user_id = '2017001002'

Please be aware of the fact that you use implicit conversion in your SQL ('5000' instead of 5000). It is a bad habit and it can harm performance of your queries in certain cases. For example, if tbl_users.user_id is integer as well then the update will be unable to use indexes to search the row with the specific user_id and it will do a sequential scan which is very slow.


问:
Update value of a property using LINQ
I have following class structure

```<code>public class OfferModelCollection
{
    List<OfferModel> offers = new List<OfferModel>();
}

public class OfferModel
{
     public int ID { get; set; }
     public ProviderModel Provider { get; set; }
     public ProviderType ProviderType { get; set; }   //Enum

}

public class ProviderModel : BaseModel, IIdentity
{
     public string ProviderCode { get; set; }
     public string ProviderName { get; set; }
}
</code>```

I am now trying to update ProviderType of those offers whose Provider.ProviderCode matches to some string value. How can I achieve it in LINQ?

Something like this:

```<code>offersVM.Offers.Where(x=>x.Provider.ProviderCode.Contains("p10"))).ProviderType = ProviderType.Default;
</code>```

答:
Use foreach

```<code>foreach (var item in offersVM.Offers.Where(x=>x.Provider.ProviderCode.Contains("p10")))
{
    item.ProviderType = ProviderType.Default;
}
</code>```

Linq is for accessing not mutating

Title: Update value of a property using LINQ

Body:
I have following class structure

public class OfferModelCollection
{
    List<OfferModel> offers = new List<OfferModel>();
}

public class OfferModel
{
     public int ID { get; set; }
     public ProviderModel Provider { get; set; }
     public ProviderType ProviderType { get; set; }   //Enum

}

public class ProviderModel : BaseModel, IIdentity
{
     public string ProviderCode { get; set; }
     public string ProviderName { get; set; }
}

I am now trying to update ProviderType of those offers whose Provider.ProviderCode matches to some string value. How can I achieve it in LINQ?

Something like this:

offersVM.Offers.Where(x=>x.Provider.ProviderCode.Contains("p10"))).ProviderType = ProviderType.Default;

Body:
Use foreach

foreach (var item in offersVM.Offers.Where(x=>x.Provider.ProviderCode.Contains("p10")))
{
    item.ProviderType = ProviderType.Default;
}

Linq is for accessing not mutating