问:
TypeError: Cannot read property 'database' of undefined. Any ideas?
I am working at this project https://github.com/ameCont/vue.git
Index.js file:

```<code>const fs = require('fs')
const path = require('path')
const Sequelize = require('sequelize')
const config = require('../config/config')
const db = {}

//console.log(config)

const sequelize = new Sequelize(
    config.db.database,
    config.db.user,
    config.db.password,
    config.db.options
)

fs
    .readdirSync(__dirname)
    .filter((file) => {
        file !== 'index.js'
    }
    )
    .forEach((file) => {
        const model = sequelize.import(path.join(__dirName, file))
        db[model.name] = model
    })

    db.sequelize = sequelize
    db.Sequelize = Sequelize

    module.exports = db
</code>```

When I run

```<code>npm start
</code>```

inside server directory I get the error

```<code>/home/ubuntu/vue/server/src/models/index.js:10
    config.db.database,
              ^

TypeError: Cannot read property 'database' of undefined
    at Object.<anonymous> (/home/ubuntu/vue/server/src/models/index.js:10:15)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Module.require (internal/modules/cjs/loader.js:692:17)
    at require (internal/modules/cjs/helpers.js:25:18)
    at Object.<anonymous> (/home/ubuntu/vue/server/src/app.js:7:21)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)
[nodemon] app crashed - waiting for file changes before starting...
</code>```

My config.js file contains:

```<code>module.exports = {
    port: process.env.PORT || 8081,
    db: {
        database: process.env.DB_NAME || 'vue',
        user: process.env.DB_USER || 'vue',
        password: process.env.DB_PASS || 'vue',
        options: {
            dialect: process.env.DIALECT || 'sqlite',
            host: process.env.HOST || 'localhost',
            storage: 'vue.sqlite.sql'
        }
    }
}
</code>```

It has || 'vue' so it shouldn't need a real database (I created one but the issue is the same)
I am beginner with vue.
Here JS: firebase.init error: TypeError: Cannot read property 'database' of undefined, the solution was to install some plugins.
But in my case which plugins?

If it helps, when I run

```<code>npm install sqlite3
</code>```

I get this

```<code>> sqlite3@4.2.0 install /home/ubuntu/vue/server/node_modules/sqlite3
> node-pre-gyp install --fallback-to-build

node-pre-gyp WARN Using request for node-pre-gyp https download
node-pre-gyp WARN Pre-built binaries not installable for sqlite3@4.2.0 and node@10.19.0 (node-v64 ABI, glibc) (falling back to source compile with node-gyp)
node-pre-gyp WARN Hit error EACCES: permission denied, mkdir '/home/ubuntu/vue/server/node_modules/sqlite3/lib/binding'
gyp ERR! configure error
gyp ERR! stack Error: EACCES: permission denied, mkdir '/home/ubuntu/vue/server/node_modules/sqlite3/build'
gyp ERR! System Linux 5.4.0-26-generic
gyp ERR! command "/usr/bin/node" "/usr/bin/node-gyp" "configure" "--fallback-to-build" "--module=/home/ubuntu/vue/server/node_modules/sqlite3/lib/binding/node-v64-linux-x64/node_sqlite3.node" "--module_name=node_sqlite3" "--module_path=/home/ubuntu/vue/server/node_modules/sqlite3/lib/binding/node-v64-linux-x64" "--napi_version=5" "--node_abi_napi=napi" "--napi_build_version=0" "--node_napi_label=node-v64"
gyp ERR! cwd /home/ubuntu/vue/server/node_modules/sqlite3
gyp ERR! node -v v10.19.0
gyp ERR! node-gyp -v v6.1.0
gyp ERR! not ok
node-pre-gyp ERR! build error
node-pre-gyp ERR! stack Error: Failed to execute '/usr/bin/node /usr/bin/node-gyp configure --fallback-to-build --module=/home/ubuntu/vue/server/node_modules/sqlite3/lib/binding/node-v64-linux-x64/node_sqlite3.node --module_name=node_sqlite3 --module_path=/home/ubuntu/vue/server/node_modules/sqlite3/lib/binding/node-v64-linux-x64 --napi_version=5 --node_abi_napi=napi --napi_build_version=0 --node_napi_label=node-v64' (1)
node-pre-gyp ERR! stack     at ChildProcess.<anonymous> (/home/ubuntu/vue/server/node_modules/node-pre-gyp/lib/util/compile.js:83:29)
node-pre-gyp ERR! stack     at ChildProcess.emit (events.js:198:13)
node-pre-gyp ERR! stack     at maybeClose (internal/child_process.js:982:16)
node-pre-gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:259:5)
node-pre-gyp ERR! System Linux 5.4.0-26-generic
node-pre-gyp ERR! command "/usr/bin/node" "/home/ubuntu/vue/server/node_modules/.bin/node-pre-gyp" "install" "--fallback-to-build"
node-pre-gyp ERR! cwd /home/ubuntu/vue/server/node_modules/sqlite3
node-pre-gyp ERR! node -v v10.19.0
node-pre-gyp ERR! node-pre-gyp -v v0.11.0
node-pre-gyp ERR! not ok
Failed to execute '/usr/bin/node /usr/bin/node-gyp configure --fallback-to-build --module=/home/ubuntu/vue/server/node_modules/sqlite3/lib/binding/node-v64-linux-x64/node_sqlite3.node --module_name=node_sqlite3 --module_path=/home/ubuntu/vue/server/node_modules/sqlite3/lib/binding/node-v64-linux-x64 --napi_version=5 --node_abi_napi=napi --napi_build_version=0 --node_napi_label=node-v64' (1)
npm WARN eslint-plugin-import@2.20.2 requires a peer of eslint@2.x - 6.x but none is installed. You must install peer dependencies yourself.
npm WARN eslint-plugin-vue@6.2.2 requires a peer of eslint@^5.0.0 || ^6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN tsutils@3.17.1 requires a peer of typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta but none is installed. You must install peer dependencies yourself.
npm WARN server@1.0.0 No description
npm WARN server@1.0.0 No repository field.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! sqlite3@4.2.0 install: `node-pre-gyp install --fallback-to-build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the sqlite3@4.2.0 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
</code>```

Also, this topic doesn't help TypeError: Cannot read property 'database' of undefined
because I do have const config = require('../config/config')

Thanks for help!

答:
Actually, in your config you have two exports, so for correctly accessing it you should name the exported objects:

```<code>module.exports.config = {
    port: process.env.PORT || 8081,
    db: {
        database: process.env.DB_NAME || 'vue',
        user: process.env.DB_USER || 'vue',
        password: process.env.DB_PASS || 'vue',
        options: {
            dialect: process.env.DIALECT || 'sqlite',
            host: process.env.HOST || 'localhost',
            storage: 'vue.sqlite.sql'
        }
    }
}

