问:
How to space two buttons
I am trying two put space between these two buttons

Tried style="margin-right: but it pushed the button down instead of keeping it even with the other button

<title>W3.CSS</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

>>>Click Here to get Started Now<<<

>>>Schedule call and LEARN MORE <<<

```

答:
You could use relative and absolute positioning to align the buttons to the left and right respectively, and use w3-container as the main element to base positioning on.

<title>W3.CSS</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

>>>Click Here to get Started Now<<<

>>>Schedule call and LEARN MORE <<<

```
</div>
</div>
</p>

<p>Another option is to use flexbox if that's something you can support. In that case, you can insert an extra "spacer" element to take up as much space as its siblings will allow.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<title>W3.CSS</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<body>

<div class="w3-container" style='width: 100%; display: flex;'>

  <div class="w3-show-inline-block" style="flex: 0; white-space: nowrap;">
  <div class="w3-bar">
    <p>>>>Click Here to get Started Now<<<</p>
  </div>
  </div>

  <div class="spacer" style="flex: 1;"></div>

  <div class="w3-show-inline-block" style="flex: 0; white-space: nowrap;">
  <div class="w3-bar">
    <p>>>>Schedule call and LEARN MORE <<<</p>
  </div>
  </div>
</div>

</body>
</html></code>```

Title: How to space two buttons

Body:
You could use relative and absolute positioning to align the buttons to the left and right respectively, and use w3-container as the main element to base positioning on.

<html>
<title>W3.CSS</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<body>

<div class="w3-container" style='width: 100%; position: relative;'>

  <div class="w3-show-inline-block" style="left: 0; position: absolute;">
  <div class="w3-bar">
    <p><a class="global-btn" href="https://queencitylocal.com/contact/">&gt;&gt;&gt;Click Here to get Started Now&lt;&lt;&lt;</a></p>
  </div>
  </div>

  <div class="w3-show-inline-block" style="right: 0; position: absolute;">
  <div class="w3-bar">
    <p><a class="global-btn" href="https://queencitylocal.com/contact/">&gt;&gt;&gt;Schedule call and LEARN MORE &lt;&lt;&lt;</a></p>
  </div>
  </div>
</div>

</body>
</html>

Another option is to use flexbox if that's something you can support. In that case, you can insert an extra "spacer" element to take up as much space as its siblings will allow.

<html>
<title>W3.CSS</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<body>

<div class="w3-container" style='width: 100%; display: flex;'>

  <div class="w3-show-inline-block" style="flex: 0; white-space: nowrap;">
  <div class="w3-bar">
    <p><a class="global-btn" href="https://queencitylocal.com/contact/">&gt;&gt;&gt;Click Here to get Started Now&lt;&lt;&lt;</a></p>
  </div>
  </div>

  <div class="spacer" style="flex: 1;"></div>

  <div class="w3-show-inline-block" style="flex: 0; white-space: nowrap;">
  <div class="w3-bar">
    <p><a class="global-btn" href="https://queencitylocal.com/contact/">&gt;&gt;&gt;Schedule call and LEARN MORE &lt;&lt;&lt;</a></p>
  </div>
  </div>
</div>

</body>
</html>


来源: stackexchange

问:
How to push an array to state in React? Getting "Invalid attempt to spread non-iterable instance"
I'm trying to push a movie object into a favorites array in state when something is clicked.

Setting the favoritesArray into state works:

```<code>addToFavorites = (movie) => {
  const favoritesArray = [];
  favoritesArray.push(movie);
  this.setState({favorites: favoritesArray});
}
</code>```

But when I try to use an updater function as recommended by React I get errors:

```<code>this.state = {
  favorites: []
};

addToFavorites = (movie) => {
  const favoritesArray = [];
  favoritesArray.push(movie);
  this.setState(prevState => ({
    favorites: [...prevState.favorites, favoritesArray]
  }))
}
</code>```

Uncaught TypeError: Invalid attempt to spread non-iterable instance

It does seem to work if there's already something in state (not an empty array).

答:
first of all:
when you tried to spread the old favorites in the new favorites state you forgot to spread the favoritesArray you declared earlier.

The line should have been like this:
favorites: [...prevState.favorites, favoritesArray]

Because you just want to add the movie object to the favorites array you don't even need to declare a favoritesArray. Just add it to the Array in setState. Like this:

addToFavorites = (movie) => {
  this.setState(prevState => ({
    favorites: [...prevState.favorites, movie]
  }))
}```

where exactly do you set the state. It seems that your favorites in your prevState are not defined or nothing spreadable like the Error suggests, i.e. not Array, not Object

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to push a movie object into a favorites array in state when something is clicked.

Setting the favoritesArray into state works:

addToFavorites = (movie) => {
  const favoritesArray = [];
  favoritesArray.push(movie);
  this.setState({favorites: favoritesArray});
}

But when I try to use an updater function as recommended by React I get errors:

this.state = {
  favorites: []
};

addToFavorites = (movie) => {
  const favoritesArray = [];
  favoritesArray.push(movie);
  this.setState(prevState => ({
    favorites: [...prevState.favorites, favoritesArray]
  }))
}

Uncaught TypeError: Invalid attempt to spread non-iterable instance

It does seem to work if there's already something in state (not an empty array).

Body:
first of all:
when you tried to spread the old favorites in the new favorites state you forgot to spread the favoritesArray you declared earlier.

The line should have been like this:
favorites: [...prevState.favorites, favoritesArray]

Because you just want to add the movie object to the favorites array you don't even need to declare a favoritesArray. Just add it to the Array in setState. Like this:

addToFavorites = (movie) => {
  this.setState(prevState => ({
    favorites: [...prevState.favorites, movie]
  }))
}

where exactly do you set the state. It seems that your favorites in your prevState are not defined or nothing spreadable like the Error suggests, i.e. not Array, not Object


问:
Table and Proc dependency
I am new to schema and not sure how the table is being populated  (How the data is being inserted into the table ). How can we find out ?

This should work.

```<code>select *
from dba_source
where upper(text) like '%TABLE_NAME%'
</code>```

But as I do not have DBA rights , can not execute this command. What is the other way to find this out ?

答:
To see dependencies between objects you have access to you can query the all_dependencies data dictionary view. In this case:

```<code>select * from all_dependencies where referenced_name = 'YOUR_TABLE_NAME';
</code>```

If the objects are in your own schema when you can use the user_dependencies view. If you want to see objects you don't have privileges against then you can use dba_dependencies, but it sounds like you are unlikely to have the privileges required to query that view, since you can't see dba_source.

Of course, that will only identify references within your stored PL/SQL code; it won't tell you about any external application code that is performing inserts directly against the database (as opposed to via CRUD procedures) or manual inserts.

And it will only tell you which objects have dependencies, you'll still need to dig through the object source code, either by querying all_source (or user_source if you're the owner) for the relevant type and name. I would avoid the possibility of false-positives from, say, comments that happen to mention the table name in code which doesn't access it. You could also do that outside the database - hopefully your code is under source control (right!?).

Title: Table and Proc dependency

Body:
I am new to schema and not sure how the table is being populated  (How the data is being inserted into the table ). How can we find out ?

This should work.

select *
from dba_source
where upper(text) like '%TABLE_NAME%'

But as I do not have DBA rights , can not execute this command. What is the other way to find this out ?

Body:
To see dependencies between objects you have access to you can query the all_dependencies data dictionary view. In this case:

select * from all_dependencies where referenced_name = 'YOUR_TABLE_NAME';

If the objects are in your own schema when you can use the user_dependencies view. If you want to see objects you don't have privileges against then you can use dba_dependencies, but it sounds like you are unlikely to have the privileges required to query that view, since you can't see dba_source.

Of course, that will only identify references within your stored PL/SQL code; it won't tell you about any external application code that is performing inserts directly against the database (as opposed to via CRUD procedures) or manual inserts.

And it will only tell you which objects have dependencies, you'll still need to dig through the object source code, either by querying all_source (or user_source if you're the owner) for the relevant type and name. I would avoid the possibility of false-positives from, say, comments that happen to mention the table name in code which doesn't access it. You could also do that outside the database - hopefully your code is under source control (right!?).


问:
Java script key value pair to object
I  am new to javascript. I have an array of data in the format:

```<code>Toronto, Ontario: 95
Markham, Ontario: 71
</code>```

I want to convert it to an array of object:

 Like this, to be consistent with other functions.

I tried:

```<code>reportData.fbcity = Object.keys(reportData.city).map((city) => {
    return {
        city: city,
        value: reportData.city[city]
    };
});
</code>```

What I get is:
{city: "Markham, Ontario": "value": 71}

答:
You can use map and split

split with : and than build a object

+ is used to convert string to number

let data = ["Toronto, Ontario: 95", "Markham, Ontario: 71"];

let op = data.map(val=>{
  let [key,value] = val.split(':')
  return {[key]: +value}
})

console.log(op)```

Title: Java script key value pair to object

Body:
I  am new to javascript. I have an array of data in the format:

Toronto, Ontario: 95
Markham, Ontario: 71

I want to convert it to an array of object:

 Like this, to be consistent with other functions.

I tried:

reportData.fbcity = Object.keys(reportData.city).map((city) => {
    return {
        city: city,
        value: reportData.city[city]
    };
});

What I get is:
{city: "Markham, Ontario": "value": 71}


问:
How to implement listagg function in hibernate 5.0.1 without using native query
I am working in the spring boot 1.5 project.
I implemented listagg but I am getting "Unexcepted token error WITHIN " Please help me to implement listagg in hibernate without using native query.  </p>

```<code>Output:
    jobname     Empno
    AC_ACCOUNT  206
    AC_MGR      205
    AD_ASST     200
    AD_PRES     100
    AD_VP       101,102
    FI_ACCOUNT  110 ,113 ,111 ,109 ,112

select  jobname, listagg(empno, ',') within group (order by empno) empno
  from emp group by jobname;