module.exports.otherConfigs = {
    // other configs ..
}
</code>```

Then in model's index.js you import the configs like that:

```<code>const { config, otherConfigs } = require('../config/config')
</code>```

Body:
I am working at this project https://github.com/ameCont/vue.git
Index.js file:

const fs = require('fs')
const path = require('path')
const Sequelize = require('sequelize')
const config = require('../config/config')
const db = {}

//console.log(config)

const sequelize = new Sequelize(
    config.db.database,
    config.db.user,
    config.db.password,
    config.db.options
)

fs
    .readdirSync(__dirname)
    .filter((file) => {
        file !== 'index.js'
    }
    )
    .forEach((file) => {
        const model = sequelize.import(path.join(__dirName, file))
        db[model.name] = model
    })

    db.sequelize = sequelize
    db.Sequelize = Sequelize

    module.exports = db

When I run

npm start

inside server directory I get the error

/home/ubuntu/vue/server/src/models/index.js:10
    config.db.database,
              ^

TypeError: Cannot read property 'database' of undefined
    at Object.<anonymous> (/home/ubuntu/vue/server/src/models/index.js:10:15)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Module.require (internal/modules/cjs/loader.js:692:17)
    at require (internal/modules/cjs/helpers.js:25:18)
    at Object.<anonymous> (/home/ubuntu/vue/server/src/app.js:7:21)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)
[nodemon] app crashed - waiting for file changes before starting...

My config.js file contains:

module.exports = {
    port: process.env.PORT || 8081,
    db: {
        database: process.env.DB_NAME || 'vue',
        user: process.env.DB_USER || 'vue',
        password: process.env.DB_PASS || 'vue',
        options: {
            dialect: process.env.DIALECT || 'sqlite',
            host: process.env.HOST || 'localhost',
            storage: 'vue.sqlite.sql'
        }
    }
}

It has || 'vue' so it shouldn't need a real database (I created one but the issue is the same)
I am beginner with vue.
Here JS: firebase.init error: TypeError: Cannot read property 'database' of undefined, the solution was to install some plugins.
But in my case which plugins?

If it helps, when I run

npm install sqlite3

I get this

> sqlite3@4.2.0 install /home/ubuntu/vue/server/node_modules/sqlite3
> node-pre-gyp install --fallback-to-build

node-pre-gyp WARN Using request for node-pre-gyp https download
node-pre-gyp WARN Pre-built binaries not installable for sqlite3@4.2.0 and node@10.19.0 (node-v64 ABI, glibc) (falling back to source compile with node-gyp)
node-pre-gyp WARN Hit error EACCES: permission denied, mkdir '/home/ubuntu/vue/server/node_modules/sqlite3/lib/binding'
gyp ERR! configure error
gyp ERR! stack Error: EACCES: permission denied, mkdir '/home/ubuntu/vue/server/node_modules/sqlite3/build'
gyp ERR! System Linux 5.4.0-26-generic
gyp ERR! command "/usr/bin/node" "/usr/bin/node-gyp" "configure" "--fallback-to-build" "--module=/home/ubuntu/vue/server/node_modules/sqlite3/lib/binding/node-v64-linux-x64/node_sqlite3.node" "--module_name=node_sqlite3" "--module_path=/home/ubuntu/vue/server/node_modules/sqlite3/lib/binding/node-v64-linux-x64" "--napi_version=5" "--node_abi_napi=napi" "--napi_build_version=0" "--node_napi_label=node-v64"
gyp ERR! cwd /home/ubuntu/vue/server/node_modules/sqlite3
gyp ERR! node -v v10.19.0
gyp ERR! node-gyp -v v6.1.0
gyp ERR! not ok
node-pre-gyp ERR! build error
node-pre-gyp ERR! stack Error: Failed to execute '/usr/bin/node /usr/bin/node-gyp configure --fallback-to-build --module=/home/ubuntu/vue/server/node_modules/sqlite3/lib/binding/node-v64-linux-x64/node_sqlite3.node --module_name=node_sqlite3 --module_path=/home/ubuntu/vue/server/node_modules/sqlite3/lib/binding/node-v64-linux-x64 --napi_version=5 --node_abi_napi=napi --napi_build_version=0 --node_napi_label=node-v64' (1)
node-pre-gyp ERR! stack     at ChildProcess.<anonymous> (/home/ubuntu/vue/server/node_modules/node-pre-gyp/lib/util/compile.js:83:29)
node-pre-gyp ERR! stack     at ChildProcess.emit (events.js:198:13)
node-pre-gyp ERR! stack     at maybeClose (internal/child_process.js:982:16)
node-pre-gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:259:5)
node-pre-gyp ERR! System Linux 5.4.0-26-generic
node-pre-gyp ERR! command "/usr/bin/node" "/home/ubuntu/vue/server/node_modules/.bin/node-pre-gyp" "install" "--fallback-to-build"
node-pre-gyp ERR! cwd /home/ubuntu/vue/server/node_modules/sqlite3
node-pre-gyp ERR! node -v v10.19.0
node-pre-gyp ERR! node-pre-gyp -v v0.11.0
node-pre-gyp ERR! not ok
Failed to execute '/usr/bin/node /usr/bin/node-gyp configure --fallback-to-build --module=/home/ubuntu/vue/server/node_modules/sqlite3/lib/binding/node-v64-linux-x64/node_sqlite3.node --module_name=node_sqlite3 --module_path=/home/ubuntu/vue/server/node_modules/sqlite3/lib/binding/node-v64-linux-x64 --napi_version=5 --node_abi_napi=napi --napi_build_version=0 --node_napi_label=node-v64' (1)
npm WARN eslint-plugin-import@2.20.2 requires a peer of eslint@2.x - 6.x but none is installed. You must install peer dependencies yourself.
npm WARN eslint-plugin-vue@6.2.2 requires a peer of eslint@^5.0.0 || ^6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN tsutils@3.17.1 requires a peer of typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta but none is installed. You must install peer dependencies yourself.
npm WARN server@1.0.0 No description
npm WARN server@1.0.0 No repository field.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! sqlite3@4.2.0 install: `node-pre-gyp install --fallback-to-build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the sqlite3@4.2.0 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

Also, this topic doesn't help TypeError: Cannot read property 'database' of undefined
because I do have const config = require('../config/config')

Thanks for help!

Body:
Actually, in your config you have two exports, so for correctly accessing it you should name the exported objects:

module.exports.config = {
    port: process.env.PORT || 8081,
    db: {
        database: process.env.DB_NAME || 'vue',
        user: process.env.DB_USER || 'vue',
        password: process.env.DB_PASS || 'vue',
        options: {
            dialect: process.env.DIALECT || 'sqlite',
            host: process.env.HOST || 'localhost',
            storage: 'vue.sqlite.sql'
        }
    }
}

module.exports.otherConfigs = {
    // other configs ..
}

Then in model's index.js you import the configs like that:

const { config, otherConfigs } = require('../config/config')


来源: stackexchange

问:
Hide Show More/Less div if more than n lines in sibling div
I am working on a way to display posts in a way that if the text of the post has more than three lines, only the first three lines are displayed and the rest is toggled via a Show More/Show Less div. I am using liquid for the loop over the posts, a css class for truncating and jquery for toggeling the truncate class

My problem now is that I would like to give the Show More/Show Less div the display:none property if we have less than three lines, but I don't know how.

Here is the code excerpt:

html:

```<code><div class="posts">
{% for post in site.posts %}
<div class="post-teaser">
  {% if post.thumbnail %}
  <div class="post-img">
     <img src="{{ site.baseurl }}/{{ post.thumbnail }}">
  </div>
  {% endif %}
  <span>
      <header>
        <h1>
            {{ post.title }}
        </h1>
        <p class="meta">
          {{ post.date | date: "%B %-d, %Y" }}
        </p>
      </header>
      <div id="{{post.path}}" class="excerpt truncate">
          {{ post.content | strip_html | escape }}
      </div>
          <div class="txtcol"><a>Show More</a></div>
  </span>
</div>
{% endfor %}
</code>```

CSS:

```<code>/* styles for '...' */
.truncate {
/* hide text if it more than N lines  */
overflow: hidden;
/* for set '...' in absolute position */
position: relative;
/* use this value to count block height */
line-height: 1.2em;
/* max-height = line-height (1.2) * lines max number (3) */
max-height: 3.6em;
/* fix problem when last visible word doesn't adjoin right side  */
text-align: justify;
/* place for '...' */
margin-right: -1em;
padding-right: 1em;
}
/* create the ... */
.truncate:before {
/* points in the end */
content: '...';
/* absolute position */
position: absolute;
/* set position to right bottom corner of block */
right: 0;
bottom: 0;
}
/* hide ... if we have text, which is less than or equal to max lines
*/
.truncate:after {
/* points in the end */
content: '';
/* absolute position */
position: absolute;
/* set position to right bottom corner of text */
right: 0;
/* set width and height */
width: 1em;
height: 1em;
margin-top: 0.2em;
/* bg color = bg color under block */
background: white;
}
</code>```

from here: http://hackingui.com/front-end/a-pure-css-solution-for-multiline-text-truncation/