</code>```

<p>-</p>

```<code>unexpected token: within","stack_trace":"antlr.NoViableAltException: unexpected token: within
at org.hibernate.hql.internal.antlr.HqlBaseParser.aliasedExpression(HqlBaseParser.java:2365)
at org.hibernate.hql.internal.antlr.HqlBaseParser.selectedPropertiesList(HqlBaseParser.java:1379)
at org.hibernate.hql.internal.antlr.HqlBaseParser.selectClause(HqlBaseParser.java:1282)
at org.hibernate.hql.internal.antlr.HqlBaseParser.selectFrom(HqlBaseParser.java:1022)
at org.hibernate.hql.internal.antlr.HqlBaseParser.queryRule(HqlBaseParser.java:730)
at org.hibernate.hql.internal.antlr.HqlBaseParser.selectStatement(HqlBaseParser.java:323)
at org.hibernate.hql.internal.antlr.HqlBaseParser.statement(HqlBaseParser.java:186)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:279)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:187)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:142)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:115)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:76)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:150)
at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:302)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:240)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1907)
at
</code>```

答:
I'm afraid but this is not possible. Neither JPA nor Hibernate know listagg.

You must use SQL.

The reason is JPA and Hibernate have implemented features that run on all databases but listagg is only implemented by a few.

Body:
I am working in the spring boot 1.5 project.
I implemented listagg but I am getting "Unexcepted token error WITHIN " Please help me to implement listagg in hibernate without using native query.

Output:
    jobname     Empno
    AC_ACCOUNT  206
    AC_MGR      205
    AD_ASST     200
    AD_PRES     100
    AD_VP       101,102
    FI_ACCOUNT  110 ,113 ,111 ,109 ,112

select  jobname, listagg(empno, ',') within group (order by empno) empno
  from emp group by jobname;

-

unexpected token: within","stack_trace":"antlr.NoViableAltException: unexpected token: within
at org.hibernate.hql.internal.antlr.HqlBaseParser.aliasedExpression(HqlBaseParser.java:2365)
at org.hibernate.hql.internal.antlr.HqlBaseParser.selectedPropertiesList(HqlBaseParser.java:1379)
at org.hibernate.hql.internal.antlr.HqlBaseParser.selectClause(HqlBaseParser.java:1282)
at org.hibernate.hql.internal.antlr.HqlBaseParser.selectFrom(HqlBaseParser.java:1022)
at org.hibernate.hql.internal.antlr.HqlBaseParser.queryRule(HqlBaseParser.java:730)
at org.hibernate.hql.internal.antlr.HqlBaseParser.selectStatement(HqlBaseParser.java:323)
at org.hibernate.hql.internal.antlr.HqlBaseParser.statement(HqlBaseParser.java:186)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:279)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:187)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:142)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:115)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:76)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:150)
at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:302)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:240)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1907)
at


问:
Why does axios always convert https into http when making request?
I am working with Laravel 5.8 and out-of-the-box pre-configured Vue.js.

For making a GET/POST/PUT/DELETE request within Vue.js components, I am using AXIOS as following:

```<code>import axios from 'axios'

const obj = axios.create({
  baseURL: '/controller-name/action-function-name'
})

export default {
  all (params) {
    return obj.get('/', params)
  },
  find (id) {
    return obj.get(`/${id}`)
  },
  store (data) {
    return obj.post(``, data)
  },
  update (id, data) {
    return obj.put(`/${id}`, data)
  },
  delete (id) {
    return obj.delete(`/${id}`)
  }
}
</code>```

Everything works fine in my local environment with a HTTP virtual host e.g. http://my-website.com. Until I deployed my application on a real hosting server with HTTPS url e.g. https://my-website.com, my app does not work any more and I get the following error.

```<code>Mixed Content: The page at 'https://my-website.com/path#/' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://my-website.com/path/controller-name/action-function-name'. This request has been blocked; the content must be served over HTTPS.
</code>```

I do understand that because my application is running on HTTPS domain but the request that AXIOS makes is via HTTP. That's why it does not work.

My question is why does AXIOS covert HTTPS into HTTP url when making a request?

I did try the following with hard code url.

```<code>import axios from 'axios'

export default {
  all (params) {
    return obj.get('https://my-website.com/controller-name/action-function-name/', params)
  },
  find (id) {
    return obj.get(`https://my-website.com/controller-name/action-function-name/${id}`)
  },
  store (data) {
    return obj.post(`https://my-website.com/controller-name/action-function-name`, data)
  },
  update (id, data) {
    return obj.put(`https://my-website.com/controller-name/action-function-name/${id}`, data)
  },
  delete (id) {
    return obj.delete(`https://my-website.com/controller-name/action-function-name/${id}`)
  }
}
</code>```

As you can see, all hard code url is prefixed with https. Every time I click on a menu link, AXIOS always overrides my https hard code url with http url. How can I fix that?

答:
Why don't you do the following:                                                                      </p>

```<code>baseURL: 'https://yourdomain.com/',
url: '/controller-name/action-function-name',
</code>```

Body:
I am working with Laravel 5.8 and out-of-the-box pre-configured Vue.js.

For making a GET/POST/PUT/DELETE request within Vue.js components, I am using AXIOS as following:

import axios from 'axios'

const obj = axios.create({
  baseURL: '/controller-name/action-function-name'
})

export default {
  all (params) {
    return obj.get('/', params)
  },
  find (id) {
    return obj.get(`/${id}`)
  },
  store (data) {
    return obj.post(``, data)
  },
  update (id, data) {
    return obj.put(`/${id}`, data)
  },
  delete (id) {
    return obj.delete(`/${id}`)
  }
}

Everything works fine in my local environment with a HTTP virtual host e.g. http://my-website.com. Until I deployed my application on a real hosting server with HTTPS url e.g. https://my-website.com, my app does not work any more and I get the following error.

Mixed Content: The page at 'https://my-website.com/path#/' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://my-website.com/path/controller-name/action-function-name'. This request has been blocked; the content must be served over HTTPS.

I do understand that because my application is running on HTTPS domain but the request that AXIOS makes is via HTTP. That's why it does not work.

My question is why does AXIOS covert HTTPS into HTTP url when making a request?

I did try the following with hard code url.

import axios from 'axios'

export default {
  all (params) {
    return obj.get('https://my-website.com/controller-name/action-function-name/', params)
  },
  find (id) {
    return obj.get(`https://my-website.com/controller-name/action-function-name/${id}`)
  },
  store (data) {
    return obj.post(`https://my-website.com/controller-name/action-function-name`, data)
  },
  update (id, data) {
    return obj.put(`https://my-website.com/controller-name/action-function-name/${id}`, data)
  },
  delete (id) {
    return obj.delete(`https://my-website.com/controller-name/action-function-name/${id}`)
  }
}

As you can see, all hard code url is prefixed with https. Every time I click on a menu link, AXIOS always overrides my https hard code url with http url. How can I fix that?

Body:
Why don't you do the following:

baseURL: 'https://yourdomain.com/',
url: '/controller-name/action-function-name',


问:
Creating associations in Sequelize migration
Nodejs. Sequelize 4.41. Try to make 2 models with relation many-to-many through another table. Running with sequelize-cli, for example...

```<code>sequelize model:generate --name Camera --attributes name:string,sn:string
</code>```

Here is models

```<code>// Camera model

'use strict';

module.exports = (sequelize, DataTypes) => {
  const Сamera = sequelize.define('Сamera', {
    name: DataTypes.STRING,
    sn: DataTypes.STRING
  }, {});
  Сamera.associate = function(models) {
    // associations can be defined here
      Camera.belongsToMany(models.Relay, {through: 'CameraRelay'});
  };
  return Сamera;
};
</code>```

And

```<code>// Relay model

'use strict';

module.exports = (sequelize, DataTypes) => {
  const Relay = sequelize.define('Relay', {
    name: DataTypes.STRING,
    sn: DataTypes.STRING,
    channel: DataTypes.INTEGER
  }, {});
  Relay.associate = function(models) {
    // associations can be defined here
      Relay.belongsToMany(models.Camera, {through: 'CameraRelay'});
  };
  return Relay;
};
</code>```

In documentation there are phrase

Belongs-To-Many associations are used to connect sources with multiple targets. Furthermore the targets can also have connections to multiple sources.

Project.belongsToMany(User, {through: 'UserProject'});
  User.belongsToMany(Project, {through: 'UserProject'});

This will
  create a new model called UserProject with the equivalent foreign keys
  projectId and userId.

Migrations is

```<code>// create-relay

'use strict';
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Relays', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      name: {
        type: Sequelize.STRING
      },
      sn: {
        type: Sequelize.STRING
      },
      channel: {
        type: Sequelize.INTEGER
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Relays');
  }
};
</code>```

And

```<code>//create camera
'use strict';
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Сameras', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      name: {
        type: Sequelize.STRING
      },
      sn: {
        type: Sequelize.STRING
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Сameras');
  }
};
</code>```

Why it doesn't create model CameraRelay and doesn't create migration for same model when I running migrate?

答:
I guess the misunderstanding is about sync vs migration: great part of documentation you are referring to, is using the sync method to create all tables and associations starting from models.

When you are using migrations, you are creating db all of your table/columns/associations using migration files (and in my hopinion, this is a better way for something that is going to production).

To understand the difference, just look at your camera model vs your camera migration file:

the model has only name and sn properties defined

the migration file has of course name and sn, but it has id, createdAt and updatedAt too.

Migrations are file with the aim of change your db in a safe way, allowing you to rollback to any point in the past.

So, back to your problem, you have to:

create a new migration file to create your new CameraRelay table, with foreign keys to both Camera and Relay tables

update your current Camera migration file with one-to-many relation to CameraRelay table

update your current Relay migration file with one-to-many relation to CameraRelay table

CameraRelay migration example:

```<code>    'use strict';
    module.exports = {
      up: (queryInterface, Sequelize) => {
        return queryInterface.createTable('CameraRelays', {
          cameraId: {
            primaryKey: true,
            type: Sequelize.INTEGER,
            allowNull: false,
            references: {
              model: 'Relay',
              key: 'id'
            }
          },
          relayId: {
            primaryKey: true,
            type: Sequelize.INTEGER,
            allowNull: false,
            references: {
              model: 'Camera',
              key: 'id'
            }
          },
          createdAt: {
            allowNull: false,
            type: Sequelize.DATE
          },
          updatedAt: {
            allowNull: false,
            type: Sequelize.DATE
          }
        });
      },
      down: (queryInterface, Sequelize) => {
        return queryInterface.dropTable('CameraRelays');
      }
    };

</code>```

Body:
Nodejs. Sequelize 4.41. Try to make 2 models with relation many-to-many through another table. Running with sequelize-cli, for example...

sequelize model:generate --name Camera --attributes name:string,sn:string

Here is models

// Camera model

'use strict';

module.exports = (sequelize, DataTypes) => {
  const Сamera = sequelize.define('Сamera', {
    name: DataTypes.STRING,
    sn: DataTypes.STRING
  }, {});
  Сamera.associate = function(models) {
    // associations can be defined here
      Camera.belongsToMany(models.Relay, {through: 'CameraRelay'});
  };
  return Сamera;
};

And

// Relay model

'use strict';

module.exports = (sequelize, DataTypes) => {
  const Relay = sequelize.define('Relay', {
    name: DataTypes.STRING,
    sn: DataTypes.STRING,
    channel: DataTypes.INTEGER
  }, {});
  Relay.associate = function(models) {
    // associations can be defined here
      Relay.belongsToMany(models.Camera, {through: 'CameraRelay'});
  };
  return Relay;
};