And jquery:

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $(".txtcol").click(function(){
    if($(this).prev().hasClass("truncate")) {
            $(this).children('a').text("Show Less");
        } else {
            $(this).children('a').text("Show More");
        }
  $(this).prev().toggleClass("truncate");

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

I would prefer a CSS solution, if possible.

EDIT: here is a snippet:
https://jsfiddle.net/6349q51r/4/

In the second post, the show more/show less should not appear (on most devices).

EDIT 2:
Here is my try to implement it, but somehow the line

```<code>$(this).next().css("display", "none;");
</code>```

does not work.
https://jsfiddle.net/6349q51r/29/+

EDIT 3:
It was a typo; it now works:
https://jsfiddle.net/6349q51r/36/

答:
$(document).ready(function(){
  $(".content").each(function(){
    if($(this).height() < $(this)[0].scrollHeight){
      $(this).parent().find(".txtcol").show();
      $(this).toggleClass("truncate");
    }
  });
  $(".txtcol").click(function(){
    if($(this).prev().hasClass("truncate")) {
        $(this).parent().find(".content").css("max-height", $(this).parent().find(".content")[0].scrollHeight);
            $(this).children('a').text("Show Less");
        } else {
        $(this).parent().find(".content").css("max-height", "3.6em");
            $(this).children('a').text("Show More");
        }
  $(this).prev().toggleClass("truncate");

  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.content {
    width:100px;
    overflow: hidden;
    white-space:normal;
    text-overflow: ellipsis;
    line-height: 1.2em;
    /* max-height = line-height (1.2) * lines max number (3) */
    max-height: 3.6em;
    /* fix problem when last visible word doesn't adjoin right side  */
    text-align: justify;
}
.txtcol{
  display:none;
  color:blue;
  cursor:pointer;
}
.maincontent{
  display:inline-block;
  vertical-align:top;
  border: 1px solid gray;
}</code>```

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Show More

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been Lorem Ipsum has been Lorem Ipsum has been Lorem Ipsum has been

Show More

Lorem Ipsum is simply

Show More

```

ContentLicense: CC BY-SA 4.0

Body:
I am working on a way to display posts in a way that if the text of the post has more than three lines, only the first three lines are displayed and the rest is toggled via a Show More/Show Less div. I am using liquid for the loop over the posts, a css class for truncating and jquery for toggeling the truncate class

My problem now is that I would like to give the Show More/Show Less div the display:none property if we have less than three lines, but I don't know how.

Here is the code excerpt:

html:

{% for post in site.posts %}

  {% if post.thumbnail %}

  {% endif %}

            {{ post.title }}

          {{ post.date | date: "%B %-d, %Y" }}

          {{ post.content | strip_html | escape }}

Show More

{% endfor %}

CSS:

/* styles for '...' */
.truncate {
/* hide text if it more than N lines  */
overflow: hidden;
/* for set '...' in absolute position */
position: relative;
/* use this value to count block height */
line-height: 1.2em;
/* max-height = line-height (1.2) * lines max number (3) */
max-height: 3.6em;
/* fix problem when last visible word doesn't adjoin right side  */
text-align: justify;
/* place for '...' */
margin-right: -1em;
padding-right: 1em;
}
/* create the ... */
.truncate:before {
/* points in the end */
content: '...';
/* absolute position */
position: absolute;
/* set position to right bottom corner of block */
right: 0;
bottom: 0;
}
/* hide ... if we have text, which is less than or equal to max lines
*/
.truncate:after {
/* points in the end */
content: '';
/* absolute position */
position: absolute;
/* set position to right bottom corner of text */
right: 0;
/* set width and height */
width: 1em;
height: 1em;
margin-top: 0.2em;
/* bg color = bg color under block */
background: white;
}

from here: http://hackingui.com/front-end/a-pure-css-solution-for-multiline-text-truncation/

And jquery:

I would prefer a CSS solution, if possible.

EDIT: here is a snippet:
https://jsfiddle.net/6349q51r/4/

In the second post, the show more/show less should not appear (on most devices).

EDIT 2:
Here is my try to implement it, but somehow the line

$(this).next().css("display", "none;");

does not work.
https://jsfiddle.net/6349q51r/29/+

EDIT 3:
It was a typo; it now works:
https://jsfiddle.net/6349q51r/36/

Body:
$(document).ready(function(){
  $(".content").each(function(){
    if($(this).height() < $(this)[0].scrollHeight){
      $(this).parent().find(".txtcol").show();
      $(this).toggleClass("truncate");
    }
  });
  $(".txtcol").click(function(){
    if($(this).prev().hasClass("truncate")) {
        $(this).parent().find(".content").css("max-height", $(this).parent().find(".content")[0].scrollHeight);
            $(this).children('a').text("Show Less");
        } else {
        $(this).parent().find(".content").css("max-height", "3.6em");
            $(this).children('a').text("Show More");
        }
  $(this).prev().toggleClass("truncate");

  });
});

.content {
    width:100px;
    overflow: hidden;
    white-space:normal;
    text-overflow: ellipsis;
    line-height: 1.2em;
    /* max-height = line-height (1.2) * lines max number (3) */
    max-height: 3.6em;
    /* fix problem when last visible word doesn't adjoin right side  */
    text-align: justify;
}
.txtcol{
  display:none;
  color:blue;
  cursor:pointer;
}
.maincontent{
  display:inline-block;
  vertical-align:top;
  border: 1px solid gray;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="maincontent">
<div class="content">
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
</div>
<div class="txtcol"><a>Show More</a></div>
</div>

<div class="maincontent">
<div class="content">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been Lorem Ipsum has been Lorem Ipsum has been Lorem Ipsum has been
</div>
<div class="txtcol"><a>Show More</a></div>
</div>

<div class="maincontent">
<div class="content">
Lorem Ipsum is simply
</div>
<div class="txtcol"><a>Show More</a></div>
</div>


问:
Dajax example "Multiply Machine!" not working. Help
Trying to learn Dajax, so decided to try out examples. But I am stuck with the "multiply" example. I have no clue what is wrong. Below is the code.

ajax.py:(its placed inside 'blog' app)

```<code>from dajax.core import Dajax
from dajaxice.core import dajaxice_functions

def multiply(request, a, b):
    dajax = Dajax()
    result = int(a) * int(b)
    dajax.assign('#result','value',str(result))
    return dajax.json()

dajaxice_functions.register(multiply)
</code>```

index.html:

```<code>{% load dajaxice_templatetags %}
<html>
    <head>

        <meta http-equiv="Content-type" content="text/html; charset=utf-8">
        <title>Blog</title>
        {% dajaxice_js_import %}
        <script type="text/javascript" charset="utf-8">
             function calculate(){
                Dajaxice.blog.multiply(Dajax.process,{'a':$('a').value,'b':$('b').value})
              }
        </script>
    </head>
    <body>

        <input type="text" name="a" value="5" id="a"> x
        <input type="text" name="b" value="6" id="b"> =
        <input type="text" name="result" value="" id="result">
        <input type="button" name="caculate" value="Let's Multiply!" id="caculate" onclick="calculate()">

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

答:
First of all you should install dajaxice properly. Then, if you are using Dajax you should install Dajax too.

Reading your code seems that dajaxice is correctly installed but you haven't installed Dajax or (at least) you have not linked your dajax-flavoured js.

If you are using Dajax (you are using Dajax) you should choose a framework between Prototype, jQuery, Dojo or mootols and add it to your page, also you need to link the framework.dajax.core.js to your page.

The rest of the installation seems to be already done.

ContentLicense: CC BY-SA 3.0

Body:
Trying to learn Dajax, so decided to try out examples. But I am stuck with the "multiply" example. I have no clue what is wrong. Below is the code.

ajax.py:(its placed inside 'blog' app)

from dajax.core import Dajax
from dajaxice.core import dajaxice_functions

def multiply(request, a, b):
    dajax = Dajax()
    result = int(a) * int(b)
    dajax.assign('#result','value',str(result))
    return dajax.json()

dajaxice_functions.register(multiply)

index.html:

{% load dajaxice_templatetags %}

        <meta http-equiv="Content-type" content="text/html; charset=utf-8">
        <title>Blog</title>
        {% dajaxice_js_import %}

        <input type="text" name="a" value="5" id="a"> x
        <input type="text" name="b" value="6" id="b"> =
        <input type="text" name="result" value="" id="result">
        <input type="button" name="caculate" value="Let's Multiply!" id="caculate" onclick="calculate()">


问:
Class 'Maatwebsite\Excel\Excel' not found
my composer.json:

```<code>    ...
    "maatwebsite/excel": "^3.0",
    ...
</code>```

I can run my project on localhost but when I upload on server I got this error message:

```<code>Class 'Maatwebsite\Excel\Excel' not found
</code>```

my laravel version:

```<code>Laravel Framework 5.5.40
</code>```

my public directory:

public_html/public/index.php

```<code><?php

/**
 * Laravel - A PHP Framework For Web Artisans
 *
 * @package  Laravel
 * @author   Taylor Otwell <taylor@laravel.com>
 */

/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader for
| our application. We just need to utilize it! We'll simply require it
| into the script here so that we don't have to worry about manual
| loading any of our classes later on. It feels great to relax.
|
*/

require __DIR__.'/../bootstrap/autoload.php';
/*
|--------------------------------------------------------------------------
| Turn On The Lights
|--------------------------------------------------------------------------
|
| We need to illuminate PHP development, so let us turn on the lights.
| This bootstraps the framework and gets it ready for use, then it
| will load up this application so that we can run it and send
| the responses back to the browser and delight our users.
|
*/

$app = require_once __DIR__.'/../bootstrap/app.php';

/*
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
|
| Once we have the application, we can handle the incoming request
| through the kernel, and send the associated response back to
| the client's browser allowing them to enjoy the creative
| and wonderful application we have prepared for them.
|
*/

$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);

$response = $kernel->handle(
    $request = Illuminate\Http\Request::capture()
);

$response->send();

$kernel->terminate($request, $response);
</code>```

my website:

http://alsatmarketing.com/

updated

I get this error after run composer require maatwebsite/excel:^3.0:

```<code> Problem 1
    - Installation request for maatwebsite/excel 3.0 -> satisfiable by maatwebsite/excel[3.0.0].
    - Conclusion: remove laravel/framework v5.5.40
    - Conclusion: don't install laravel/framework v5.5.40
    - maatwebsite/excel 3.0.0 requires illuminate/support ^5.6 -> satisfiable by illuminate/support[v5.6.0, v5.6.1, v5.6.10, v5.6.11, v5.6.12, v5.6.13, v5.6.14, v5.6.15, v5.6.16, v5.6.17,
v5.6.19, v5.6.2, v5.6.20, v5.6.21, v5.6.22, v5.6.23, v5.6.3, v5.6.4, v5.6.5, v5.6.6, v5.6.7, v5.6.8, v5.6.9].
    - don't install illuminate/support v5.6.4|don't install laravel/framework v5.5.40
    - don't install illuminate/support v5.6.5|don't install laravel/framework v5.5.40
    - don't install illuminate/support v5.6.6|don't install laravel/framework v5.5.40
    - don't install illuminate/support v5.6.7|don't install laravel/framework v5.5.40
    - don't install illuminate/support v5.6.0|don't install laravel/framework v5.5.40
    - don't install illuminate/support v5.6.1|don't install laravel/framework v5.5.40
    - illuminate/support v5.6.10 conflicts with laravel/framework[v5.5.40].
    - illuminate/support v5.6.11 conflicts with laravel/framework[v5.5.40].
    - illuminate/support v5.6.12 conflicts with laravel/framework[v5.5.40].
    - illuminate/support v5.6.13 conflicts with laravel/framework[v5.5.40].
    - illuminate/support v5.6.14 conflicts with laravel/framework[v5.5.40].
    - illuminate/support v5.6.15 conflicts with laravel/framework[v5.5.40].
    - illuminate/support v5.6.16 conflicts with laravel/framework[v5.5.40].
    - illuminate/support v5.6.17 conflicts with laravel/framework[v5.5.40].
    - illuminate/support v5.6.19 conflicts with laravel/framework[v5.5.40].
    - don't install illuminate/support v5.6.2|don't install laravel/framework v5.5.40
    - illuminate/support v5.6.20 conflicts with laravel/framework[v5.5.40].
    - illuminate/support v5.6.21 conflicts with laravel/framework[v5.5.40].
    - illuminate/support v5.6.22 conflicts with laravel/framework[v5.5.40].
    - illuminate/support v5.6.23 conflicts with laravel/framework[v5.5.40].
    - don't install illuminate/support v5.6.3|don't install laravel/framework v5.5.40
    - illuminate/support v5.6.8 conflicts with laravel/framework[v5.5.40].
    - illuminate/support v5.6.9 conflicts with laravel/framework[v5.5.40].
    - Installation request for laravel/framework (locked at v5.5.40, required as 5.5.*) -> satisfiable by laravel/framework[v5.5.40].

Installation failed, reverting ./composer.json to its original content.
</code>```

答:
If you use Laravel 5.4, please run this command for install composer</p>

```<code>composer require maatwebsite/excel:~2.1
</code>```

Body:
my composer.json:

    ...
    "maatwebsite/excel": "^3.0",
    ...

I can run my project on localhost but when I upload on server I got this error message:

Class 'Maatwebsite\Excel\Excel' not found

my laravel version:

Laravel Framework 5.5.40

my public directory:

public_html/public/index.php

<?php

/**
 * Laravel - A PHP Framework For Web Artisans
 *
 * @package  Laravel
 * @author   Taylor Otwell <taylor@laravel.com>
 */

/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader for
| our application. We just need to utilize it! We'll simply require it
| into the script here so that we don't have to worry about manual
| loading any of our classes later on. It feels great to relax.
|
*/

require __DIR__.'/../bootstrap/autoload.php';
/*
|--------------------------------------------------------------------------
| Turn On The Lights
|--------------------------------------------------------------------------
|
| We need to illuminate PHP development, so let us turn on the lights.
| This bootstraps the framework and gets it ready for use, then it
| will load up this application so that we can run it and send
| the responses back to the browser and delight our users.
|
*/

$app = require_once __DIR__.'/../bootstrap/app.php';

/*
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
|
| Once we have the application, we can handle the incoming request
| through the kernel, and send the associated response back to
| the client's browser allowing them to enjoy the creative
| and wonderful application we have prepared for them.
|
*/

$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);

$response = $kernel->handle(
    $request = Illuminate\Http\Request::capture()
);

$response->send();

$kernel->terminate($request, $response);

my website:

http://alsatmarketing.com/

updated

I get this error after run composer require maatwebsite/excel:^3.0:

 Problem 1
    - Installation request for maatwebsite/excel 3.0 -> satisfiable by maatwebsite/excel[3.0.0].
    - Conclusion: remove laravel/framework v5.5.40
    - Conclusion: don't install laravel/framework v5.5.40
    - maatwebsite/excel 3.0.0 requires illuminate/support ^5.6 -> satisfiable by illuminate/support[v5.6.0, v5.6.1, v5.6.10, v5.6.11, v5.6.12, v5.6.13, v5.6.14, v5.6.15, v5.6.16, v5.6.17,
v5.6.19, v5.6.2, v5.6.20, v5.6.21, v5.6.22, v5.6.23, v5.6.3, v5.6.4, v5.6.5, v5.6.6, v5.6.7, v5.6.8, v5.6.9].
    - don't install illuminate/support v5.6.4|don't install laravel/framework v5.5.40
    - don't install illuminate/support v5.6.5|don't install laravel/framework v5.5.40
    - don't install illuminate/support v5.6.6|don't install laravel/framework v5.5.40
    - don't install illuminate/support v5.6.7|don't install laravel/framework v5.5.40
    - don't install illuminate/support v5.6.0|don't install laravel/framework v5.5.40
    - don't install illuminate/support v5.6.1|don't install laravel/framework v5.5.40
    - illuminate/support v5.6.10 conflicts with laravel/framework[v5.5.40].
    - illuminate/support v5.6.11 conflicts with laravel/framework[v5.5.40].
    - illuminate/support v5.6.12 conflicts with laravel/framework[v5.5.40].
    - illuminate/support v5.6.13 conflicts with laravel/framework[v5.5.40].
    - illuminate/support v5.6.14 conflicts with laravel/framework[v5.5.40].
    - illuminate/support v5.6.15 conflicts with laravel/framework[v5.5.40].
    - illuminate/support v5.6.16 conflicts with laravel/framework[v5.5.40].
    - illuminate/support v5.6.17 conflicts with laravel/framework[v5.5.40].
    - illuminate/support v5.6.19 conflicts with laravel/framework[v5.5.40].
    - don't install illuminate/support v5.6.2|don't install laravel/framework v5.5.40
    - illuminate/support v5.6.20 conflicts with laravel/framework[v5.5.40].
    - illuminate/support v5.6.21 conflicts with laravel/framework[v5.5.40].
    - illuminate/support v5.6.22 conflicts with laravel/framework[v5.5.40].
    - illuminate/support v5.6.23 conflicts with laravel/framework[v5.5.40].
    - don't install illuminate/support v5.6.3|don't install laravel/framework v5.5.40
    - illuminate/support v5.6.8 conflicts with laravel/framework[v5.5.40].
    - illuminate/support v5.6.9 conflicts with laravel/framework[v5.5.40].
    - Installation request for laravel/framework (locked at v5.5.40, required as 5.5.*) -> satisfiable by laravel/framework[v5.5.40].

Installation failed, reverting ./composer.json to its original content.

Body:
If you use Laravel 5.4, please run this command for install composer

composer require maatwebsite/excel:~2.1


问:
IntelliJ continues code in REST method after stopping
I have a spring boot backend. I am using IntelliJ. I am debugging my rest method.

I have noticed the following weird behaviour:

When I am debugging and I am e.g. at line 22. When I now stop the process (by clicking the red stop button in IntelliJ), the application stops, but I noticed that the the rest of the method is still executed.

Is that the normal behaviour?

答:
OK the behavious is normal. The solution is:

Please enable "Kill the debug process immediately" option in "Settings (Preferences)| Build, Execution, Deployment | Debugger"


问:
Where can i download sample siebel CRM application to practice automation testing
I want to create a POC of automation testing for Siebel CRM application.
Can anybody suggest any sample CRM application or refere a place from where i can download Siebel application.

Also it will be helpful if anybody recommend  any automation testing tool to perform automation testing on siebel CRM based application.

Thanks,
Bibek

答:
the fastest option is to use the Siebel 20.x Sample images on Oracle Cloud Infrastructure. This will give you a current 20.x Siebel Server instance with the sample (Oracle) database. https://cloudmarketplace.oracle.com/marketplace/en_US/listing/75325155

Running the Jenkins-driven setup completes in approximately 40 minutes. Compared to installing everything on your own which takes 1 day at minimum (if you know what you are doing).

Test Automation is built in since Siebel IP 17, allowing in-client recording as well as unit and batch playback.

(see Test Automation Guide in Siebel Bookshelf https://docs.oracle.com/cd/F26413_05/books/TestGuide/index.html )

@lex


问:
PrivateChannel 403 error Laravel Echo Pusher Laravel Websockets local setup
I am getting a 403 on broadcasting/auth route.

I am using Laravel websockets package for web sockets and I have the below setup

```<code>- Backend Laravel server ( on port 8000 )
- Laravel Websockets Server ( laravel is running on 8001 and websocket server on 6001 )
- Standalone Ionic React app ( on port 8100)
</code>```

Now everything works when I am trying Public Channel but when I try Private Channel it fails.

in the above screenshot of Laravel sockets dashboard I can see connection made as this is the same socketId which went with the request.

I am using Laravel Sanctum for Authentication.

PFB :- my client side code

```<code>const headers = {
    'Content-Type': 'application/json',
    Authorization: window.localStorage.getItem('token')
      ? `Bearer ${window.localStorage.getItem('token')}`
      : '',
    'Access-Control-Allow-Credentials': true,
  };
  const options = {
    broadcaster: 'pusher',
    key: 'abcsock',
    authEndpoint: 'http://localhost:8001/api/broadcasting/auth',
    authorizer: (channel, options) => {
      return {
        authorize: (socketId, callback) => {
          axios
            .post(
              'http://localhost:8001/api/broadcasting/auth',
              {
                socket_id: socketId,
                channel_name: channel.name,
              },
              { headers, withCredentials: true }
            )
            .then((response) => {
              callback(false, response.data);
            })
            .catch((error) => {
              callback(true, error);
            });
        },
      };
    },
    wsHost: '127.0.0.1',
    wsPort: 6001,
    encrypted: true,
    disableStats: true,
    enabledTransports: ['ws', 'wss'],
    forceTLS: false,
  };
</code>```

Code from Laravel Websockets Server

api.php file

```<code>use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Broadcast;

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Broadcast::routes(['middleware' => ['auth:sanctum']]);
</code>```

BroadcastServiceProvider.php

```<code>namespace App\Providers;

use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\ServiceProvider;

class BroadcastServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Broadcast::routes(['middleware' => ['auth:sanctum']]);

        require base_path('routes/channels.php');
    }
}
</code>```

NewNotification.php

```<code><?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\BroadcastMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Broadcasting\PrivateChannel;

use App\AppNotification;
use App\User;

class NewNotification extends Notification
{
    use Queueable;

    public $notification;
    public $user;
    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct(AppNotification $notification, User $user)
    {
        $this->notification = $notification;
        $this->user = $user;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['database', 'broadcast'];
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        $notification = $this->notification;
        return [
            'id' => $notification->id,
            'title' => $notification->title,
            'description' => $notification->description,
            'button_text' => $notification->button_text,
            'is_read' => $notification->is_read,
            'created_at' => $notification->created_at,
            [
                'notification_for' => $notification->notifiable
            ]
        ];
    }

    public function toBroadcast($notifiable)
    {
        return new BroadcastMessage($this->toArray($notifiable));
    }

    public function broadcastOn()
    {
        return new PrivateChannel('Notifications.' . $this->user->id);
    }
}
</code>```

channels.php

```<code><?php

use Illuminate\Support\Facades\Broadcast;

Broadcast::channel('Notifications.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
}, ['guards' => ['sanctum']]);
</code>```

I have attached whatever I felt was sufficient to explain the issue and for you to troubleshoot but if you need anything more please ask.

Any help will be appreciated

答:
Have you added authentication for your channels.php? Please refer here:
https://laravel.com/docs/7.x/broadcasting#defining-authorization-routes
What does it look like?

I think you are doing everything correctly but you have not authorized your routes.

Body:
I am getting a 403 on broadcasting/auth route.

I am using Laravel websockets package for web sockets and I have the below setup

- Backend Laravel server ( on port 8000 )
- Laravel Websockets Server ( laravel is running on 8001 and websocket server on 6001 )
- Standalone Ionic React app ( on port 8100)

Now everything works when I am trying Public Channel but when I try Private Channel it fails.

in the above screenshot of Laravel sockets dashboard I can see connection made as this is the same socketId which went with the request.

I am using Laravel Sanctum for Authentication.

PFB :- my client side code

const headers = {
    'Content-Type': 'application/json',
    Authorization: window.localStorage.getItem('token')
      ? `Bearer ${window.localStorage.getItem('token')}`
      : '',
    'Access-Control-Allow-Credentials': true,
  };
  const options = {
    broadcaster: 'pusher',
    key: 'abcsock',
    authEndpoint: 'http://localhost:8001/api/broadcasting/auth',
    authorizer: (channel, options) => {
      return {
        authorize: (socketId, callback) => {
          axios
            .post(
              'http://localhost:8001/api/broadcasting/auth',
              {
                socket_id: socketId,
                channel_name: channel.name,
              },
              { headers, withCredentials: true }
            )
            .then((response) => {
              callback(false, response.data);
            })
            .catch((error) => {
              callback(true, error);
            });
        },
      };
    },
    wsHost: '127.0.0.1',
    wsPort: 6001,
    encrypted: true,
    disableStats: true,
    enabledTransports: ['ws', 'wss'],
    forceTLS: false,
  };

Code from Laravel Websockets Server

api.php file

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Broadcast;

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Broadcast::routes(['middleware' => ['auth:sanctum']]);

BroadcastServiceProvider.php

namespace App\Providers;

use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\ServiceProvider;

class BroadcastServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Broadcast::routes(['middleware' => ['auth:sanctum']]);

        require base_path('routes/channels.php');
    }
}

NewNotification.php

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\BroadcastMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Broadcasting\PrivateChannel;

use App\AppNotification;
use App\User;

class NewNotification extends Notification
{
    use Queueable;

    public $notification;
    public $user;
    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct(AppNotification $notification, User $user)
    {
        $this->notification = $notification;
        $this->user = $user;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['database', 'broadcast'];
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        $notification = $this->notification;
        return [
            'id' => $notification->id,
            'title' => $notification->title,
            'description' => $notification->description,
            'button_text' => $notification->button_text,
            'is_read' => $notification->is_read,
            'created_at' => $notification->created_at,
            [
                'notification_for' => $notification->notifiable
            ]
        ];
    }

    public function toBroadcast($notifiable)
    {
        return new BroadcastMessage($this->toArray($notifiable));
    }

    public function broadcastOn()
    {
        return new PrivateChannel('Notifications.' . $this->user->id);
    }
}

channels.php

<?php

use Illuminate\Support\Facades\Broadcast;

Broadcast::channel('Notifications.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
}, ['guards' => ['sanctum']]);

I have attached whatever I felt was sufficient to explain the issue and for you to troubleshoot but if you need anything more please ask.

Any help will be appreciated


问:
How to push values correctly into an array of objects
I want to push some of the values of the following enum

```<code>enum p {
  XDR = 1,
    PT1M = 2,
    PT1M_ = 2,
    PT5M = 3,
    PT5M_ = 3,
    PT15M = 4,
    PT15M_ = 4,
    PT1H = 5,
    PT1H_ = 5,
    P1D = 6,
    P1D_ = 6,
    P7D = 7,
    P1W = 7,
    P1M = 8,
}
</code>```

using this function

```<code>private getGMap(): view[] {
  const w = View.getView().getW();
  return widgets.reduce((g, widget) => {
    const granularitySymbol = QueryProcessorService.getWidgetApplied(widget);
    g.push([granularitySymbol, Priority[gSymbol]]);
    return g;
  }, []);
}
</code>```

where view is this interface

```<code>interface view {
  gSymbol: string;
  priority: number;
}
</code>```

I think I am pushing the variables the wrong way. Could someone have a look and help me?

答:
```<code>private getGMap(): view[] {
        const w = View.getView().getW();
        return widgets.reduce((g, widget) => {
          const granularitySymbol = QueryProcessorService.getWidgetApplied(widget);
          g.push([{gSymbol: granularitySymbol, priority: Priority[granularitySymbol]}]);
          return g;
        }, []);

      }
</code>```

Body:
I want to push some of the values of the following enum

enum p {
  XDR = 1,
    PT1M = 2,
    PT1M_ = 2,
    PT5M = 3,
    PT5M_ = 3,
    PT15M = 4,
    PT15M_ = 4,
    PT1H = 5,
    PT1H_ = 5,
    P1D = 6,
    P1D_ = 6,
    P7D = 7,
    P1W = 7,
    P1M = 8,
}

using this function

private getGMap(): view[] {
  const w = View.getView().getW();
  return widgets.reduce((g, widget) => {
    const granularitySymbol = QueryProcessorService.getWidgetApplied(widget);
    g.push([granularitySymbol, Priority[gSymbol]]);
    return g;
  }, []);
}

where view is this interface

interface view {
  gSymbol: string;
  priority: number;
}

I think I am pushing the variables the wrong way. Could someone have a look and help me?


问:
Unable to import python module from subdirectory
My structrue

```<code>/api/__init__.py
/api/api.py
/database_access/__init__.py
/database_access/databaseaccess.py
/database_access/models/__init__.py
/database_access/models/manufacturer.py
</code>```

manufacturer.py

```<code>class Manufacturer:
    # methods here
</code>```

And databaseaccess.py

```<code>import pymongo
from models import manufacturer # <-- unable to import 'models'

myclient = pymongo.MongoClient("mongodb://localhost:27017/")

computer_parts_database = myclient["computer_parts"]
part_types = computer_parts_database["manufacturers"]
parts = computer_parts_database["parts"]

class DatabaseAccess:
    manufacturers = computer_parts_database["manufacturers"]

da = DatabaseAccess()
#mf = Manufacturer.init2(1, "Advanced Micro Devices", "AMD")
#da.manufacturers.insert_one(mf.toObject())
</code>```

I'm unable to get the manufacturer module to load. The same happens with import models and import models.manufacturer

I get the same problem in api.py, if I want to access the databaseaccess module I'm not sure how

答: Something which I hadn't noticed was I had an __init__.py at the root. I removed this and the errors went away

Body:
My structrue

/api/__init__.py
/api/api.py
/database_access/__init__.py
/database_access/databaseaccess.py
/database_access/models/__init__.py
/database_access/models/manufacturer.py

manufacturer.py

class Manufacturer:
    # methods here

And databaseaccess.py

import pymongo
from models import manufacturer # <-- unable to import 'models'

myclient = pymongo.MongoClient("mongodb://localhost:27017/")

computer_parts_database = myclient["computer_parts"]
part_types = computer_parts_database["manufacturers"]
parts = computer_parts_database["parts"]

class DatabaseAccess:
    manufacturers = computer_parts_database["manufacturers"]

da = DatabaseAccess()
#mf = Manufacturer.init2(1, "Advanced Micro Devices", "AMD")
#da.manufacturers.insert_one(mf.toObject())

I'm unable to get the manufacturer module to load. The same happens with import models and import models.manufacturer

I get the same problem in api.py, if I want to access the databaseaccess module I'm not sure how


问:
jQuery: Editing user inserted DOM elements
I want to add html items (text and buttons inside a div) to the DOM and each item be editable or deletable.  I used jquery to do this as follows.

```<code><div id="ak"></div>
<input type="text" name="lname" id="itext" size="60"/><br/>
<button id="but">Add Item</button>
<div id="test"></div>

$("#but").click(function(){
        var istring = $("#itext").val();
        $("#ak").append("<div class=\"item\"><p>"+istring+"<button class=\"editable\">Edit</button><button class=\"deletable\">Delete</button></p></div>");
        $("#itext").val("");
});

$(".deletable").click(function(){
    alert("Alert !!");
});
</code>```

However, when I pressed the delete button in each item nothing happens (should give an alert).  I feel something is very wrong.  Any help is appreciated.

答:
I'd argue that it's one of jQuery's shining gems, these event handlers on dynamically-created HTML elements. It's a perfectly valid topic, but I still wish we had, like, a quarter for everyone who asked why event handlers were not working on dynamically-created HTML elements. :D

And in every such question, I'd argue that you use .delegate() instead of .live(), especially since (at least in your sample code) you know exactly from the get-go where you're inserting your elements.

```<code>$('#ak').delegate('.deletable', 'click', function (e) {
    // do something
});
</code>```

No sense in going for .live() and popping up a global handler in a global context.

If you seriously don't want to go down the live / delegate path, you could always snap in your handlers as you're creating the element as well.

```<code>// creating a button with a click event handler
$('<button/>', {
    id : 'foo',
    class : 'deletable',
    click : function (e) {
        // do something
    }
});
</code>```

... then you can use that and append that somewhere. You may find that this approach, when integrated in your code, might be more viable for you.

Body:
I want to add html items (text and buttons inside a div) to the DOM and each item be editable or deletable.  I used jquery to do this as follows.

<input type="text" name="lname" id="itext" size="60"/>

<button id="but">Add Item</button>

$("#but").click(function(){
        var istring = $("#itext").val();
        $("#ak").append("

"+istring+"<button class=\"editable\">Edit</button><button class=\"deletable\">Delete</button>

");
        $("#itext").val("");
});

$(".deletable").click(function(){
    alert("Alert !!");
});

However, when I pressed the delete button in each item nothing happens (should give an alert).  I feel something is very wrong.  Any help is appreciated.

Body:
I'd argue that it's one of jQuery's shining gems, these event handlers on dynamically-created HTML elements. It's a perfectly valid topic, but I still wish we had, like, a quarter for everyone who asked why event handlers were not working on dynamically-created HTML elements. :D

And in every such question, I'd argue that you use .delegate() instead of .live(), especially since (at least in your sample code) you know exactly from the get-go where you're inserting your elements.

$('#ak').delegate('.deletable', 'click', function (e) {
    // do something
});

No sense in going for .live() and popping up a global handler in a global context.

If you seriously don't want to go down the live / delegate path, you could always snap in your handlers as you're creating the element as well.

// creating a button with a click event handler
$('<button/>', {
    id : 'foo',
    class : 'deletable',
    click : function (e) {
        // do something
    }
});

... then you can use that and append that somewhere. You may find that this approach, when integrated in your code, might be more viable for you.


问:
Postman in circleci - Error calling workflow: 'workflow'
Trying to run simple postman API calls but getting

```<code>Error calling workflow: 'workflow'
</code>```

My .circleci/config.yml is

```<code>$ cat .circleci/config.yml
version: 2.1
orbs:
  newman: postman/newman@0.0.2
jobs:
  newman-collection-run:
    executor: newman/postman-newman-docker
    steps:
      - checkout
      - newman/newman-run:
          collection: ./collection.json
</code>```

collection.json is at the root of the project and is the export from postman.

I am using the example from

https://circleci.com/orbs/registry/orb/postman/newman

which shows:

The "workflow" reference comes from the original example on the circleci site (not with newman) when I start building on this branch and I've replaced the config file contents in the branch and pushed it so not sure why this reference is coming up ?

Here is that original screen:

which I change to be:

and

答:
I believe the original config.yml file is missing the build: step, which comes in before the executor: line.

```<code>version: 2.1
orbs:
  newman: postman/newman@0.0.2
jobs:
  build:
    executor: newman/postman-newman-docker
    steps:
      - checkout
      - newman/newman-run:
          collection: ./collection.json
</code>```

Body:
Trying to run simple postman API calls but getting

Error calling workflow: 'workflow'

My .circleci/config.yml is

$ cat .circleci/config.yml
version: 2.1
orbs:
  newman: postman/newman@0.0.2
jobs:
  newman-collection-run:
    executor: newman/postman-newman-docker
    steps:
      - checkout
      - newman/newman-run:
          collection: ./collection.json

collection.json is at the root of the project and is the export from postman.

I am using the example from

https://circleci.com/orbs/registry/orb/postman/newman

which shows:

The "workflow" reference comes from the original example on the circleci site (not with newman) when I start building on this branch and I've replaced the config file contents in the branch and pushed it so not sure why this reference is coming up ?

Here is that original screen:

which I change to be:

and

Body:
I believe the original config.yml file is missing the build: step, which comes in before the executor: line.

version: 2.1
orbs:
  newman: postman/newman@0.0.2
jobs:
  build:
    executor: newman/postman-newman-docker
    steps:
      - checkout
      - newman/newman-run:
          collection: ./collection.json


问:
Trying to code 'rock paper scissors' game with tkinter. But my coding doesn't give what i want, and no error has occured
So here's what I just did.

```<code>from tkinter import *
import random
window = Tk()

button_list=['Rock', 'Paper', 'Scissors']

RockImage=PhotoImage(file="rock.png")
PaperImage=PhotoImage(file="paper.png")
ScissorImage=PhotoImage(file="scissors.png")

  def update_image(num,Img):

     if num==1:
         inputLabel_1=Label(window, image=Img)
         inputLabel_1.grid(row=0, column=0)

    elif num==2:
        inputLabel_2=Label(window, image=Img)
        inputLabel_2.grid(row=0, column=2)

Mid_ResultLabel=Label(window, text=' ', fg='green')
ResultLabel=Label(window, text=' ',fg='green')
Mid_ResultLabel.grid(row=0, column=1)
ResultLabel.grid(row=1, column=1)

def game(choice):
    opponent = random.randint(1,3)
    if opponent == 1:
        update_image(2,RockImage)
    elif opponent == 2:
        update_image(2,PaperImage)
    elif opponent ==3:
        update_image(2,ScissorImage)

    if choice == 'Rock':
        update_image(1,RockImage)
        if opponent == 1:
            Mid_ResultLabel = Label(window, width=10, text='======')
            ResultLabel = Label(window, width=10, text='DRAW!',fg='green')
        elif opponent == 2:
            Mid_ResultLabel = Label(window, width=10, text='<<<<<<')
            ResultLabel = Label(window, width=10, text='LOSE...')
        elif opponent ==3:
            Mid_ResultLabel = Label(window, width=10, text='>>>>>>')
            ResultLabel = Label(window, width=10, text='YOU WON!')

    elif choice == 'Paper':
        update_image(1,PaperImage)
        if opponent == 1:
            Mid_ResultLabel = Label(window, width=10, text='>>>>>>')
            ResultLabel = Label(window, width=10, text='YOU WON!')
        elif opponent == 2:
            Mid_ResultLabel = Label(window, width=10, text='======')
            ResultLabel = Label(window, width=10, text='DRAW!')
        elif opponent == 3:
            Mid_ResultLabel = Label(window, width=10, text='<<<<<<')
            ResultLabel = Label(window, width=10, text='LOSE...')

    elif choice == 'Scissors':
        update_image(1,ScissorImage)
        if opponent == 1:
            Mid_ResultLabel = Label(window, width=10, text='<<<<<<')
            ResultLabel = Label(window, width=10, text='LOSE...')
        elif opponent == 2:
            Mid_ResultLabel = Label(window, width=10, text='>>>>>>')
            ResultLabel = Label(window, width=10, text='YOU WON!')
        elif opponent == 3 :
            Mid_ResultLabel = Label(window, width=10, text='======')
            ResultLabel = Label(window, width=10, text='DRAW!')

        Mid_ResultLabel.grid(row=0, column=1)
        ResultLabel.grid(row=1, column=1)

i=0
for button_text in button_list:
    def click(t=i):
            game(t)
    Button(window, text=button_text, width=30, command = click).grid(row=3, column = i)
    i+=1

window.mainloop()
</code>```

I can't use canvas in this thing.. just allowed to use Labels.
Error does not appear when I run this. So I can't figure it out what is wrong.

What should I edit on here? Where did I made mistakes?

rock image

paper image

scissors image

答:
For a start, you pass to the game function an integer not a string, so when you check to see if it is rock, paper or scissors it never returns a value. This means you should change your code to read:

if choice == 'Rock': -> if choice == 0:
elif choice == 'Paper': -> elif choice == 1:
elif choice == 'Scissors': -> elif choice == 2:
```

<p>Furthermore, instead of rebuilding the labels you can use <code>label.configure</code> to change the text simply:</p>

<pre class="lang-py prettyprint-override"><code>if choice == 0:
    update_image(1,RockImage)
    if opponent == 1:
        Mid_ResultLabel.configure(text='======')
        ResultLabel.configure(text='DRAW!')
    elif opponent == 2:
        Mid_ResultLabel.configure(text='<<<<<<')
        ResultLabel.configure(text='LOSE...')
    elif opponent ==3:
        Mid_ResultLabel.configure(text=">>>>>>")
        ResultLabel.configure(text='YOU WON!')

elif choice == 1:
    update_image(1,PaperImage)
    if opponent == 1:
        Mid_ResultLabel.configure(text=">>>>>>")
        ResultLabel.configure(text='YOU WON!')
    elif opponent == 2:
        Mid_ResultLabel.configure(text='======')
        ResultLabel.configure(text='DRAW!')
    elif opponent == 3:
        Mid_ResultLabel.configure(text='<<<<<<')
        ResultLabel.configure(text='LOSE...')

elif choice == 2:
    update_image(1,ScissorImage)
    if opponent == 1:
        Mid_ResultLabel.configure(text='<<<<<<')
        ResultLabel.configure(text='LOSE...')
    elif opponent == 2:
        Mid_ResultLabel.configure(text=">>>>>>")
        ResultLabel.configure(text='YOU WON!')
    elif opponent == 3 :
        Mid_ResultLabel.configure(text='======')
        ResultLabel.configure(text='DRAW!')
</code>```

There are more improvements you can also make to your code; however, these changes will make your code working!

Overall the code changes made

from tkinter import *
import random
window = Tk()

button_list = ['Rock', 'Paper', 'Scissors']

RockImage = PhotoImage(file="rock.png")
PaperImage = PhotoImage(file="paper.png")
ScissorImage = PhotoImage(file="scissors.png")

def update_image(num, Img):
    if num == 1:
         inputLabel_1 = Label(window, image=Img)
         inputLabel_1.grid(row=0, column=0)
    elif num==2:
        inputLabel_2=Label(window, image=Img)
        inputLabel_2.grid(row=0, column=2)

Mid_ResultLabel=Label(window, text=' ', fg='green')
ResultLabel=Label(window, text=' ',fg='green')
Mid_ResultLabel.grid(row=0, column=1)
ResultLabel.grid(row=1, column=1)

def game(choice):
    print("GAME FUNCTION")
    opponent = random.randint(1,3)
    if opponent == 1:
        update_image(2,RockImage)
    elif opponent == 2:
        update_image(2,PaperImage)
    elif opponent ==3:
        update_image(2,ScissorImage)

    if choice == 0:
        update_image(1,RockImage)
        if opponent == 1:
            Mid_ResultLabel.configure(text='======')
            ResultLabel.configure(text='DRAW!')
        elif opponent == 2:
            Mid_ResultLabel.configure(text='<<<<<<')
            ResultLabel.configure(text='LOSE...')
        elif opponent ==3:
            Mid_ResultLabel.configure(text=">>>>>>")
            ResultLabel.configure(text='YOU WON!')

    elif choice == 1:
        update_image(1,PaperImage)
        if opponent == 1:
            Mid_ResultLabel.configure(text=">>>>>>")
            ResultLabel.configure(text='YOU WON!')
        elif opponent == 2:
            Mid_ResultLabel.configure(text='======')
            ResultLabel.configure(text='DRAW!')
        elif opponent == 3:
            Mid_ResultLabel.configure(text='<<<<<<')
            ResultLabel.configure(text='LOSE...')

    elif choice == 2:
        update_image(1,ScissorImage)
        if opponent == 1:
            Mid_ResultLabel.configure(text='<<<<<<')
            ResultLabel.configure(text='LOSE...')
        elif opponent == 2:
            Mid_ResultLabel.configure(text=">>>>>>")
            ResultLabel.configure(text='YOU WON!')
        elif opponent == 3 :
            Mid_ResultLabel.configure(text='======')
            ResultLabel.configure(text='DRAW!')

i=0
for button_text in button_list:
    def click(t=i):
            game(t)
    Button(window, text=button_text, width=30, command = click).grid(row=3, column = i)
    i+=1

window.mainloop()
```

<h1>Other Changes you can make</h1>

<p>You can also improve your code to be more ledgible in some other ways. Arguably the most important would be to move your code to Object Orientated Programming, I find this guide to be rather good!</p>

<p>Another change you can make is to change your <code>for loop</code>, that creates the buttons, to use Python's enumerate function and lambda:</p>

<pre class="lang-py prettyprint-override"><code>for i, button_text in enumerate(button_list):
    Button(window, text=button_text, width=30, command = lambda t=i: game(t)).grid(row=3, column = i)
</code>```

As you can see, that one code change can improve the look of your code!

Hope this helps,

James

Body:
So here's what I just did.

from tkinter import *
import random
window = Tk()

button_list=['Rock', 'Paper', 'Scissors']

RockImage=PhotoImage(file="rock.png")
PaperImage=PhotoImage(file="paper.png")
ScissorImage=PhotoImage(file="scissors.png")

  def update_image(num,Img):

     if num==1:
         inputLabel_1=Label(window, image=Img)
         inputLabel_1.grid(row=0, column=0)

    elif num==2:
        inputLabel_2=Label(window, image=Img)
        inputLabel_2.grid(row=0, column=2)

Mid_ResultLabel=Label(window, text=' ', fg='green')
ResultLabel=Label(window, text=' ',fg='green')
Mid_ResultLabel.grid(row=0, column=1)
ResultLabel.grid(row=1, column=1)

def game(choice):
    opponent = random.randint(1,3)
    if opponent == 1:
        update_image(2,RockImage)
    elif opponent == 2:
        update_image(2,PaperImage)
    elif opponent ==3:
        update_image(2,ScissorImage)

    if choice == 'Rock':
        update_image(1,RockImage)
        if opponent == 1:
            Mid_ResultLabel = Label(window, width=10, text='======')
            ResultLabel = Label(window, width=10, text='DRAW!',fg='green')
        elif opponent == 2:
            Mid_ResultLabel = Label(window, width=10, text='<<<<<<')
            ResultLabel = Label(window, width=10, text='LOSE...')
        elif opponent ==3:
            Mid_ResultLabel = Label(window, width=10, text='>>>>>>')
            ResultLabel = Label(window, width=10, text='YOU WON!')

    elif choice == 'Paper':
        update_image(1,PaperImage)
        if opponent == 1:
            Mid_ResultLabel = Label(window, width=10, text='>>>>>>')
            ResultLabel = Label(window, width=10, text='YOU WON!')
        elif opponent == 2:
            Mid_ResultLabel = Label(window, width=10, text='======')
            ResultLabel = Label(window, width=10, text='DRAW!')
        elif opponent == 3:
            Mid_ResultLabel = Label(window, width=10, text='<<<<<<')
            ResultLabel = Label(window, width=10, text='LOSE...')

    elif choice == 'Scissors':
        update_image(1,ScissorImage)
        if opponent == 1:
            Mid_ResultLabel = Label(window, width=10, text='<<<<<<')
            ResultLabel = Label(window, width=10, text='LOSE...')
        elif opponent == 2:
            Mid_ResultLabel = Label(window, width=10, text='>>>>>>')
            ResultLabel = Label(window, width=10, text='YOU WON!')
        elif opponent == 3 :
            Mid_ResultLabel = Label(window, width=10, text='======')
            ResultLabel = Label(window, width=10, text='DRAW!')

        Mid_ResultLabel.grid(row=0, column=1)
        ResultLabel.grid(row=1, column=1)

i=0
for button_text in button_list:
    def click(t=i):
            game(t)
    Button(window, text=button_text, width=30, command = click).grid(row=3, column = i)
    i+=1

window.mainloop()

I can't use canvas in this thing.. just allowed to use Labels.
Error does not appear when I run this. So I can't figure it out what is wrong.

What should I edit on here? Where did I made mistakes?

rock image

paper image

scissors image

Body:
For a start, you pass to the game function an integer not a string, so when you check to see if it is rock, paper or scissors it never returns a value. This means you should change your code to read:

if choice == 'Rock': -> if choice == 0:
elif choice == 'Paper': -> elif choice == 1:
elif choice == 'Scissors': -> elif choice == 2:

Furthermore, instead of rebuilding the labels you can use label.configure to change the text simply:

if choice == 0:
    update_image(1,RockImage)
    if opponent == 1:
        Mid_ResultLabel.configure(text='======')
        ResultLabel.configure(text='DRAW!')
    elif opponent == 2:
        Mid_ResultLabel.configure(text='<<<<<<')
        ResultLabel.configure(text='LOSE...')
    elif opponent ==3:
        Mid_ResultLabel.configure(text=">>>>>>")
        ResultLabel.configure(text='YOU WON!')

elif choice == 1:
    update_image(1,PaperImage)
    if opponent == 1:
        Mid_ResultLabel.configure(text=">>>>>>")
        ResultLabel.configure(text='YOU WON!')
    elif opponent == 2:
        Mid_ResultLabel.configure(text='======')
        ResultLabel.configure(text='DRAW!')
    elif opponent == 3:
        Mid_ResultLabel.configure(text='<<<<<<')
        ResultLabel.configure(text='LOSE...')

elif choice == 2:
    update_image(1,ScissorImage)
    if opponent == 1:
        Mid_ResultLabel.configure(text='<<<<<<')
        ResultLabel.configure(text='LOSE...')
    elif opponent == 2:
        Mid_ResultLabel.configure(text=">>>>>>")
        ResultLabel.configure(text='YOU WON!')
    elif opponent == 3 :
        Mid_ResultLabel.configure(text='======')
        ResultLabel.configure(text='DRAW!')

There are more improvements you can also make to your code; however, these changes will make your code working!

Overall the code changes made

from tkinter import *
import random
window = Tk()

button_list = ['Rock', 'Paper', 'Scissors']

RockImage = PhotoImage(file="rock.png")
PaperImage = PhotoImage(file="paper.png")
ScissorImage = PhotoImage(file="scissors.png")

def update_image(num, Img):
    if num == 1:
         inputLabel_1 = Label(window, image=Img)
         inputLabel_1.grid(row=0, column=0)
    elif num==2:
        inputLabel_2=Label(window, image=Img)
        inputLabel_2.grid(row=0, column=2)

Mid_ResultLabel=Label(window, text=' ', fg='green')
ResultLabel=Label(window, text=' ',fg='green')
Mid_ResultLabel.grid(row=0, column=1)
ResultLabel.grid(row=1, column=1)

def game(choice):
    print("GAME FUNCTION")
    opponent = random.randint(1,3)
    if opponent == 1:
        update_image(2,RockImage)
    elif opponent == 2:
        update_image(2,PaperImage)
    elif opponent ==3:
        update_image(2,ScissorImage)

    if choice == 0:
        update_image(1,RockImage)
        if opponent == 1:
            Mid_ResultLabel.configure(text='======')
            ResultLabel.configure(text='DRAW!')
        elif opponent == 2:
            Mid_ResultLabel.configure(text='<<<<<<')
            ResultLabel.configure(text='LOSE...')
        elif opponent ==3:
            Mid_ResultLabel.configure(text=">>>>>>")
            ResultLabel.configure(text='YOU WON!')

    elif choice == 1:
        update_image(1,PaperImage)
        if opponent == 1:
            Mid_ResultLabel.configure(text=">>>>>>")
            ResultLabel.configure(text='YOU WON!')
        elif opponent == 2:
            Mid_ResultLabel.configure(text='======')
            ResultLabel.configure(text='DRAW!')
        elif opponent == 3:
            Mid_ResultLabel.configure(text='<<<<<<')
            ResultLabel.configure(text='LOSE...')

    elif choice == 2:
        update_image(1,ScissorImage)
        if opponent == 1:
            Mid_ResultLabel.configure(text='<<<<<<')
            ResultLabel.configure(text='LOSE...')
        elif opponent == 2:
            Mid_ResultLabel.configure(text=">>>>>>")
            ResultLabel.configure(text='YOU WON!')
        elif opponent == 3 :
            Mid_ResultLabel.configure(text='======')
            ResultLabel.configure(text='DRAW!')

i=0
for button_text in button_list:
    def click(t=i):
            game(t)
    Button(window, text=button_text, width=30, command = click).grid(row=3, column = i)
    i+=1

window.mainloop()

Other Changes you can make

You can also improve your code to be more ledgible in some other ways. Arguably the most important would be to move your code to Object Orientated Programming, I find this guide to be rather good!

Another change you can make is to change your for loop, that creates the buttons, to use Python's enumerate function and lambda:

for i, button_text in enumerate(button_list):
    Button(window, text=button_text, width=30, command = lambda t=i: game(t)).grid(row=3, column = i)

As you can see, that one code change can improve the look of your code!

Hope this helps,

James


问:
Python Scatter Plot Edgecolors by Label
I'm trying to figure out how to dynamically set the edgecolor of a datapoint.
The facecolor can be set by using c=[array of numeric labels], but not so for edgecolors.

What im trying to achieve is a plot where the facecolor equals the predicted label of an algorithm for an instance, and the edgecolor equals the true label of that instance.
This way, i could visually compare the results (important for further work).

Any suggestions? This is my code so far:

```<code>fig, axs = plt.subplots(2, 2)
axs[0, 0].scatter(X_train[:,0], X_train[:,1], c=y_train)
axs[0, 0].set_title('org.Data with true labels')
axs[0, 1].scatter(X_train[:,0], X_train[:,1], c=y_pred)
axs[0, 1].set_title('org.Data with LOF labels')
axs[1, 0].scatter(data_PCA[:,0],data_PCA[:,1], c=y_pred)
axs[1, 0].set_title("PCAplt, labels LOF: org.Data")
axs[1, 1].scatter(data_PCA[:,0],data_PCA[:,1], c=y_pred_PCA)
axs[1, 1].set_title('PCA.plt, labels LOF: PCA')
</code>```

which gives me the following plot

I appreciate any suggestions.
Thank you!

答:
Sometimes the answer comes after laying stuff to rest for some time. I found a solution and wanted to share in case anyone ever needs this:

In short: I precomputed a list of "true label colors" using a very simple list comprehension, and used another list of length 2 with the same colors for the facecolors.

The code:

```<code>colors = ["green","red"]
true_labels_color_encoded = ["red" if label == 1 else "green" for label in y_train]

fig, axs = plt.subplots(2, 2)
axs[0, 0].scatter(X_train[:,0], X_train[:,1], c=y_train, cmap=ListedColormap(colors), edgecolors=true_labels_color_encoded)
axs[0, 0].set_title('org.Data with true labels')
axs[0, 1].scatter(X_train[:,0], X_train[:,1], c=y_pred,cmap=ListedColormap(colors),edgecolors=true_labels_color_encoded)
axs[0, 1].set_title('org.Data with LOF labels')
axs[1, 0].scatter(data_PCA[:,0],data_PCA[:,1], c=y_pred,cmap=ListedColormap(colors),edgecolors=true_labels_color_encoded)
axs[1, 0].set_title("PCAplt, labels LOF: org.Data")
axs[1, 1].scatter(data_PCA[:,0],data_PCA[:,1], c=y_pred_PCA,cmap=ListedColormap(colors),edgecolors=true_labels_color_encoded)
axs[1, 1].set_title('PCA.plt, labels LOF: PCA')
</code>```

so true_labels_color_encoded looks something like = ["red","green","green","green"]
(note: in my case, a label in y_train = 1 means anomaly, and 0 means normal)

which gives me the following plot:

See my plot here

I got even better results using other reduction techniques like ISOMAP or t-SNE.

Title: Python Scatter Plot Edgecolors by Label

Body:
I'm trying to figure out how to dynamically set the edgecolor of a datapoint.
The facecolor can be set by using c=[array of numeric labels], but not so for edgecolors.

What im trying to achieve is a plot where the facecolor equals the predicted label of an algorithm for an instance, and the edgecolor equals the true label of that instance.
This way, i could visually compare the results (important for further work).

Any suggestions? This is my code so far:

fig, axs = plt.subplots(2, 2)
axs[0, 0].scatter(X_train[:,0], X_train[:,1], c=y_train)
axs[0, 0].set_title('org.Data with true labels')
axs[0, 1].scatter(X_train[:,0], X_train[:,1], c=y_pred)
axs[0, 1].set_title('org.Data with LOF labels')
axs[1, 0].scatter(data_PCA[:,0],data_PCA[:,1], c=y_pred)
axs[1, 0].set_title("PCAplt, labels LOF: org.Data")
axs[1, 1].scatter(data_PCA[:,0],data_PCA[:,1], c=y_pred_PCA)
axs[1, 1].set_title('PCA.plt, labels LOF: PCA')

which gives me the following plot

I appreciate any suggestions.
Thank you!

Body:
Sometimes the answer comes after laying stuff to rest for some time. I found a solution and wanted to share in case anyone ever needs this:

In short: I precomputed a list of "true label colors" using a very simple list comprehension, and used another list of length 2 with the same colors for the facecolors.

The code:

colors = ["green","red"]
true_labels_color_encoded = ["red" if label == 1 else "green" for label in y_train]

fig, axs = plt.subplots(2, 2)
axs[0, 0].scatter(X_train[:,0], X_train[:,1], c=y_train, cmap=ListedColormap(colors), edgecolors=true_labels_color_encoded)
axs[0, 0].set_title('org.Data with true labels')
axs[0, 1].scatter(X_train[:,0], X_train[:,1], c=y_pred,cmap=ListedColormap(colors),edgecolors=true_labels_color_encoded)
axs[0, 1].set_title('org.Data with LOF labels')
axs[1, 0].scatter(data_PCA[:,0],data_PCA[:,1], c=y_pred,cmap=ListedColormap(colors),edgecolors=true_labels_color_encoded)
axs[1, 0].set_title("PCAplt, labels LOF: org.Data")
axs[1, 1].scatter(data_PCA[:,0],data_PCA[:,1], c=y_pred_PCA,cmap=ListedColormap(colors),edgecolors=true_labels_color_encoded)
axs[1, 1].set_title('PCA.plt, labels LOF: PCA')

so true_labels_color_encoded looks something like = ["red","green","green","green"]
(note: in my case, a label in y_train = 1 means anomaly, and 0 means normal)

which gives me the following plot:

See my plot here

I got even better results using other reduction techniques like ISOMAP or t-SNE.