In documentation there are phrase

Belongs-To-Many associations are used to connect sources with multiple targets. Furthermore the targets can also have connections to multiple sources.

Project.belongsToMany(User, {through: 'UserProject'});
  User.belongsToMany(Project, {through: 'UserProject'});

This will
  create a new model called UserProject with the equivalent foreign keys
  projectId and userId.

Migrations is

// create-relay

'use strict';
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Relays', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      name: {
        type: Sequelize.STRING
      },
      sn: {
        type: Sequelize.STRING
      },
      channel: {
        type: Sequelize.INTEGER
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Relays');
  }
};

And

//create camera
'use strict';
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Сameras', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      name: {
        type: Sequelize.STRING
      },
      sn: {
        type: Sequelize.STRING
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Сameras');
  }
};

Why it doesn't create model CameraRelay and doesn't create migration for same model when I running migrate?

Body:
I guess the misunderstanding is about sync vs migration: great part of documentation you are referring to, is using the sync method to create all tables and associations starting from models.

When you are using migrations, you are creating db all of your table/columns/associations using migration files (and in my hopinion, this is a better way for something that is going to production).

To understand the difference, just look at your camera model vs your camera migration file:

the model has only name and sn properties defined

the migration file has of course name and sn, but it has id, createdAt and updatedAt too.

Migrations are file with the aim of change your db in a safe way, allowing you to rollback to any point in the past.

So, back to your problem, you have to:

create a new migration file to create your new CameraRelay table, with foreign keys to both Camera and Relay tables

update your current Camera migration file with one-to-many relation to CameraRelay table

update your current Relay migration file with one-to-many relation to CameraRelay table

CameraRelay migration example:

    'use strict';
    module.exports = {
      up: (queryInterface, Sequelize) => {
        return queryInterface.createTable('CameraRelays', {
          cameraId: {
            primaryKey: true,
            type: Sequelize.INTEGER,
            allowNull: false,
            references: {
              model: 'Relay',
              key: 'id'
            }
          },
          relayId: {
            primaryKey: true,
            type: Sequelize.INTEGER,
            allowNull: false,
            references: {
              model: 'Camera',
              key: 'id'
            }
          },
          createdAt: {
            allowNull: false,
            type: Sequelize.DATE
          },
          updatedAt: {
            allowNull: false,
            type: Sequelize.DATE
          }
        });
      },
      down: (queryInterface, Sequelize) => {
        return queryInterface.dropTable('CameraRelays');
      }
    };


问:
How to fix "Could not find method" error?
I'm working on home work on Android studio, every thing was Ok, and I shut down my pc till next day, when i opened android studio i found this error message

ERROR: Could not find method implementation() for arguments [directory 'libs'] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

```<code>dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    testImplementation 'junit:junit:4.13-beta-3'
    //noinspection GradleCompatible
    implementation 'com.android.support:appcompat-v7:26.0.0-alpha1'

    // Displaying images
    implementation 'com.github.bumptech.glide:glide:4.9.0'
    implementation 'com.google.firebase:firebase-core:16.0.9'

    // Realtime database
    implementation 'com.google.firebase:firebase-database:17.0.0'
    implementation 'com.android.support:support-v4:28.0.0'
}
</code>```

答:
This happens because the buildscript dependencies are outdated; update them to the current version, then it will know about implementation() and api() - or just use previous compile().

```<code>buildscript {
    repositories {
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.4.1'
    }
}
</code>```

That version number always equals the version number of Android Studio; eg. build-tools 3.4.1 requires Android Studio 3.4.1 to build... updating the whole installation should automatically fix it.

Body:
I'm working on home work on Android studio, every thing was Ok, and I shut down my pc till next day, when i opened android studio i found this error message

ERROR: Could not find method implementation() for arguments [directory 'libs'] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    testImplementation 'junit:junit:4.13-beta-3'
    //noinspection GradleCompatible
    implementation 'com.android.support:appcompat-v7:26.0.0-alpha1'

    // Displaying images
    implementation 'com.github.bumptech.glide:glide:4.9.0'
    implementation 'com.google.firebase:firebase-core:16.0.9'

    // Realtime database
    implementation 'com.google.firebase:firebase-database:17.0.0'
    implementation 'com.android.support:support-v4:28.0.0'
}

Body:
This happens because the buildscript dependencies are outdated; update them to the current version, then it will know about implementation() and api() - or just use previous compile().

buildscript {
    repositories {
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.4.1'
    }
}

That version number always equals the version number of Android Studio; eg. build-tools 3.4.1 requires Android Studio 3.4.1 to build... updating the whole installation should automatically fix it.


问:
I want to limit the pdf file size uploaded to firebase storage. I want that user can upload a file with maximum size of 7MB
I want put a limitation on firebase storage. That is user can upload a pdf file of maximum size of 7MB. And How can i reduce the size of pdf file? is there any way in android.

I don't know the solution of my question. I find a lot but doesn't get my answer.
Can someone help me with firebase security rules? I am not familiar with that doesn't find any answer about this.

答:
The Firebase documentation on security rules has an example that shows (amongst others) how to set the maximum size of files that can be stored:

```<code>service firebase.storage {
 match /b/{bucket}/o {
   match /images {
     // Cascade read to any image type at any path
     match /{allImages=**} {
       allow read;
     }

     // Allow write files to the path "images/*", subject to the constraints:
     // 1) File is less than 5MB
     // 2) Content type is an image
     // 3) Uploaded content type matches existing content type
     // 4) File name (stored in imageId wildcard variable) is less than 32 characters
     match /{imageId} {
       allow write: if request.resource.size < 5 * 1024 * 1024
                    && request.resource.contentType.matches('image/.*')
                    && request.resource.contentType == resource.contentType
                    && imageId.size() < 32
     }
   }
 }
}
</code>```

Since these rules will only be applied after the actual upload has completed (but before the file is actually stored in your storage bucket), you'll typically also want to check the file size in your Android app before uploading it, to prevent using bandwidth for a file that is too large. For some examples of how to check the local file size on Android, see Get the file size in android sdk?

Body:
The Firebase documentation on security rules has an example that shows (amongst others) how to set the maximum size of files that can be stored:

service firebase.storage {
 match /b/{bucket}/o {
   match /images {
     // Cascade read to any image type at any path
     match /{allImages=**} {
       allow read;
     }

     // Allow write files to the path "images/*", subject to the constraints:
     // 1) File is less than 5MB
     // 2) Content type is an image
     // 3) Uploaded content type matches existing content type
     // 4) File name (stored in imageId wildcard variable) is less than 32 characters
     match /{imageId} {
       allow write: if request.resource.size < 5 * 1024 * 1024
                    && request.resource.contentType.matches('image/.*')
                    && request.resource.contentType == resource.contentType
                    && imageId.size() < 32
     }
   }
 }
}

Since these rules will only be applied after the actual upload has completed (but before the file is actually stored in your storage bucket), you'll typically also want to check the file size in your Android app before uploading it, to prevent using bandwidth for a file that is too large. For some examples of how to check the local file size on Android, see Get the file size in android sdk?


问:
TYPO3 Fluid - Exit a for loop
Is it somehow possible to break out of a for loop in fluid?

```<code><f:for each="{subItem.image}" as="imageItem">
 <f:if condition="{selectedCategory} == {subItem.imagecategory}">
  Do Stuff
  Exit loop
 </f:if>
</f:for>
</code>```

I need to loop trough a couple of images then render one if the category matches and exit the loop after that since I only want to render the first image with the matching category.

答:
You can use Fluid variable view helper:</p>

```<code><f:variable name="imageRendered" value="0" />
<f:for each="{subItem.image}" as="imageItem">
 <f:if condition="{selectedCategory} == {subItem.imagecategory} && {imageRendered} == 0">
  Do Stuff
  Exit loop
  <f:variable name="imageRendered" value="1" />
 </f:if>
</f:for>
</code>```

Title: TYPO3 Fluid - Exit a for loop

Body:
Is it somehow possible to break out of a for loop in fluid?

<f:for each="{subItem.image}" as="imageItem">
 <f:if condition="{selectedCategory} == {subItem.imagecategory}">
  Do Stuff
  Exit loop
 </f:if>
</f:for>

I need to loop trough a couple of images then render one if the category matches and exit the loop after that since I only want to render the first image with the matching category.

Body:
You can use Fluid variable view helper:

<f:variable name="imageRendered" value="0" />
<f:for each="{subItem.image}" as="imageItem">
 <f:if condition="{selectedCategory} == {subItem.imagecategory} && {imageRendered} == 0">
  Do Stuff
  Exit loop
  <f:variable name="imageRendered" value="1" />
 </f:if>
</f:for>


问:
How to recieve touches began event inside a subview?
I have a view containing two subviews(plain UIviews).  The parent view recognizes touch events like touchesbegan ,ended, etc. but the sub view is not recognizing the touch event. How to make it recognize the touch event. Specifically i need only sub view to recognize  touch events and not parent view. Thanks in advance.

UserInteractionEnabled is set to YES for the views.

答:
There's two ways of dealing with this.

1) Detect the touches in your viewcontroller instead of in a view. You should be able to work out which view contains the point which was touched and from that can decide what to do with the touch (or just throw it away if it wasn't in either view).

2) Create a subclass of UIView and add these to your main view instead of just UIViews. Then you can detect the touches inside your subclass and deal with them accordingly.

Hope that helps.

ContentLicense: CC BY-SA 3.0


问:
How to read Excel cell having Date with Apache POI?
I'm using Apache POI 3.6, I want to read an excel file which has a date like this 8/23/1991.

```<code> switch (cell.getCellType()) {

   ...
   ...

   case HSSFCell.CELL_TYPE_NUMERIC:
     value = "NUMERIC value=" + cell.getNumericCellValue();
     break;

   ...

 }
</code>```

But it takes the numeric value type and returns the value like this 33473.0.

I've tried to use Numeric Cell Type although with no luck.

```<code>dbltemp=row.getCell(c, Row.CREATE_NULL_AS_BLANK).getNumericCellValue();

if (c == 6 || c == 9) {
    strTemp= new String(dbltemp.toString().trim());

    long tempDate = Long.parseLong(strTemp);
    Date date = new Date(tempDate);

    strVal = date.toString();
}
</code>```

How can I fix my problem?

答:
If you know the cell number, then i would recommend using getDateCellValue() method
Here's an example for the same that worked for me -
java.util.Date date  = row.getCell().getDateCellValue();
System.out.println(date);</p>

Body:
I'm using Apache POI 3.6, I want to read an excel file which has a date like this 8/23/1991.

 switch (cell.getCellType()) {

   ...
   ...

   case HSSFCell.CELL_TYPE_NUMERIC:
     value = "NUMERIC value=" + cell.getNumericCellValue();
     break;

   ...

 }

But it takes the numeric value type and returns the value like this 33473.0.

I've tried to use Numeric Cell Type although with no luck.

dbltemp=row.getCell(c, Row.CREATE_NULL_AS_BLANK).getNumericCellValue();

if (c == 6 || c == 9) {
    strTemp= new String(dbltemp.toString().trim());

    long tempDate = Long.parseLong(strTemp);
    Date date = new Date(tempDate);

    strVal = date.toString();
}

How can I fix my problem?


问:
Linear Regression - Implementing Feature Scaling
I was trying to implement Linear Regression in Octave 5.1.0 on a data set relating the GRE score to the probability of Admission.
The data set is of the sort,

337 0.92

  324 0.76

  316 0.72

  322 0.8

  .
 .
 .

My main Program.m file looks like,

```<code>     % read the data

  data = load('Admission_Predict.txt');

  % initiate variables
  x = data(:,1);
  y = data(:,2);
  m = length(y);
  theta = zeros(2,1);
  alpha = 0.01;
  iters = 1500;
  J_hist = zeros(iters,1);

  % plot data
  subplot(1,2,1);
  plot(x,y,'rx','MarkerSize', 10);
  title('training data');

  % compute cost function
  x = [ones(m,1), (data(:,1) ./ 300)]; % feature scaling
  J = computeCost(x,y,theta);

  % run gradient descent
  [theta, J_hist] = gradientDescent(x,y,theta,alpha,iters);

  hold on;
  subplot(1,2,1);
  plot((x(:,2) .* 300), (x*theta),'-');
  xlabel('GRE score');
  ylabel('Probability');
  hold off;

  subplot (1,2,2);
  plot(1:iters, J_hist, '-b');
  xlabel('no: of iteration');
  ylabel('Cost function');
</code>```

computeCost.m looks like,

```<code> function J = computeCost(x,y,theta)
  m = length(y);
  h = x * theta;
  J = (1/(2*m))*sum((h-y) .^ 2);
endfunction
</code>```

and gradientDescent.m looks like,

```<code>    function [theta, J_hist] = gradientDescent(x,y,theta,alpha,iters)
  m = length(y);
  J_hist = zeros(iters,1);

  for i=1:iters

    diff = (x*theta - y);
    theta = theta - (alpha * (1/(m))) * (x' * diff);
    J_hist(i) = computeCost(x,y,theta);

  endfor

endfunction
</code>```

The graphs plotted then looks like this,

which you can see, doesn't feel right even though my Cost function seems to be minimized.

Can someone please tell me if this is right? If not, what am I doing wrong?

答: The easiest way to check whether your implementation is correct is to compare with a validated implementation of linear regression. I suggest using an alternative implementation approach like the one suggested here, and then comparing your results. If the fits match, then this is the best linear fit to your data and if they don't match, then there may be something wrong in your implementation.</p>

Body:
I was trying to implement Linear Regression in Octave 5.1.0 on a data set relating the GRE score to the probability of Admission.
The data set is of the sort,

337 0.92

  324 0.76

  316 0.72

  322 0.8

  .
 .
 .

My main Program.m file looks like,

     % read the data

  data = load('Admission_Predict.txt');

  % initiate variables
  x = data(:,1);
  y = data(:,2);
  m = length(y);
  theta = zeros(2,1);
  alpha = 0.01;
  iters = 1500;
  J_hist = zeros(iters,1);

  % plot data
  subplot(1,2,1);
  plot(x,y,'rx','MarkerSize', 10);
  title('training data');

  % compute cost function
  x = [ones(m,1), (data(:,1) ./ 300)]; % feature scaling
  J = computeCost(x,y,theta);

  % run gradient descent
  [theta, J_hist] = gradientDescent(x,y,theta,alpha,iters);

  hold on;
  subplot(1,2,1);
  plot((x(:,2) .* 300), (x*theta),'-');
  xlabel('GRE score');
  ylabel('Probability');
  hold off;

  subplot (1,2,2);
  plot(1:iters, J_hist, '-b');
  xlabel('no: of iteration');
  ylabel('Cost function');

computeCost.m looks like,

 function J = computeCost(x,y,theta)
  m = length(y);
  h = x * theta;
  J = (1/(2*m))*sum((h-y) .^ 2);
endfunction

and gradientDescent.m looks like,

    function [theta, J_hist] = gradientDescent(x,y,theta,alpha,iters)
  m = length(y);
  J_hist = zeros(iters,1);

  for i=1:iters

    diff = (x*theta - y);
    theta = theta - (alpha * (1/(m))) * (x' * diff);
    J_hist(i) = computeCost(x,y,theta);

  endfor

endfunction

The graphs plotted then looks like this,

which you can see, doesn't feel right even though my Cost function seems to be minimized.

Can someone please tell me if this is right? If not, what am I doing wrong?


问:
AWS- Using dependency for third party SDK with lambdas?
I am trying to use cron via CloudWatch to run a simple python script that utilizes a third party API to check for an available number.  My goal is to have CloudWatch run the cron, trigger a lambda that runs the python script, if there is a number returned to trigger an SNS notification.

My problem is installing the third party API dependencies.  I am getting an error of the module not found.  Can third party dependencies be used with lambdas or am I better off installing them on an EC2 instance I manually spin up?

答:
Please refer to the docs. https://docs.aws.amazon.com/lambda/latest/dg/lambda-python-how-to-create-deployment-package.html

This goes over how to create a deployment package and include dependencies for python.


问:
Removing duplicates and keeping one copy
I have been going through the threads about removing duplicates from a table and keeping one copy .I have seen an illustration in the case one have a table with composite key.anyone with the idea ?

table contr with composite key checkno,salary_month,sal_year

```<code>delete (select * from CONTR t1
    INNER JOIN
 (select CHECKNO, SALARY_YEAR,SALARY_MONTH FROM CONTR
group by CHECKNO, SALARY_YEAR,SALARY_MONTH HAVING COUNT(*) > 1) dupes
ON
t1.CHECKNO = dupes.CHECKNO AND
t1.SALARY_YEAR= dupes.SALARY_YEAR AND
t1.SALARY_MONTH=dupes.SALARY_MONTH);
</code>```

I expected one duplicate to be removed and one maintained.

答:
You can use this query below to remove duplicates by using rowid as having a unique valued column :

```<code>delete contr t1
 where rowid <
     (
      select max(rowid)
        from contr t2
       where t2.checkno = t1.checkno
         and t2.salary_year = t1.salary_year
         and t2.salary_month = t1.salary_month
      );
</code>```

Demo

Body:
I have been going through the threads about removing duplicates from a table and keeping one copy .I have seen an illustration in the case one have a table with composite key.anyone with the idea ?

table contr with composite key checkno,salary_month,sal_year

delete (select * from CONTR t1
    INNER JOIN
 (select CHECKNO, SALARY_YEAR,SALARY_MONTH FROM CONTR
group by CHECKNO, SALARY_YEAR,SALARY_MONTH HAVING COUNT(*) > 1) dupes
ON
t1.CHECKNO = dupes.CHECKNO AND
t1.SALARY_YEAR= dupes.SALARY_YEAR AND
t1.SALARY_MONTH=dupes.SALARY_MONTH);

I expected one duplicate to be removed and one maintained.

Body:
You can use this query below to remove duplicates by using rowid as having a unique valued column :

delete contr t1
 where rowid <
     (
      select max(rowid)
        from contr t2
       where t2.checkno = t1.checkno
         and t2.salary_year = t1.salary_year
         and t2.salary_month = t1.salary_month
      );

Demo


问:
How to extract access rights validation in Kotlin's Ktor
I have Ktor based REST API application which uses the jwt token's as authentication. Then I have to restrict certain routes for the specific role. In order to do it I am creating principal, containing the relevant info:

```<code>data class UserPrincipal (
  val id: Long,
  val username: String,
  val roleId: Long,
): Princpal {
  override fun getName() = username
}

object AuthLogin {
  fun Application.auth(jwt: JwtProvider) {
    install(Authentication) {
      jwt("jwt") {
        realm = jwt.realm()
        verifier(jwt.verifier())
        validate {
          val userId = it.payload.getClaim("id").asLong()
          val username = it.payload.getClain("name")
          val roleId = it.payload.getClaim("roleId").asLong()
          UserPrincipal(userId, username, roleId)
        }
      }
    }
  }
}
</code>```

The claims with userId and roleId are being provided when signing the correctly logged in user. Now I can restrict REST endpoints like that:

```<code>object RestModule {
  fun Application.enititiesOne(userRepo: UserRepo) {
    routing {
      authenticate("jwt") {
        route("/entities1") {
          get {
            val principal = call.principal<UserPrincipal>()
            when(userRepo.hasAccessByRole(principal!!.roleId, "CAN_R_E1") {
              false -> call.respond(HttpStatusCode.Forbidden)
              true -> // some retrieval logic
          }
          post {
            val principal = call.principal<UserPrincipal>()
            when(userRepo.hasAccessByRole(principal!!.roleId, "CAN_W_E1") {
              false -> call.respond(HttpStatusCode.Forbidden)
              true -> // some update logic
          }
        }
      }
    }
  }
}
</code>```

As you can see even inside one routing function I have to duplicate code that checks the principal's role twice. I can move it out to function but what I want is a single place to define my security roles. Something like that:

```<code>authenticate {
  val principal = call.principal<UserPrincipal()
  val rights = userRepo.rightsByRole(principal.roleId)
  when(routes) {
    get("/entities1/**") ->
      if(rights.contain("CAN_R_E1")) call.proceed
      else call.respond(HttpStatusCode.Forbidden)
    post("/entites1) -> rights.contain("CAN_W_E1") // similar
    get("/entities2/**") -> rights.contain("CAN_R_E2") // similar
    else -> call.respond(401)
  }
}
</code>```

And then plug it into the rest endpoints. Or is there some similar approach that I can use in Kotlin's Ktor? Seems like interceptors is what I need but I'm not sure how to use them in an intended way.

答:
You can check the method and uri in the validate block.

```<code>install(Authentication) {
    jwt {
        validate {
            val userId = it.payload.getClaim("id").asLong()
            val username = it.payload.getClaim("name").asString()
            val roleId = it.payload.getClaim("roleId").asLong()
            UserPrincipal(userId, username, roleId)
            val requiredRole = when (request.httpMethod) {
                HttpMethod.Get -> // get role
                HttpMethod.Post -> // get other role
            }
            // check if role exists in repo
        }
    }
}
install(Routing) {
    get {
        val principal = call.principal<UserPrincipal>()!!
        call.respond(principal)
    }

    post {
        val principal = call.principal<UserPrincipal>()!!
        call.respond(principal)
    }
}
</code>```

By the way, there were several issues with the code you posted, so it wouldn't compile.

Body:
I have Ktor based REST API application which uses the jwt token's as authentication. Then I have to restrict certain routes for the specific role. In order to do it I am creating principal, containing the relevant info:

data class UserPrincipal (
  val id: Long,
  val username: String,
  val roleId: Long,
): Princpal {
  override fun getName() = username
}

object AuthLogin {
  fun Application.auth(jwt: JwtProvider) {
    install(Authentication) {
      jwt("jwt") {
        realm = jwt.realm()
        verifier(jwt.verifier())
        validate {
          val userId = it.payload.getClaim("id").asLong()
          val username = it.payload.getClain("name")
          val roleId = it.payload.getClaim("roleId").asLong()
          UserPrincipal(userId, username, roleId)
        }
      }
    }
  }
}

The claims with userId and roleId are being provided when signing the correctly logged in user. Now I can restrict REST endpoints like that:

object RestModule {
  fun Application.enititiesOne(userRepo: UserRepo) {
    routing {
      authenticate("jwt") {
        route("/entities1") {
          get {
            val principal = call.principal<UserPrincipal>()
            when(userRepo.hasAccessByRole(principal!!.roleId, "CAN_R_E1") {
              false -> call.respond(HttpStatusCode.Forbidden)
              true -> // some retrieval logic
          }
          post {
            val principal = call.principal<UserPrincipal>()
            when(userRepo.hasAccessByRole(principal!!.roleId, "CAN_W_E1") {
              false -> call.respond(HttpStatusCode.Forbidden)
              true -> // some update logic
          }
        }
      }
    }
  }
}

As you can see even inside one routing function I have to duplicate code that checks the principal's role twice. I can move it out to function but what I want is a single place to define my security roles. Something like that:

authenticate {
  val principal = call.principal<UserPrincipal()
  val rights = userRepo.rightsByRole(principal.roleId)
  when(routes) {
    get("/entities1/**") ->
      if(rights.contain("CAN_R_E1")) call.proceed
      else call.respond(HttpStatusCode.Forbidden)
    post("/entites1) -> rights.contain("CAN_W_E1") // similar
    get("/entities2/**") -> rights.contain("CAN_R_E2") // similar
    else -> call.respond(401)
  }
}

And then plug it into the rest endpoints. Or is there some similar approach that I can use in Kotlin's Ktor? Seems like interceptors is what I need but I'm not sure how to use them in an intended way.

Body:
You can check the method and uri in the validate block.

install(Authentication) {
    jwt {
        validate {
            val userId = it.payload.getClaim("id").asLong()
            val username = it.payload.getClaim("name").asString()
            val roleId = it.payload.getClaim("roleId").asLong()
            UserPrincipal(userId, username, roleId)
            val requiredRole = when (request.httpMethod) {
                HttpMethod.Get -> // get role
                HttpMethod.Post -> // get other role
            }
            // check if role exists in repo
        }
    }
}
install(Routing) {
    get {
        val principal = call.principal<UserPrincipal>()!!
        call.respond(principal)
    }

    post {
        val principal = call.principal<UserPrincipal>()!!
        call.respond(principal)
    }
}

By the way, there were several issues with the code you posted, so it wouldn't compile.


问:
splitViewController with Two NavigationController linking protocols
EDIT: Added Source Project

--> I uploaded a sample project that clearly shows my dilemma which can be found here <--

I created a Split View-based Application. I then added a second UINavigationController to the DetailViewController inside the MainWindow.xib.

I then pop a new UIViewController Subclasses when a toolbar item is clicked. I use the following code to conduct the pop:

```<code>DocumentDetailVC *DetailViewController = [[DocumentDetailVC alloc] initWithNibName:@"DocumentDetailVC" bundle:[NSBundle mainBundle]];
[detailViewController.detailNavController pushViewController:DetailViewController animated:YES];

DocumentsVC *RRequestViewController = [[DocumentsVC alloc] initWithNibName:@"DocumentsVC" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:RRequestViewController animated:YES];
</code>```

This works. The issue I am having is how do I pass information or function calls from the Main side of the Split View to the Detail side of the Split view?

If I present the UIViewController via the following method:

```<code>DocumentDetailVC *RRequestViewController = [[DocumentDetailVC alloc] initWithNibName:@"DocumentDetailVC" bundle:[NSBundle mainBundle]];
RRequestViewController.delegate=self;
RRequestViewController.modalPresentationStyle = UIModalPresentationCurrentContext;
[RRequestViewController setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
[self presentModalViewController:RRequestViewController animated:YES];
[RRequestViewController release];
RRequestViewController = nil;
</code>```

I am able to complete a reach back through a protocol as intended.

DocumentDetailVC, when loaded via the pushViewController, the hierarchy is as follows:

```<code>NSLog([NSString stringWithFormat:@"%@",self]);
//self = <DocumentDetailVC: 0x4e0d960>
NSLog([NSString stringWithFormat:@"%@",self.parentViewController]);
//self.parentViewController = <UINavigationController: 0x4e0ce30>
NSLog([NSString stringWithFormat:@"%@",self.parentViewController.parentViewController]);
//self.parentViewController.parentViewController = <UISplitViewController: 0x4e0d0f0>
</code>```

Thank you for your assistance. This problem is consuming my life!

--> I uploaded a sample project that clearly shows my dilemma which can be found here <--

答:
Ok, I know am very late for answer but this answer is, I think, perfect and working. Try it. Open your RootViewController.h, on the top write this line:

```<code>#import "Left.h"
#import "Right.h"
</code>```

in @interface RootViewController  write this lines

```<code>Left *lefty;
Right *righty;
</code>```

after that declare property as,

```<code>@property (nonatomic, retain) Left *lefty;
@property (nonatomic, retain) Right *righty;
</code>```

go to ROOTVIEWCONTROLLER.M file synthesize as,

```<code>@synthesize lefty;
@synthesize righty;
</code>```

after that in RootViewController.m just replace your function with this one

```<code>    - (IBAction)myBtnPushed{
    NSLog(@"myBtnPushed");

    lefty = [[Left alloc] initWithNibName:@"Left" bundle:[NSBundle mainBundle]];
    righty = [[Right alloc] initWithNibName:@"Right" bundle:[NSBundle mainBundle]];

    lefty.delegate=righty;
    [self.navigationController pushViewController:lefty animated:YES];

    [detailViewController.navigationController pushViewController:righty animated:YES];

}
</code>```

in delloac write this,

```<code>[lefty release];
lefty = nil;
[righty release];
righty = nil;
</code>```

It's done, run your app. I tested, it's done.

ContentLicense: CC BY-SA 2.5

Body:
EDIT: Added Source Project

--> I uploaded a sample project that clearly shows my dilemma which can be found here <--

I created a Split View-based Application. I then added a second UINavigationController to the DetailViewController inside the MainWindow.xib.

I then pop a new UIViewController Subclasses when a toolbar item is clicked. I use the following code to conduct the pop:

DocumentDetailVC *DetailViewController = [[DocumentDetailVC alloc] initWithNibName:@"DocumentDetailVC" bundle:[NSBundle mainBundle]];
[detailViewController.detailNavController pushViewController:DetailViewController animated:YES];

DocumentsVC *RRequestViewController = [[DocumentsVC alloc] initWithNibName:@"DocumentsVC" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:RRequestViewController animated:YES];

This works. The issue I am having is how do I pass information or function calls from the Main side of the Split View to the Detail side of the Split view?

If I present the UIViewController via the following method:

DocumentDetailVC *RRequestViewController = [[DocumentDetailVC alloc] initWithNibName:@"DocumentDetailVC" bundle:[NSBundle mainBundle]];
RRequestViewController.delegate=self;
RRequestViewController.modalPresentationStyle = UIModalPresentationCurrentContext;
[RRequestViewController setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
[self presentModalViewController:RRequestViewController animated:YES];
[RRequestViewController release];
RRequestViewController = nil;

I am able to complete a reach back through a protocol as intended.

DocumentDetailVC, when loaded via the pushViewController, the hierarchy is as follows:

NSLog([NSString stringWithFormat:@"%@",self]);
//self = <DocumentDetailVC: 0x4e0d960>
NSLog([NSString stringWithFormat:@"%@",self.parentViewController]);
//self.parentViewController = <UINavigationController: 0x4e0ce30>
NSLog([NSString stringWithFormat:@"%@",self.parentViewController.parentViewController]);
//self.parentViewController.parentViewController = <UISplitViewController: 0x4e0d0f0>

Thank you for your assistance. This problem is consuming my life!

--> I uploaded a sample project that clearly shows my dilemma which can be found here <--

Body:
Ok, I know am very late for answer but this answer is, I think, perfect and working. Try it. Open your RootViewController.h, on the top write this line:

#import "Left.h"
#import "Right.h"

in @interface RootViewController  write this lines

Left *lefty;
Right *righty;

after that declare property as,

@property (nonatomic, retain) Left *lefty;
@property (nonatomic, retain) Right *righty;

go to ROOTVIEWCONTROLLER.M file synthesize as,

@synthesize lefty;
@synthesize righty;

after that in RootViewController.m just replace your function with this one

    - (IBAction)myBtnPushed{
    NSLog(@"myBtnPushed");

    lefty = [[Left alloc] initWithNibName:@"Left" bundle:[NSBundle mainBundle]];
    righty = [[Right alloc] initWithNibName:@"Right" bundle:[NSBundle mainBundle]];

    lefty.delegate=righty;
    [self.navigationController pushViewController:lefty animated:YES];

    [detailViewController.navigationController pushViewController:righty animated:YES];

}

in delloac write this,

[lefty release];
lefty = nil;
[righty release];
righty = nil;

It's done, run your app. I tested, it's done.


问:
Smart Card reader PCSC with multiple slots
I implemented a Card reader with CCID Protocol based on a microcontroller with three card slots.

In the description of the Protocol each team has the bytes of the numbers of slots for receiving the command.

The computer I use the app PCSC_Sample and SCardToolSet. The problem is that they only send requests to slot number 0.

How do you determine the number of card slots? Is it a certain parameter that in one of the answers sends Card READER to pcsc program as a parameter or does the program itself search for cards on the wizard (computer)? If the latter, then what program can you recommend for Windows 10?

答:
All readers with several slots, I encountered (admittedly contact-based/contactless combinations, not several contact-based) are offering each slot under a separate friendly name. This also makes it easier for dumb applications to handle the scenario.

High security readers having a built-in security module in a second slot are unlikely to use PCSC.


问:
console.log() displays the correct value, but when assigned it to a variable, it is undefined - Angular, firestore
I'm working on an Angular application and want to get some data from Firestore. But my function always returns undefined. When I, however, console.log() the value before returning it, it displays the correct value.

```<code>getToken(user_id) {
    this.afs.collection("tokens").ref.doc(user_id).get().then((doc) => {
      if (doc.exists) {
        console.log(doc.data().user_token); //displays the correct user_token value
        return doc.data().user_token; //returns undefined!
      }
    });
}
</code>```

Shouldn't both values be the same?

答:
This may answer your question: Can't access object property, even though it exists. Returns undefined

"The output of console.log(anObject) is misleading; the state of the object displayed is only resolved when you expand the > in the console."

In other words, doc.data().user_token might be getting populated by an asynchronous process.

Body:
I'm working on an Angular application and want to get some data from Firestore. But my function always returns undefined. When I, however, console.log() the value before returning it, it displays the correct value.

getToken(user_id) {
    this.afs.collection("tokens").ref.doc(user_id).get().then((doc) => {
      if (doc.exists) {
        console.log(doc.data().user_token); //displays the correct user_token value
        return doc.data().user_token; //returns undefined!
      }
    });
}

Shouldn't both values be the same?


问:
Share RAM between Docker containers using mmap() in Annoy library
I am using Annoy library that is using mmap() to load some multi-Gb files into RAM memory. The goal of using mmap() is to load the file only once in memory even when different processes need it.

Using docker, I plan to scale with multiple containers executing the same script on the same host. But the multi-Gb file should be loaded only once in RAM (which is why we use mmap()), otherwise my server will explode.

The multi-Gb file is located in a volume mounted on my containers.

But I still need to find a way to share RAM between containers so that I get the advantages of mmap().

I found this article about using the --ipc tag in docker, but I don't know if it applies to my case and how to implement it. Any help welcome.

答: --ipc is a red herring. For local volumes no action is required, if it is the same file then memory will be shared. I suspect the same for remote volumes, but can't confirm that remote volumes will not multiply mounted.


问:
Singleton initialization
I implemented the Singleton design pattern in my code.

Suppose it is:

```<code>class Singleton
{
  Singleton () {}
  static Singleton* s;
public:
  static Singleton* Get () {
    if (!s)
      s = new Singleton ();
    return s;
  }
};
</code>```

What puzzles me is the 'initialization' of this pattern.
In the .cpp I put:

```<code>SingletonPointer* SingletonClass::s (0);
</code>```

But I don't understand how is it possible to <s>access</s> define s, as it is private.
How's that possible?

TIA,
Jir

答:
Static fields must have definitions besides their declaration. The declaration usually goes in the class declaration in the .h file, while the definition almost always goes in the .cpp file. The definition of static variables is a must, since they must be initialized to something.

But even though the definition is outside of the class body and even in an entirely different file, it doesn't mean it's not a part of the class. The SingletonClass:: makes it part of the class definition (as opposed to the class declaration), and therefore it can 'access' private fields.

The same goes for methods defined outside of the class body, for instance:

```<code>// A.h
class A
{
private:
    int b;
public:
    A(int x) : b(x)
    {}

    Do();
}

// A.cpp
A::Do()
{
    return b;
}
</code>```

Title: Singleton initialization

Body:
I implemented the Singleton design pattern in my code.

Suppose it is:

class Singleton
{
  Singleton () {}
  static Singleton* s;
public:
  static Singleton* Get () {
    if (!s)
      s = new Singleton ();
    return s;
  }
};

What puzzles me is the 'initialization' of this pattern.
In the .cpp I put:

SingletonPointer* SingletonClass::s (0);

But I don't understand how is it possible to <s>access</s> define s, as it is private.
How's that possible?

TIA,
Jir

Body:
Static fields must have definitions besides their declaration. The declaration usually goes in the class declaration in the .h file, while the definition almost always goes in the .cpp file. The definition of static variables is a must, since they must be initialized to something.

But even though the definition is outside of the class body and even in an entirely different file, it doesn't mean it's not a part of the class. The SingletonClass:: makes it part of the class definition (as opposed to the class declaration), and therefore it can 'access' private fields.

The same goes for methods defined outside of the class body, for instance:

// A.h
class A
{
private:
    int b;
public:
    A(int x) : b(x)
    {}

    Do();
}

// A.cpp
A::Do()
{
    return b;
}


问:
psycopg2 insert python dictionary as json
I want to insert a python dictionary as a json into my postgresql database (via python and psycopg2).

I have:

thedictionary = {'price money': '$1', 'name': 'Google', 'color': '', 'imgurl': 'http://www.google.com/images/nav_logo225.png', 'charateristics': 'No Description', 'store': 'google'}

cur.execute("INSERT INTO product(store_id, url, price, charecteristics, color, dimensions) VALUES (%d, %s, %s, %d, %s, %s)", (1,  'http://www.google.com', '$20', thedictionary, 'red', '8.5x11'))
```

And it gives the error message:

cur.execute("INSERT INTO product(store_id, url, price, charecteristics, color, dimensions) VALUES (%d, %s, %s, %d, %s, %s)", (1,  'http://www.google.com', '$20', thedictionary, 'red', '8.5x11'))
      psycopg2.ProgrammingError: can't adapt type 'dict'

I am not sure how to proceed from here.
I cannot find anything on the internet about how to do this exact kind of thing and I am very new to psycopg2.

答:
Is there a particular reason you want to have each key as its own column? Postgres lets you perform direct query operations within a single column containing valid JSON or JSONB

This means you can simply create a 2 column DB with ID (primary key) and metadata and then perform queries such as:

```<code>SELECT * FROM users WHERE metadata @> '{"key": "value"}';
</code>```

Here is a good resource for you.

Body:
I want to insert a python dictionary as a json into my postgresql database (via python and psycopg2).

I have:

thedictionary = {'price money': '$1', 'name': 'Google', 'color': '', 'imgurl': 'http://www.google.com/images/nav_logo225.png', 'charateristics': 'No Description', 'store': 'google'}

cur.execute("INSERT INTO product(store_id, url, price, charecteristics, color, dimensions) VALUES (%d, %s, %s, %d, %s, %s)", (1,  'http://www.google.com', '$20', thedictionary, 'red', '8.5x11'))

And it gives the error message:

cur.execute("INSERT INTO product(store_id, url, price, charecteristics, color, dimensions) VALUES (%d, %s, %s, %d, %s, %s)", (1,  'http://www.google.com', '$20', thedictionary, 'red', '8.5x11'))
      psycopg2.ProgrammingError: can't adapt type 'dict'

I am not sure how to proceed from here.
I cannot find anything on the internet about how to do this exact kind of thing and I am very new to psycopg2.

Body:
Is there a particular reason you want to have each key as its own column? Postgres lets you perform direct query operations within a single column containing valid JSON or JSONB

This means you can simply create a 2 column DB with ID (primary key) and metadata and then perform queries such as:

SELECT * FROM users WHERE metadata @> '{"key": "value"}';

Here is a good resource for you.


问:
How to fix 'If(isset($_POST['Id'])) error' while editing the form in a PHP based CRUD application?
The "if(isset($_POST["titleId"]) && !empty($_POST["titleId"])" in my code is returning false value.

I'm working on a CRUD application, the insert modal is working fine, now I'm stuck at the update part of it.  So when you click on the update icon it does fetch the right titleId in the URL but the first 'if' condition returns false and hence the update isn't working.

Here's what I've tried so far.

```<code>admin.php
<?php
$typeId = filter_input(INPUT_GET, "type");
$titleId = filter_input(INPUT_GET, "titleId");
$active = "admin" . $typeId;
require_once './pages/header.php';
require_once './functions/queries.php';
$getAll = Queries::getAllTitle($typeId);

?>
<div class="container">
<div class="wrapper">
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-12">
                    <div class="page-header clearfix">
                        <h2 class="pull-left"></h2>
                        <button type="button" class="btn btn-success btn-sm" data-toggle="modal" data-target="#facultyAddModal">Add Title</button>
                    </div>

<!--<div class="container">
    <button type="button" class="btn btn-success btn-sm" data-toggle="modal" data-target="#facultyAddModal">Add Title</button>
    <br><br>-->
    <div class="panel-group" id="titleAccordion">
        <?php
        for ($i = 0; $i < count($getAll); $i++) {
            echo <<<HTML
                <div class="panel panel-default">
                    <div class="panel-heading"><h4 class="panel-title">
                        <a data-toggle="collapse" data-parent="#titleAccordion" href="#collapseF{$i}">{$getAll[$i]['title']}</a></h4>
                    </div>
                        <div id="collapseF{$i}" class="panel-collapse collapse" >
                        <div class="panel-body">
                            <div class="table-responsive">
                                <table class="table table-condensed"><tbody>
                                <tr><td>Title:</td><td>{$getAll[$i]['title']}</td></tr>
                                <tr><td>Units:</td><td>{$getAll[$i]['units']}</td></tr>
                                <tr><td>Category:</td><td>{$getAll[$i]['category']}</td></tr>
                            <tr><td>
                                <tr><td><input type="hidden" id="titleId" name="titleId" value="{$getAll[$i]['titleId']}"> </tr><td>
                             <a href='edit.php?titleId={$getAll[$i]['titleId']}' title='Update Record' data-toggle='tooltip'><span class='glyphicon glyphicon-pencil'></span></a>
                             <a href='delete.php?titleId={$getAll[$i]['titleId']}' title='Delete Record' data-toggle='tooltip'><span class='glyphicon glyphicon-trash'></span></a>
                            </tr></td>

                                </tbody></table>
                            </div>

                      </div>
                     </div>
                </div>
HTML;
       }
       ?>
    </div>
            </div>
            </div>
        </div>
    </div>
</div>

<!--    Title Add Modal-->

       <div class="modal fade" id="facultyAddModal" role="dialog">
           <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">×</button>
                    <h4 class="modal-title">Add Title</h4>
                </div>
                <div class="modal-body">
                 <div id="adminResult" class="hide" role="alert">
               <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
                 <div id="resultAdminContent"></div>
                </div>
                    <form class="cmxform" id="adminForm" method="post">
                <label for="Activity">ActivityAttended (required)</label>
                <input class="form-control" id="adminTitle" name="title" type="text" required>
            <br>
                <label for="units">Units (required)</label>
                <input class="form-control" id="adminUnits" type="number" name="units" required>
            <br>
                <label for="Category">Category (Optional)</label>
                <input class="form-control" id="adminCategory" type="text" name="category">
            <br>
                <?php echo
                 '<input type="hidden" id="addadminTypeId" value="'.$typeId.'">';
                ?>
                <?php echo
                 '<input type="hidden" id="titleId" name="titleId" value="'.$titleId.'">';
                ?>

                <button class="btn btn-info btn-primary" type="submit">Submit</button>
            <br>
            <br>
        </form>
          </div>
            </div>
          </div>
        </div>

update.php

<?php
require_once 'functions/db_connection.php';
 $conn = DB::databaseConnection();
$title = $units = $category = "";

if(isset($_POST["titleId"]) && !empty($_POST["titleId"])){

        $titleId = $_POST['titleId'];

        $sql =  "UPDATE title SET title = :title, units = :units, category = :category WHERE titleId = :titleId";

       if($stmt = $conn->prepare($sql))
        {
            // Bind variables to the prepared statement as parameters
           $stmt->bindParam(':titleId', $titleId);
           $stmt->bindParam(':title', $title);
           $stmt->bindParam(':units', $units);
           $stmt->bindParam(':category', $category);
           if ($stmt->execute()) {
              header("location: index.php");
                exit();
            } else{
                echo "Something went wrong. Please try again later.";
            }

        unset($stmt);
    }

    unset($conn);
} else{

    if(isset($_GET["titleId"]) && !empty(trim($_GET["titleId"]))){
        $titleId =  trim($_GET["titleId"]);

        $sql = "SELECT * FROM title WHERE titleId = :titleId";
        if($stmt = $conn->prepare($sql))
        {
            $stmt->bindParam(':titleId', $titleId);
            if ($stmt->execute()){
                   if($stmt->rowCount() == 1){
                $result = $stmt->fetch(PDO::FETCH_ASSOC);
                    // Retrieve individual field value
                    $title = $result["title"];
                    $units = $result["units"];
                    $category = $result["category"];
                } else{
                    echo"error1";
                    exit();
                }

            } else{
                echo "Oops! Something went wrong. Please try again later.";
            }
        }

        unset($stmt);

        unset($conn);
    }  else{
        // URL doesn't contain id parameter. Redirect to error page
        echo"error2";
        exit();
    }
}
?>

<!--<!DOCTYPE html>-->
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Update Record</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
    <style type="text/css">
        .wrapper{
            width: 500px;
            margin: 0 auto;
        }
    </style>
</head>

<body>

    <div class="wrapper">
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-12">
                    <div class="page-header">
                        <h2>Update Record</h2>
                    </div>
    <form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
                <label for="Activity">Title</label>
                <input class="form-control" id="adminTitle" name="title" type="text" value="<?php echo $title; ?>" required>

            <br>
                <label for="units">Units (required)</label>
                <input class="form-control" id="adminUnits" type="number" name="units" value="<?php echo $units; ?>" required>
            <br>
                <label for="Category">Category (Optional)</label>
                <input class="form-control" id="adminCategory" type="text" value="<?php echo $category; ?>" name="category">
            <br>
                <input type="hidden"  name="titleId" value="<?php echo $titleId; ?>">
                <button class="btn btn-info btn-primary" type="submit">Submit</button>
            <br>

            <br>
        </form>
                </div>
            </<div>
        </div>
       </div>
    </div>
</body>
</html>

</code>```

The only goal here is to get the update form working, the user should be able to update the records of the respective title being selected.

答:
I don't know crud but I think there is a way to debug a little:

e.g. try this:

```<code>if(isset($_POST["titleId"]) && !empty($_POST["titleId"])){
   // test if you are here:
   echo 'hi, yeah I am here!';
}
</code>```

or this

```<code>echo '```';
var_dump($_POST);
echo '```';
// before:
if(isset($_POST["titleId"]) && !empty($_POST["titleId"])){
    // ...
}
</code>```

also, take a look at

```<code>error_get_last()['message']
</code>```

Body:
The "if(isset($_POST["titleId"]) && !empty($_POST["titleId"])" in my code is returning false value.

I'm working on a CRUD application, the insert modal is working fine, now I'm stuck at the update part of it.  So when you click on the update icon it does fetch the right titleId in the URL but the first 'if' condition returns false and hence the update isn't working.

Here's what I've tried so far.

admin.php
<?php
$typeId = filter_input(INPUT_GET, "type");
$titleId = filter_input(INPUT_GET, "titleId");
$active = "admin" . $typeId;
require_once './pages/header.php';
require_once './functions/queries.php';
$getAll = Queries::getAllTitle($typeId);

?>

                        <button type="button" class="btn btn-success btn-sm" data-toggle="modal" data-target="#facultyAddModal">Add Title</button>

        <?php
        for ($i = 0; $i < count($getAll); $i++) {
            echo <<<HTML

                        {$getAll[$i]['title']}

Title:	{$getAll[$i]['title']}

Units:	{$getAll[$i]['units']}

Category:	{$getAll[$i]['category']}

<input type="hidden" id="titleId" name="titleId" value="{$getAll[$i]['titleId']}">

HTML;
       }
       ?>

                    <button type="button" class="close" data-dismiss="modal">×</button>

Add Title

               <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>

                    <form class="cmxform" id="adminForm" method="post">
                ActivityAttended (required)
                <input class="form-control" id="adminTitle" name="title" type="text" required>

                Units (required)
                <input class="form-control" id="adminUnits" type="number" name="units" required>

                Category (Optional)
                <input class="form-control" id="adminCategory" type="text" name="category">

                <?php echo
                 '<input type="hidden" id="addadminTypeId" value="'.$typeId.'">';
                ?>
                <?php echo
                 '<input type="hidden" id="titleId" name="titleId" value="'.$titleId.'">';
                ?>

                <button class="btn btn-info btn-primary" type="submit">Submit</button>

        </form>

update.php

<?php
require_once 'functions/db_connection.php';
 $conn = DB::databaseConnection();
$title = $units = $category = "";

if(isset($_POST["titleId"]) && !empty($_POST["titleId"])){

        $titleId = $_POST['titleId'];

        $sql =  "UPDATE title SET title = :title, units = :units, category = :category WHERE titleId = :titleId";

       if($stmt = $conn->prepare($sql))
        {
            // Bind variables to the prepared statement as parameters
           $stmt->bindParam(':titleId', $titleId);
           $stmt->bindParam(':title', $title);
           $stmt->bindParam(':units', $units);
           $stmt->bindParam(':category', $category);
           if ($stmt->execute()) {
              header("location: index.php");
                exit();
            } else{
                echo "Something went wrong. Please try again later.";
            }

        unset($stmt);
    }

    unset($conn);
} else{

    if(isset($_GET["titleId"]) && !empty(trim($_GET["titleId"]))){
        $titleId =  trim($_GET["titleId"]);

        $sql = "SELECT * FROM title WHERE titleId = :titleId";
        if($stmt = $conn->prepare($sql))
        {
            $stmt->bindParam(':titleId', $titleId);
            if ($stmt->execute()){
                   if($stmt->rowCount() == 1){
                $result = $stmt->fetch(PDO::FETCH_ASSOC);
                    // Retrieve individual field value
                    $title = $result["title"];
                    $units = $result["units"];
                    $category = $result["category"];
                } else{
                    echo"error1";
                    exit();
                }

            } else{
                echo "Oops! Something went wrong. Please try again later.";
            }
        }

        unset($stmt);

        unset($conn);
    }  else{
        // URL doesn't contain id parameter. Redirect to error page
        echo"error2";
        exit();
    }
}
?>

    <meta charset="UTF-8">
    <title>Update Record</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">

Update Record

    <form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
                Title
                <input class="form-control" id="adminTitle" name="title" type="text" value="<?php echo $title; ?>" required>

                Units (required)
                <input class="form-control" id="adminUnits" type="number" name="units" value="<?php echo $units; ?>" required>

                Category (Optional)
                <input class="form-control" id="adminCategory" type="text" value="<?php echo $category; ?>" name="category">

                <input type="hidden"  name="titleId" value="<?php echo $titleId; ?>">
                <button class="btn btn-info btn-primary" type="submit">Submit</button>

        </form>

            </

The only goal here is to get the update form working, the user should be able to update the records of the respective title being selected.

Body:
I don't know crud but I think there is a way to debug a little:

e.g. try this:

if(isset($_POST["titleId"]) && !empty($_POST["titleId"])){
   // test if you are here:
   echo 'hi, yeah I am here!';
}

or this

echo '<pre>';
var_dump($_POST);
echo '</pre>';
// before:
if(isset($_POST["titleId"]) && !empty($_POST["titleId"])){
    // ...
}

also, take a look at

error_get_last()['message']


问:
How to prevent users from turning off GPS, Wifi and Bluetooth?
I'm developing a tracking application and I need to prevent users from turning off the basic sensors used to determine the location. I can not modify the devices ROM or have root access (or at least it would be very desirable to had not), but I thought of using the Device Administration API to perform these functions through the Profile Owner or Device Owner modes. I'm basically looking for a method to block these functions in Android settings.

I'm unsure about whether this is possible and how to do it, I have not found examples in GitHub for applications that have implemented this. Could anyone give me a light, some example or specific documentation?

I tried to follow these three documentations, without success in finding a solution to this specific feature:

https://source.android.com/devices/tech/admin
  https://developer.android.com/guide/topics/admin/device-admin
  https://developers.google.com/android/management/introduction

This is an excerpt from what I've been trying:

```<code>setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true);
setUserRestriction(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS, active);
setUserRestriction(UserManager.DISALLOW_CONFIG_BLUETOOTH, active);

private void setUserRestriction(String restriction, boolean disallow){
    if (disallow) {
        mDevicePolicyManager.addUserRestriction(mAdminComponentName, restriction);
    } else {
        mDevicePolicyManager.clearUserRestriction(mAdminComponentName,
restriction);
    }
}
</code>```

DISALLOW_CONFIG_BLUETOOTH
  Added in API level 18
  public static final String DISALLOW_CONFIG_BLUETOOTH

Specifies if a user is disallowed from configuring bluetooth. This does not restrict the user from turning bluetooth on or off. The default value is false.

This restriction doesn't prevent the user from using bluetooth. For disallowing usage of bluetooth completely on the device, use DISALLOW_BLUETOOTH.

This restriction has no effect in a managed profile.

Key for user restrictions.

Type: Boolean

答:
You cannot prevent them from turning GPS, WIFI and Bluetooth off. What you can do is have an implementation as below or use this library.

https://github.com/KI-labs/gps-permission-checks-livedata

Body:
I'm developing a tracking application and I need to prevent users from turning off the basic sensors used to determine the location. I can not modify the devices ROM or have root access (or at least it would be very desirable to had not), but I thought of using the Device Administration API to perform these functions through the Profile Owner or Device Owner modes. I'm basically looking for a method to block these functions in Android settings.

I'm unsure about whether this is possible and how to do it, I have not found examples in GitHub for applications that have implemented this. Could anyone give me a light, some example or specific documentation?

I tried to follow these three documentations, without success in finding a solution to this specific feature:

https://source.android.com/devices/tech/admin
  https://developer.android.com/guide/topics/admin/device-admin
  https://developers.google.com/android/management/introduction

This is an excerpt from what I've been trying:

setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true);
setUserRestriction(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS, active);
setUserRestriction(UserManager.DISALLOW_CONFIG_BLUETOOTH, active);

private void setUserRestriction(String restriction, boolean disallow){
    if (disallow) {
        mDevicePolicyManager.addUserRestriction(mAdminComponentName, restriction);
    } else {
        mDevicePolicyManager.clearUserRestriction(mAdminComponentName,
restriction);
    }
}

DISALLOW_CONFIG_BLUETOOTH
  Added in API level 18
  public static final String DISALLOW_CONFIG_BLUETOOTH

Specifies if a user is disallowed from configuring bluetooth. This does not restrict the user from turning bluetooth on or off. The default value is false.

This restriction doesn't prevent the user from using bluetooth. For disallowing usage of bluetooth completely on the device, use DISALLOW_BLUETOOTH.

This restriction has no effect in a managed profile.

Key for user restrictions.

Type: Boolean


问:
Post permalink structure not found when adding a custom prefix
I'm trying to setting the post permalink and category base like that:

Post URL: site.com/insights/%category%/%postname%/

Category Base: insights

The attachment here: tinyurl.com/y3jlqucq

But the post is return 404 - page not found. How to fix this?

答: In "Custom Structure" remove /insights/, it's on "Category base". Maybe it help.</p>


问:
Wrong value returned when converting from raw character to hex equivalent
I have an application where the input is a raw set of bytes and I want to see the two-digit hex code of each of those bytes. For now I'm trying to get the proper hex code for one byte. This is my code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){
char hexvc; //= ascii code for hex value
char aval[2]={0xFF,0x00}; //Our raw 1 byte data. can't print actual code here
char hexv[20]; //value for output
memset(hexv,0,19); //clear output
hexvc=strtol(aval,NULL,16) & 0xFF;
if (hexvc != '\0'){
    sprintf(hexv,"%02hx",hexvc);
}else{
    //hexvc always equals 0. why not FFh?
    strcpy(hexv,"00");
}
printf("%s\n",hexv);
return 0;
}
</code>```

I expected to see ff appear on the screen, but instead I see 00.
How do I fix this?

And if I change 0xFF after aval[2]= to 0x31 or '1' (since 1 is the actual value for ascii code 0x31) then I want to see 31 appear on the screen.

答:
```<code>char aval[] = {0x66, 0x66, 0x00};
</code>```

0x66 is char 'f' in ascii

Body:
I have an application where the input is a raw set of bytes and I want to see the two-digit hex code of each of those bytes. For now I'm trying to get the proper hex code for one byte. This is my code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){
char hexvc; //= ascii code for hex value
char aval[2]={0xFF,0x00}; //Our raw 1 byte data. can't print actual code here
char hexv[20]; //value for output
memset(hexv,0,19); //clear output
hexvc=strtol(aval,NULL,16) & 0xFF;
if (hexvc != '\0'){
    sprintf(hexv,"%02hx",hexvc);
}else{
    //hexvc always equals 0. why not FFh?
    strcpy(hexv,"00");
}
printf("%s\n",hexv);
return 0;
}

I expected to see ff appear on the screen, but instead I see 00.
How do I fix this?

And if I change 0xFF after aval[2]= to 0x31 or '1' (since 1 is the actual value for ascii code 0x31) then I want to see 31 appear on the screen.

Body:
char aval[] = {0x66, 0x66, 0x00};

0x66 is char 'f' in ascii


问:
What type of analysis with categorical outcome with both continuous and categorical predictors?
I have a categorical outcome (Response) that is either -1 or 1.
I also have predictors (Weight, Condition, Trial Type) where all are categorical except weight which is continuous.

Basically, what I want to know is if Response changed depending on the weight of the trial.

So like Sbj 500, were they more likely to have a response of -1 at the weight of 6 versus the weight of 1.

Since my outcome is categorical, I did a GLM. But my overall model is not sig but each predictor is. I am not sure what the appropriate test to do is.

# Sample data frame
df500 <- data.frame(Sbj = c(500), TrialNum=c(1:6),
                    Condition=c(1,1,1,1,1,1),
                    TrialType = c(1, 1, 1, -1, -1, -1),
                    Weight=c(1:6), Response=c(-1,1,-1,1,1,-1))

df501 <- data.frame(Sbj = c(501), TrialNum=c(1:6),
                    Condition=c(-1,-1,-1,-1,-1,-1),
                    TrialType = c(-1, -1, -1, 1, 1, 1),
                    Weight=c(6:1), Response=c(1,-1,-1,1,1,-1))

df502 <- data.frame(Sbj = c(502), TrialNum=c(1:6),
                    Condition=c(1,1,1,1,1,1),
                    TrialType = c(1, 1, 1, -1, -1, -1),
                    Weight=c(1:6), Response=c(1,-1,-1,-1,1,1))

df <- merge(df500, df501, all=TRUE)
df <- merge(df, df502, all=TRUE)

# GLM
GLM_m <- glm(Response ~ 1 + Condition*Type*Weight,
             data = df, family = "binomial")
summary(GLM_m)

```

In my summary, the individual coefficients are sig, but the overall model is not. What does this mean?

答:
Testing depends only on the type of outcome.

In your case, for categorical outcome you should make use of tests such as accuracy, precision, recall, f-score and confusion matrix.

You can use error based metrics for continuous outcomes. These metrics include mean square error, mean absolute error, root mean square error, just to mention a few.

To see how various features relate to the predictions, you must have a look at the model summary. The summary consists of coefficients of the various features and answer your question of how well each feature relates to the prediction (How strongly does the feature affect the prediction).

Here is a comprehensive explanation to the model summary of a glm model.

Model summary of glm model.

Body:
I have a categorical outcome (Response) that is either -1 or 1.
I also have predictors (Weight, Condition, Trial Type) where all are categorical except weight which is continuous.

Basically, what I want to know is if Response changed depending on the weight of the trial.

So like Sbj 500, were they more likely to have a response of -1 at the weight of 6 versus the weight of 1.

Since my outcome is categorical, I did a GLM. But my overall model is not sig but each predictor is. I am not sure what the appropriate test to do is.

# Sample data frame
df500 <- data.frame(Sbj = c(500), TrialNum=c(1:6),
                    Condition=c(1,1,1,1,1,1),
                    TrialType = c(1, 1, 1, -1, -1, -1),
                    Weight=c(1:6), Response=c(-1,1,-1,1,1,-1))

df501 <- data.frame(Sbj = c(501), TrialNum=c(1:6),
                    Condition=c(-1,-1,-1,-1,-1,-1),
                    TrialType = c(-1, -1, -1, 1, 1, 1),
                    Weight=c(6:1), Response=c(1,-1,-1,1,1,-1))

df502 <- data.frame(Sbj = c(502), TrialNum=c(1:6),
                    Condition=c(1,1,1,1,1,1),
                    TrialType = c(1, 1, 1, -1, -1, -1),
                    Weight=c(1:6), Response=c(1,-1,-1,-1,1,1))

df <- merge(df500, df501, all=TRUE)
df <- merge(df, df502, all=TRUE)

# GLM
GLM_m <- glm(Response ~ 1 + Condition*Type*Weight,
             data = df, family = "binomial")
summary(GLM_m)

In my summary, the individual coefficients are sig, but the overall model is not. What does this mean?


问:
Recursion to print number by using return statement
I'm using recursion to print numbers until 2(number), and I'm passing zero(0) as input and recursively calling it until the number reaches 2.
I have tried this code, and it shows the correct output.

```<code>class Test{
    public static void main(String[] args) {
        rec(0);
    }
    private static void rec(int num){
        if(num<=2){
            rec(++num);
        }
        System.out.println(num);
    }
}
</code>```

but I want to do this with the following way.

```<code>class Test{
    public static void main(String[] args) {
        rec(0);
    }
    private static void rec(int num){
        if(num==2){
            return;
        }
        rec(++num);
        System.out.println(num);
    }
}
</code>```

Expected output:

```<code>2,1,0
</code>```

but it shows:

```<code>2,1
</code>```

Why does it happen?

答:
It happens because ++num doesn't just return num + 1 it also modifies num like num = num + 1.

Your if statement is also backwards.

```<code>public class Test {

  public static void main(String[] args) {
    rec(0);
  }

  private static void rec(int num) {
    if (num < 2) {
      rec(num + 1);
    }
    System.out.println(num);
  }
</code>```

Body:
I'm using recursion to print numbers until 2(number), and I'm passing zero(0) as input and recursively calling it until the number reaches 2.
I have tried this code, and it shows the correct output.

class Test{
    public static void main(String[] args) {
        rec(0);
    }
    private static void rec(int num){
        if(num<=2){
            rec(++num);
        }
        System.out.println(num);
    }
}

but I want to do this with the following way.

class Test{
    public static void main(String[] args) {
        rec(0);
    }
    private static void rec(int num){
        if(num==2){
            return;
        }
        rec(++num);
        System.out.println(num);
    }
}

Expected output:

2,1,0

but it shows:

2,1

Why does it happen?

Body:
It happens because ++num doesn't just return num + 1 it also modifies num like num = num + 1.

Your if statement is also backwards.

public class Test {

  public static void main(String[] args) {
    rec(0);
  }

  private static void rec(int num) {
    if (num < 2) {
      rec(num + 1);
    }
    System.out.println(num);
  }


问:
.designer file not being associated with .cs file in visual studio?

EDIT:

There seems to be a visual (?) bug in visual studio. When I opened my website folder as a website and looked at my Views.ascx.designer.cs it doesn't show that it is associated. However, if I open that same website's solution file then the files are associated and all is well.

Just to be clear, even though it is still showing the below error messages it is working and I believe that it's a bug with opening it as a website instead of as a solution.

On my live site I have an error:

But it should exist because I have it in my Views.ascx.designer.cs:

But in Visual Studio my Views.ascx.designer.cs is not being associated with my View.ascx:

I tried to drag and drop the .designer file onto View.ascx but it displayed this error message:

It works and looks perfectly fine on my dev server:

I'm not sure how I would go about getting the file to associate itself with the View.ascx or View.ascx.cs files.

答: Have had the same issue while adding form from other project to the pending one , I've excluded both files then added back by adding non-designer file 1st and .Designer.cs was then added in the right place automatically from the same catalogue as .cs file (VS2012).</p>