问:
Summernote editor validation for allow some html tags like , ,
,
 but not special characters
I am using many patterns but not found any proper pattern for allow string with some HTML tags and without HTML tags.

This pattern allows HTML tags but not a simple string

```<code><textarea id="description" class="summernote" maxlength="500" data-parsley-pattern="/<(p|span|ul|li|i|u) ?.*>(.*)<\/(p|span|ul|li|i|u)>/"></textarea>
</code>```

allowed values should be : 1.  Adfg gfg gdfsg gvdsfgdsr

This is for test description

test for

dasdasddsad

should not be allowed : >@>$#@$>
./34.3/2.2/34
34
34234
$#%#$$#

Please help me

答:
1.) If you want to allow the whole tag ( with attributes and text with it, special chars are allowed in attributes but not in text area) you can use this.

For all examples : Highlighted will be matched

Aenean lacinia bibendum life sed consectetur. Work quis risus eget urna mollis ornare about leo. "

```<code>/<\s*([a-z]?)[^>]*>([a-zA-Z0-9_]*?)<\s*/\s*([a-z]?)>/g
</code>```

If you only want to allow the tag name you can use this

It will match only tag names like =>
, ,

```<code>/<\s*([a-z]*?)[>]*\s*>/g
</code>```

if you only want to accept one tag at a time: example =>

use this:

```<code>/<\s*([a-z]*?)[>]*\s*>/
</code>```

if you don't want to allow space at the start or end of the tags use (remove \s*)

```<code>/<([a-z]*?)[>]*>/
</code>```

If you want to allow only some specific tags:

```<code>/<\s*((p|span|ul|li|i|u)1?)[>]*\s*>/
</code>```

This will only allow specific tags and alphnumerics + _ in between , wont allow any attributes in tags:

Example: life klaskdjlaksjd lsdjk

```<code>/<\s*((p|span|ul|li|i|u|a)?)*>([a-zA-Z0-9_ ]*?)<\s*/\s*((p|span|ul|li|i|u|a)1?)?>/
</code>```

Title: Summernote editor validation for allow some html tags like <b>, <i>, <ul>, <li> but not special characters

Body:
I am using many patterns but not found any proper pattern for allow string with some HTML tags and without HTML tags.

This pattern allows HTML tags but not a simple string

<textarea id="description" class="summernote" maxlength="500" data-parsley-pattern="/<(p|span|ul|li|i|u) ?.*>(.*)<\/(p|span|ul|li|i|u)>/"></textarea>

allowed values should be : 1.  Adfg gfg gdfsg gvdsfgdsr

This is for test description

test for

dasdasddsad

should not be allowed : >@>$#@$>
./34.3/2.2/34
34
34234
$#%#$$#

Please help me

Body:
1.) If you want to allow the whole tag ( with attributes and text with it, special chars are allowed in attributes but not in text area) you can use this.

For all examples : Highlighted will be matched

Aenean lacinia bibendum <a href="/life">life</a> sed consectetur. <a href="/work">Work</a> quis risus eget urna mollis ornare <a href="/about">about</a> leo. "

/<\s*([a-z]?)[^>]*>([a-zA-Z0-9_]*?)<\s*/\s*([a-z]?)>/g

If you only want to allow the tag name you can use this

It will match only tag names like =>  <div>, <a>, <li>

/<\s*([a-z]*?)[>]*\s*>/g

if you only want to accept one tag at a time: example =><div>
use this:

/<\s*([a-z]*?)[>]*\s*>/

if you don't want to allow space at the start or end of the tags use (remove \s*)

/<([a-z]*?)[>]*>/

If you want to allow only some specific tags:

/<\s*((p|span|ul|li|i|u)1?)[>]*\s*>/

This will only allow specific tags and alphnumerics + _ in between , wont allow any attributes in tags:

Example: <a>life klaskdjlaksjd lsdjk</a>

/<\s*((p|span|ul|li|i|u|a)?)*>([a-zA-Z0-9_ ]*?)<\s*/\s*((p|span|ul|li|i|u|a)1?)?>/


来源: stackexchange

问:
how to detect logout of asp.net 4 session
How do you detect when a user logs out using the ASP.Net 4 session management?  I have a site that is using the <LoginTemplate> with a <LoginStatus> control.  When the user clicks the "Log out" link, it should fire the LoggingOut event of the LoginStatus, but I cannot get it to do so.  Is there another way to detect when the user logs out of the application?  Session_End isn't being fired because the session itself is still valid, just that the user isn't logged in.</p>

答:
Session.Abandon()

http://msdn.microsoft.com/en-us/library/ms524310.aspx

Here is a little more detail on the HttpSessionState object:

http://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate_members.aspx

ContentLicense: CC BY-SA 3.0


问:
React+JavaScript: How to erase data fields after a successful 200 code from sign up page and redirect to login?
Please find my code below for the SignUp react function, once I receive response of 200 after clicking the Sign up button, I want to erase the text in all three fields and redirect the user back to login page. Very new to web development, any help is appreciated!  There are three fields needed to sign up: firstName, email and password.</p>

```<code> export default function SignUp() {
      const [firstName, setFirstName] = React.useState("");
      const [email, setEmail] = React.useState("");
      const [password, setPassword] = React.useState("");

  let sign = async (event) => {
    event.preventDefault();
    await ApiService.createUser(
      firstName,
      email,
      password
    )
      .then((response) => {
        console.log(response.data);
      })
      .catch((error) => console.log(error));
  };

  return (
    <Container component="main" maxWidth="xs">
      <CssBaseline />
      <div className={classes.paper}>
        <Avatar className={classes.avatar}>
          <LockOutlinedIcon />
        </Avatar>
        <Typography component="h1" variant="h5">
          Sign up
        </Typography>
        <form className={classes.form} noValidate>
          <Grid container spacing={2}>
            <Grid item xs={12} sm={6}>
              <TextField
                autoComplete="fname"
                name="firstName"
                variant="outlined"
                required
                fullWidth
                id="firstName"
                label="First Name"
                autoFocus
                onChange={(event) => setFirstName(event.target.value)}
              />
            </Grid>
            <Grid item xs={12}>
              <TextField
                variant="outlined"
                required
                fullWidth
                id="email"
                label="Email Address"
                name="email"
                autoComplete="email"
                onChange={(event) => setEmail(event.target.value)}
              />
            </Grid>
            <Grid item xs={12}>
              <TextField
                variant="outlined"
                required
                fullWidth
                name="password"
                label="Password"
                type="password"
                id="password"
                autoComplete="current-password"
                onChange={(event) => setPassword(event.target.value)}
              />
            </Grid>
          </Grid>
          <Button
            type="submit"
            fullWidth
            variant="contained"
            color="primary"
            className={classes.submit}
            onClick={sign}
          >
            Sign Up
          </Button>
</code>```

答:
For the redirection part, you need to inform us which router you are using.

For instance, if you are using react-router, you can use useHistory hook as follow:

```<code>import { useHistory } from "react-router-dom"

// in your sign function
let history = useHistory()
history.push("/loginPage") // the string '/loginPage' is an example and depend on your routes implementation
</code>```

react-router doc : https://reacttraining.com/react-router/web/api/Hooks/usehistory

Also, you most probably don't need to erase the text-fields since the redirection will unmount your component.

ContentLicense: CC BY-SA 4.0

Body:
Please find my code below for the SignUp react function, once I receive response of 200 after clicking the Sign up button, I want to erase the text in all three fields and redirect the user back to login page. Very new to web development, any help is appreciated!  There are three fields needed to sign up: firstName, email and password.

 export default function SignUp() {
      const [firstName, setFirstName] = React.useState("");
      const [email, setEmail] = React.useState("");
      const [password, setPassword] = React.useState("");

  let sign = async (event) => {
    event.preventDefault();
    await ApiService.createUser(
      firstName,
      email,
      password
    )
      .then((response) => {
        console.log(response.data);
      })
      .catch((error) => console.log(error));
  };

  return (
    <Container component="main" maxWidth="xs">
      <CssBaseline />

        <Avatar className={classes.avatar}>
          <LockOutlinedIcon />
        </Avatar>
        <Typography component="h1" variant="h5">
          Sign up
        </Typography>
        <form className={classes.form} noValidate>
          <Grid container spacing={2}>
            <Grid item xs={12} sm={6}>
              <TextField
                autoComplete="fname"
                name="firstName"
                variant="outlined"
                required
                fullWidth
                id="firstName"
                label="First Name"
                autoFocus
                onChange={(event) => setFirstName(event.target.value)}
              />
            </Grid>
            <Grid item xs={12}>
              <TextField
                variant="outlined"
                required
                fullWidth
                id="email"
                label="Email Address"
                name="email"
                autoComplete="email"
                onChange={(event) => setEmail(event.target.value)}
              />
            </Grid>
            <Grid item xs={12}>
              <TextField
                variant="outlined"
                required
                fullWidth
                name="password"
                label="Password"
                type="password"
                id="password"
                autoComplete="current-password"
                onChange={(event) => setPassword(event.target.value)}
              />
            </Grid>
          </Grid>
          <Button
            type="submit"
            fullWidth
            variant="contained"
            color="primary"
            className={classes.submit}
            onClick={sign}
          >
            Sign Up
          </Button>

Body:
For the redirection part, you need to inform us which router you are using.

For instance, if you are using react-router, you can use useHistory hook as follow:

import { useHistory } from "react-router-dom"

// in your sign function
let history = useHistory()
history.push("/loginPage") // the string '/loginPage' is an example and depend on your routes implementation

react-router doc : https://reacttraining.com/react-router/web/api/Hooks/usehistory

Also, you most probably don't need to erase the text-fields since the redirection will unmount your component.


问:
How do I expire a timer manually/programmatically in Activiti BPMN?
I am using Activiti BPMN version 5.15.
I have a user task where I attached a timer as you see at the following screenshot

How am I supposed to make the timer expire now (for testing purposes) either programmatically or manually ?

Thank you

答:
Why dont you add a signal boundary event that points to the same output just for testing. You can send the signal to the engine via the ReST API, again, just for testing. The handler can stay in place in production as nothing will every trigger it.
You can also follow the solution here which also uses a signal, but uses the signal to reset the boundary timer.
The second option is more complex, but may better emulate exactly what you are asking for.</p>


问:
Debug in Atmel Studio jumps to wild area of code when 'step out' is pressed
Good day all!

I am running the latest Atmel Studio 7 with all patches.
AVR-GCC is being used with a 32U4 avr plus an Atmel-ICE via JTAG.

I am in an ISR function and step over works fine each time I press until I call a separate function.
When I get to this function I am on the 1st line of code.
The next press of step over does not go to the next line as it clearly should but jumps back to the middle of my ISR function in a random place.

The code is not working over all but did before the last few changes.

How do I go about troubleshooting this?

Thanks!

答:
When you debug an ISR don't forget that on break points cpu will stop, but all I/Os continue to run, and you probably a new interrupt will be triggered while you pressing next stop over, so other break points may be triggeredvand debugger stop on another place.

Are you enable interrupts before final RETI?


问:
How can I get webpack to autoprefixe my scss files using this configuration?
Im looking for some help with a webpack using scss and autoprefixer. For some reason I can not get the autoprefixer to work. My cofig file is quite unique. Any help would be greatly appreciated, I have been trying modifying the config in a number of way and I have been googling alot but nothing seems to be working.

this is my webpack config

```<code>/* eslint-disable import/no-extraneous-dependencies */
const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const autoprefixer = require("autoprefixer");
const SVGSpritemapPlugin = require("svg-spritemap-webpack-plugin");
const VueLoaderPlugin = require("vue-loader/lib/plugin");
const CopyPlugin = require("copy-webpack-plugin");
require("@babel/polyfill");

module.exports = {
  devtool: "source-map",
  mode: "development",

  entry: {
    app: "./src/index.js",
  },

  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "js/[name].js",
  },

  resolve: {
    extensions: [".web.js", ".js", ".json", ".web.jsx", ".jsx"],
  },
  externals: {
    jquery: "jQuery",
  },

  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        use: [
          {
            loader: require.resolve("babel-loader"),
            options: {
              cacheDirectory: true,
              presets: ["@babel/preset-env"],
            },
          },
        ],
      },
      {
        test: /\.vue$/,
        loader: "vue-loader",
      },
      {
        test: /\.(png|woff|woff2|eot|ttf|svg|gif)$/,
        use: [
          {
            loader: "file-loader",
            options: {
              name: "../[path][name].[ext]",
              context: "src",
            },
          },
          {
            loader: "url-loader",
            options: {
              limit: 8192,
            },
          },
        ],
      },
      {
        test: /\.(scss|sass)$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
          },
          {
            loader: "css-loader",
            options: {
              sourceMap: true,
            },
          },

          {
            loader: "postcss-loader",
            options: {
              autoprefixer: {
                grid: true,
                browsers: ["last 2 versions, IE11"],
              },
              parser: "postcss-scss",
              sourceMap: true,
              plugins: () => [autoprefixer],
            },
          },

          {
            loader: "sass-loader",
            options: {
              sourceMap: true,
            },
          },
        ],
      },
    ],
  },

  plugins: [
    new MiniCssExtractPlugin({
      filename: "./css/[name].css",
    }),
    new VueLoaderPlugin(),
    new SVGSpritemapPlugin("src/images/sprites/**/*.svg", {
      output: {
        svg4everybody: true,
      },
      sprite: {
        generate: {
          use: true,
        },
      },
    }),
    new CopyPlugin([
      {
        from: "src/img",
        to: "img",
      },
    ]),
  ],
};

</code>```

答:
Sometimes it's worth reading the documentation :)
Missing plugins: [ autoprefixer, ... ];

```<code>{
  loader: 'postcss-loader',
  options: {
    plugins: [
      require('postcss-import')(),
      require('stylelint')(),
      ...,
    ]
  }
}
</code>```

For better order move the postcss configuration to a separate file or even a folder.

```<code>{
  loader: 'postcss-loader',
  options: {
    sourceMap: true,
    config: {
      path: './config/',
    },
  },
},
</code>```

Dir with post.config - config/postcss.config.js

postcss.config.js

```<code>const cssnano = require('cssnano')
const autoprefixer = require('autoprefixer')
const postcssUrl = require('postcss-url')

module.exports = {
  plugins: [
    postcssUrl({
      url: 'inline',
      maxSize: 50,
    }),
    cssnano({
      safe: true,
    }),
    autoprefixer({
      grid: "autoplace"
    }),
  ],
};
</code>```

Body:
Im looking for some help with a webpack using scss and autoprefixer. For some reason I can not get the autoprefixer to work. My cofig file is quite unique. Any help would be greatly appreciated, I have been trying modifying the config in a number of way and I have been googling alot but nothing seems to be working.

this is my webpack config

/* eslint-disable import/no-extraneous-dependencies */
const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const autoprefixer = require("autoprefixer");
const SVGSpritemapPlugin = require("svg-spritemap-webpack-plugin");
const VueLoaderPlugin = require("vue-loader/lib/plugin");
const CopyPlugin = require("copy-webpack-plugin");
require("@babel/polyfill");

module.exports = {
  devtool: "source-map",
  mode: "development",

  entry: {
    app: "./src/index.js",
  },

  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "js/[name].js",
  },

  resolve: {
    extensions: [".web.js", ".js", ".json", ".web.jsx", ".jsx"],
  },
  externals: {
    jquery: "jQuery",
  },

  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        use: [
          {
            loader: require.resolve("babel-loader"),
            options: {
              cacheDirectory: true,
              presets: ["@babel/preset-env"],
            },
          },
        ],
      },
      {
        test: /\.vue$/,
        loader: "vue-loader",
      },
      {
        test: /\.(png|woff|woff2|eot|ttf|svg|gif)$/,
        use: [
          {
            loader: "file-loader",
            options: {
              name: "../[path][name].[ext]",
              context: "src",
            },
          },
          {
            loader: "url-loader",
            options: {
              limit: 8192,
            },
          },
        ],
      },
      {
        test: /\.(scss|sass)$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
          },
          {
            loader: "css-loader",
            options: {
              sourceMap: true,
            },
          },

          {
            loader: "postcss-loader",
            options: {
              autoprefixer: {
                grid: true,
                browsers: ["last 2 versions, IE11"],
              },
              parser: "postcss-scss",
              sourceMap: true,
              plugins: () => [autoprefixer],
            },
          },

          {
            loader: "sass-loader",
            options: {
              sourceMap: true,
            },
          },
        ],
      },
    ],
  },

  plugins: [
    new MiniCssExtractPlugin({
      filename: "./css/[name].css",
    }),
    new VueLoaderPlugin(),
    new SVGSpritemapPlugin("src/images/sprites/**/*.svg", {
      output: {
        svg4everybody: true,
      },
      sprite: {
        generate: {
          use: true,
        },
      },
    }),
    new CopyPlugin([
      {
        from: "src/img",
        to: "img",
      },
    ]),
  ],
};

Body:
Sometimes it's worth reading the documentation :)
Missing plugins: [ autoprefixer, ... ];

{
  loader: 'postcss-loader',
  options: {
    plugins: [
      require('postcss-import')(),
      require('stylelint')(),
      ...,
    ]
  }
}

For better order move the postcss configuration to a separate file or even a folder.

{
  loader: 'postcss-loader',
  options: {
    sourceMap: true,
    config: {
      path: './config/',
    },
  },
},

Dir with post.config - config/postcss.config.js

postcss.config.js

const cssnano = require('cssnano')
const autoprefixer = require('autoprefixer')
const postcssUrl = require('postcss-url')

module.exports = {
  plugins: [
    postcssUrl({
      url: 'inline',
      maxSize: 50,
    }),
    cssnano({
      safe: true,
    }),
    autoprefixer({
      grid: "autoplace"
    }),
  ],
};


问:
SQL Duplicate Key Help
I have a statement that looks something like this:

```<code>insert table_name(...)
select .... from ... join ...
</code>```

How can I use where not exists or something of that effect with this insert and select statement so that if this exact code is reran with the same values, it won't throw an error. I don't want to have to copy and paste the select/joins in a check as it is a pretty big block of code, so is there any way to do something like

```<code>if not exists (insert table_name(...)
              select ... from...join)
</code>```

or would it be something else like

```<code>insert table_name(...)
if not exists(select ... from ... join)
</code>```

答:
Trying to keep this as generic as you did and still have it make sense. Hopefully, this is understandable.

```<code>insert table_name(...)
select .... from ... join ...
WHERE NOT EXISTS(SELECT NULL
                     FROM table_name
                     WHERE PKColumn = YourOuterSelectTable.PKColumn)
</code>```

To try to put some more meat on it:

```<code>/* Assume Column1 is primary key */
INSERT INTO table_name
    (Column1, Column2)
    SELECT a.Column1, b.Column2
        FROM TableA a
            INNER JOIN TableB b
                ON a.Column1 = b.FKColumn1
        WHERE NOT EXISTS (SELECT NULL
                              FROM table_name
                              WHERE Column1 = a.Column1)
</code>```

Title: SQL Duplicate Key Help

Body:
I have a statement that looks something like this:

insert table_name(...)
select .... from ... join ...

How can I use where not exists or something of that effect with this insert and select statement so that if this exact code is reran with the same values, it won't throw an error. I don't want to have to copy and paste the select/joins in a check as it is a pretty big block of code, so is there any way to do something like

if not exists (insert table_name(...)
              select ... from...join)

or would it be something else like

insert table_name(...)
if not exists(select ... from ... join)

Body:
Trying to keep this as generic as you did and still have it make sense. Hopefully, this is understandable.

insert table_name(...)
select .... from ... join ...
WHERE NOT EXISTS(SELECT NULL
                     FROM table_name
                     WHERE PKColumn = YourOuterSelectTable.PKColumn)

To try to put some more meat on it:

/* Assume Column1 is primary key */
INSERT INTO table_name
    (Column1, Column2)
    SELECT a.Column1, b.Column2
        FROM TableA a
            INNER JOIN TableB b
                ON a.Column1 = b.FKColumn1
        WHERE NOT EXISTS (SELECT NULL
                              FROM table_name
                              WHERE Column1 = a.Column1)


问:
GeneXus 16 .NET Web - Consume SOAP service via External Object with Basic Authentication
I have Consumer (GX16 U5 .NET) and a Provider (GX15 U6 Java) that are talking via SOAP.  The Provider expects the "Authorization" HTTP Header with Basic Authentication but my Consumer is apparently not including the Header (as seen from TCPTrace) even though I have set the Authentication to Yes, Auth Method to Basic, and provided the creds.

I am using an External Object created from the WSDL inspector to consume the service, and I set the Location variable accordingly.

Is there something special on the .NET side (or even in IIS) I need to do to include the Header?

I have a second Consumer from a third KB (GX16 U5 Java) that consumes this SAME EXACT Provider just fine - the HTTP Header is included.

Any help would be appreciated!

答:
The reason why .NET does not include the Authorization header in the first attempt is because it is not Preemptive.

The opposite behavior, in some cases is considered less secure, which is to send the credentials on the first request. (This is called Preemptive Authentication)

If the provider returns 401 error code after the first attempt .NET will execute a second attempt that will include the Authorization header with the credentials.
If the provider returns a different code, there will not be a second attempt. We believe this is your case.

To sump up:
When the service is invoked, the following is done:
- The request will be made without sending the credentials.
- The server responds an error 401 with a header of the type: Authorization: Basic dXNlcjpwYXNz.
- A second request is executed, now with the credentials. The Authorization Header goes with Authorization : Basic dXNlcjpwYXNz
- The server authenticates the user and responds with Http code 200.

Workaround:
In order to send the Authorization header you may need to use httpclient by including a specific procedure for every service that matters, and replacing your ExternalObject.

Below you will find the example:

Event 'TestHTTP'

&HTTPClient.Host = "localhost"

&HTTPClient.Port = 8089

&HTTPClient.BaseURL = "/version8JavaEnvironment/servlet/"

&HTTPClient.AddHeader("Content-type", "text/xml;charset=utf-8")

&HTTPClient.AddHeader("SOAPAction", "version8action/ASERVICEPROVIDER.Execute")

&HTTPClient.AddHeader("Authorization", "ppppppppppppppppppppppppp")

&XMLWriter.OpenRequest(&HTTPClient)

&XMLWriter.WriteStartDocument("utf-8", 0)

&XMLWriter.WriteStartElement("SOAP-ENVEnvelope")

&XMLWriter.WriteAttribute("xmlnsSOAP-ENV",http//schemas.xmlsoap.org/soap/envelope/")

&XMLWriter.WriteAttribute("xmlnsxsd", "http//www.w3.org/2001/XMLSchema")

&XMLWriter.WriteAttribute("xmlnsSOAP-ENC",http//schemas.xmlsoap.org/soap/encoding/")

&XMLWriter.WriteAttribute("xmlnsxsi", "http//www.w3.org/2001/XMLSchema-instance")

&XMLWriter.WriteStartElement("SOAP-ENVBody")

&XMLWriter.WriteElement("ServiceProvider.Execute", "")

&XMLWriter.WriteAttribute("xmlns", "version8")

&XMLWriter.WriteEndElement()

&XMLWriter.Close()

&HTTPClient.Execute("POST", "targetResourceName")

&longvarchar = &HTTPClient.ToString()

Endevent


问:
Cytoscape installation assistance
I've tried installing and reinstalling both Cytoscape and Java. I'm kinda ignorant when it comes to these things so I would love detailed help.

macOS Catalina Version 10.15.4. Cytoscape 3.8.0 and Java 8 Update 251

答:
Cytoscape 3.8.0 requires Java 11 and won't run with Java 8.

-- scooter

Title: Cytoscape installation assistance


问:
ggplot: remove lines at ribbon edges
I am using ggplot to plot time course data (fixation proportions over time to different objects on the screen) and want to use a ribbon to show the SE, but the ribbon itself has lines at the top and bottom edges, which makes reading the graph a bit harder. I haven't been able to figure out how to get rid of those edge lines. Here is my plot code:

```<code>ggplot(d, aes(Time, y, color = Object, fill = Object)) +
  stat_summary(fun.y = "mean", geom = "line", size = 2) +
  stat_summary(fun.data = "mean_se", geom = "ribbon", alpha = .3)
</code>```

Any suggestions?

Here is a minimal working example. I've compressed my data to:

```<code>   Time Object          y      lower     upper
 1 1000      C 0.12453389 0.04510504 0.2039627
 2 1000      T 0.58826856 0.37615078 0.8003864
 3 1000      U 0.09437160 0.03278069 0.1559625
 4 1100      C 0.12140127 0.03943988 0.2033627
 5 1100      T 0.64560823 0.44898727 0.8422292
 6 1100      U 0.06725172 0.01584248 0.1186610

d <- structure(list(Time = c(1000L, 1000L, 1000L, 1100L, 1100L, 1100L), Object = structure(c(1L, 2L, 3L, 1L, 2L, 3L), .Label = c("C",
"T", "U"), class = "factor"), y = c(0.12453389, 0.58826856, 0.0943716,
0.12140127, 0.64560823, 0.06725172), lower = c(0.04510504, 0.37615078,
0.03278069, 0.03943988, 0.44898727, 0.01584248), upper = c(0.2039627,
0.8003864, 0.1559625, 0.2033627, 0.8422292, 0.118661)), .Names = c("Time",
"Object", "y", "lower", "upper"), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6"))
</code>```

and here is the new plot code:

```<code>ggplot(d, aes(Time, y, color = Object, fill = Object)) +
  geom_line(size = 2) +
  geom_ribbon(aes(ymin = lower, ymax = upper), alpha = .3)
</code>```

答:
ggplot2's geom_ribbon() now includes an outline.type argument that helps control how the ribbon outlines are displayed.

Outline Type

library(tidyverse)

huron <- tibble(year = 1875:1972, level = as.vector(LakeHuron))

huron %>%
    ggplot(aes(year, level)) +
    geom_ribbon(aes(ymin = level - 1, ymax = level + 1),
                fill = "grey70", color = "red",
                outline.type = "lower") +
    geom_line(aes(y = level))
```

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

<p><sup>Created on 2020-05-28 by the reprex package (v0.3.0)</sup></p>

<h2>Linetype = 0</h2>

<p>Alternatively, as suggested we can set <code>linetype = 0</code> to remove all lines. </p>

<pre class="lang-r prettyprint-override"><code>library(tidyverse)

huron <- tibble(year = 1875:1972, level = as.vector(LakeHuron))

huron %>%
    ggplot(aes(year, level)) +
    geom_ribbon(aes(ymin = level - 1, ymax = level + 1),
                fill = "grey70", color = "red", linetype = 0) +
    geom_line(aes(y = level))
</code>```

Created on 2020-05-28 by the reprex package (v0.3.0)

Title: ggplot: remove lines at ribbon edges

Body:
I am using ggplot to plot time course data (fixation proportions over time to different objects on the screen) and want to use a ribbon to show the SE, but the ribbon itself has lines at the top and bottom edges, which makes reading the graph a bit harder. I haven't been able to figure out how to get rid of those edge lines. Here is my plot code:

ggplot(d, aes(Time, y, color = Object, fill = Object)) +
  stat_summary(fun.y = "mean", geom = "line", size = 2) +
  stat_summary(fun.data = "mean_se", geom = "ribbon", alpha = .3)

Any suggestions?

Here is a minimal working example. I've compressed my data to:

   Time Object          y      lower     upper
 1 1000      C 0.12453389 0.04510504 0.2039627
 2 1000      T 0.58826856 0.37615078 0.8003864
 3 1000      U 0.09437160 0.03278069 0.1559625
 4 1100      C 0.12140127 0.03943988 0.2033627
 5 1100      T 0.64560823 0.44898727 0.8422292
 6 1100      U 0.06725172 0.01584248 0.1186610

d <- structure(list(Time = c(1000L, 1000L, 1000L, 1100L, 1100L, 1100L), Object = structure(c(1L, 2L, 3L, 1L, 2L, 3L), .Label = c("C",
"T", "U"), class = "factor"), y = c(0.12453389, 0.58826856, 0.0943716,
0.12140127, 0.64560823, 0.06725172), lower = c(0.04510504, 0.37615078,
0.03278069, 0.03943988, 0.44898727, 0.01584248), upper = c(0.2039627,
0.8003864, 0.1559625, 0.2033627, 0.8422292, 0.118661)), .Names = c("Time",
"Object", "y", "lower", "upper"), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6"))

and here is the new plot code:

ggplot(d, aes(Time, y, color = Object, fill = Object)) +
  geom_line(size = 2) +
  geom_ribbon(aes(ymin = lower, ymax = upper), alpha = .3)

Body:
ggplot2's geom_ribbon() now includes an outline.type argument that helps control how the ribbon outlines are displayed.

Outline Type

library(tidyverse)

huron <- tibble(year = 1875:1972, level = as.vector(LakeHuron))

huron %>%
    ggplot(aes(year, level)) +
    geom_ribbon(aes(ymin = level - 1, ymax = level + 1),
                fill = "grey70", color = "red",
                outline.type = "lower") +
    geom_line(aes(y = level))

Created on 2020-05-28 by the reprex package (v0.3.0)

Linetype = 0

Alternatively, as suggested we can set linetype = 0 to remove all lines.

library(tidyverse)

huron <- tibble(year = 1875:1972, level = as.vector(LakeHuron))

huron %>%
    ggplot(aes(year, level)) +
    geom_ribbon(aes(ymin = level - 1, ymax = level + 1),
                fill = "grey70", color = "red", linetype = 0) +
    geom_line(aes(y = level))

Created on 2020-05-28 by the reprex package (v0.3.0)


问:
How to use mapcomplex in C#
I am trying to map an object from my entity framework to an object. Everything was working fine until I had to do a list of objects. I get an error saying I should use a mapcomplex instead of a map. Unfortunately, I cannot find any doc on that function.

Complete classes:

```<code>using Cld.Domain.DataService.Contract.Filter;
using Cld.Domain.DataService.Contract.Model;
using Cld.Domain.DataService.Service.Model;
using Core.Data;
using System.Collections.Generic;
using System.Linq;

namespace Cld.Domain.DataService.Service.Repositories
{
    internal class ConditRepository : RepositoryBase<CONDIT, Condit, string>,
                                         ISearchableRepository<CONDIT, Condit, ConditFilter>
    {
         public static readonly IMapping<CONDIT, Condit> ConditMap = new Mapping<CONDIT, Condit>()
            .Maps(entity => entity.ID, contract => contract.Id)
            .Maps(entity => entity.LIBELLE_D, contract => contract.LabelD)
            .Maps(entity => entity.LIBELLE_E, contract => contract.LabelE)
            .Maps(entity => entity.LIBELLE_F, contract => contract.LabelF)
            .Maps(entity => entity.LIBELLE_N, contract => contract.LabelN)
            .Maps(entity => entity.TRACKURL, contract => contract.TrackUrl)
            .Maps(entity => entity.CODE, contract => contract.Code)
            .Maps(entity => entity.CUSTID, contract => contract.Custid)
            .Maps(entity => entity.NUMERO, contract => contract.Number)
            .Maps(entity => entity.SCAC, contract => contract.Scac)
            .Maps(entity => entity.SERVIID, contract => contract.ServiId)
            .Maps(entity => entity.SHIPORDER, contract => contract.ShipOrder)
            .Maps(entity => entity.REQTIME, contract => contract.RequestedDateTime)
            .Maps(entity => entity.OutputPath, contract => contract.OutputPath)
            .Maps(entity => entity.PACTYPs.Select(x => x.ID).ToList(), contract => contract.listPacktypes)
            ;
    }
}
</code>```

then the class from the EF:

```<code>namespace Cld.Domain.DataService.Service.Model
{
    using System;
    using System.Collections.Generic;

    public partial class CONDIT
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public CONDIT()
        {
            this.SHIPMENTs = new HashSet<SHIPMENT>();
            this.PACTYPs = new HashSet<PACTYP>();
        }

        public string LIBELLE_F { get; set; }
        public string LIBELLE_N { get; set; }
        public short NUMERO { get; set; }
        public string ID { get; set; }
        public string LIBELLE_E { get; set; }
        public string LIBELLE_D { get; set; }
        public string CUSTID { get; set; }
        public string SERVIID { get; set; }
        public string SCAC { get; set; }
        public string CODE { get; set; }
        public string TRACKURL { get; set; }
        public int SHIPORDER { get; set; }
        public System.TimeSpan REQTIME { get; set; }
        public string OutputPath { get; set; }
        public byte[] timestamp_column { get; set; }
        public bool Active { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<SHIPMENT> SHIPMENTs { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<PACTYP> PACTYPs { get; set; }
    }
}
</code>```

And finally the contract I'm trying to fit it into:

```<code>using Cld.Core.ContractFramework;
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;

namespace Cld.Domain.DataService.Contract.Model
{
    [DataContract]
    public class Condit : IEntity<string>
    {
        [DataMember]
        public string Id { get; set; }

        [DataMember]
        public string LabelF { get; set; }

        [DataMember]
        public string LabelN { get; set; }

        [DataMember]
        public string LabelE { get; set; }

        [DataMember]
        public string LabelD { get; set; }

        [DataMember]
        public short Number { get; set; }

        [DataMember]
        public byte[] Timestamp { get; set; }

        [DataMember]
        public string Custid { get; set; }

        [DataMember]
        public string ServiId { get; set; }

        [DataMember]
        public string Scac { get; set; }

        [DataMember]
        public string Code { get; set; }

        [DataMember]
        public string TrackUrl { get; set; }

        [DataMember]
        public int ShipOrder { get; set; }

        [DataMember]
        public TimeSpan RequestedDateTime { get; set; }

        [DataMember]
        public string OutputPath { get; set; }

        [DataMember]
        public List<int> listPacktypes { get; set; }
    }
}
</code>```

答:
A colleague logged in and I managed to ask him the question.

Here's the result:

```<code>.MapComplex((entity, contractEntity, synchronizer) =>
            {
                contractEntity.listCondits = entity.CONDITs.Select(x => x.ID).ToList();

            });
</code>```

entity automatically take the original type, contractEntity take the type you want to put the info into, and I don't know what the synchronizer is.
From there, you can manipulate them how you want. So in this case, I modified the contract entity by filling its listCondits with the info from the original entity.

Sorry for the trouble, my colleague was supposed to have left and not reconnect.

Title: How to use mapcomplex in C#

Body:
I am trying to map an object from my entity framework to an object. Everything was working fine until I had to do a list of objects. I get an error saying I should use a mapcomplex instead of a map. Unfortunately, I cannot find any doc on that function.

Complete classes:

using Cld.Domain.DataService.Contract.Filter;
using Cld.Domain.DataService.Contract.Model;
using Cld.Domain.DataService.Service.Model;
using Core.Data;
using System.Collections.Generic;
using System.Linq;

namespace Cld.Domain.DataService.Service.Repositories
{
    internal class ConditRepository : RepositoryBase<CONDIT, Condit, string>,
                                         ISearchableRepository<CONDIT, Condit, ConditFilter>
    {
         public static readonly IMapping<CONDIT, Condit> ConditMap = new Mapping<CONDIT, Condit>()
            .Maps(entity => entity.ID, contract => contract.Id)
            .Maps(entity => entity.LIBELLE_D, contract => contract.LabelD)
            .Maps(entity => entity.LIBELLE_E, contract => contract.LabelE)
            .Maps(entity => entity.LIBELLE_F, contract => contract.LabelF)
            .Maps(entity => entity.LIBELLE_N, contract => contract.LabelN)
            .Maps(entity => entity.TRACKURL, contract => contract.TrackUrl)
            .Maps(entity => entity.CODE, contract => contract.Code)
            .Maps(entity => entity.CUSTID, contract => contract.Custid)
            .Maps(entity => entity.NUMERO, contract => contract.Number)
            .Maps(entity => entity.SCAC, contract => contract.Scac)
            .Maps(entity => entity.SERVIID, contract => contract.ServiId)
            .Maps(entity => entity.SHIPORDER, contract => contract.ShipOrder)
            .Maps(entity => entity.REQTIME, contract => contract.RequestedDateTime)
            .Maps(entity => entity.OutputPath, contract => contract.OutputPath)
            .Maps(entity => entity.PACTYPs.Select(x => x.ID).ToList(), contract => contract.listPacktypes)
            ;
    }
}

then the class from the EF:

namespace Cld.Domain.DataService.Service.Model
{
    using System;
    using System.Collections.Generic;

    public partial class CONDIT
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public CONDIT()
        {
            this.SHIPMENTs = new HashSet<SHIPMENT>();
            this.PACTYPs = new HashSet<PACTYP>();
        }

        public string LIBELLE_F { get; set; }
        public string LIBELLE_N { get; set; }
        public short NUMERO { get; set; }
        public string ID { get; set; }
        public string LIBELLE_E { get; set; }
        public string LIBELLE_D { get; set; }
        public string CUSTID { get; set; }
        public string SERVIID { get; set; }
        public string SCAC { get; set; }
        public string CODE { get; set; }
        public string TRACKURL { get; set; }
        public int SHIPORDER { get; set; }
        public System.TimeSpan REQTIME { get; set; }
        public string OutputPath { get; set; }
        public byte[] timestamp_column { get; set; }
        public bool Active { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<SHIPMENT> SHIPMENTs { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<PACTYP> PACTYPs { get; set; }
    }
}

And finally the contract I'm trying to fit it into:

using Cld.Core.ContractFramework;
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;

namespace Cld.Domain.DataService.Contract.Model
{
    [DataContract]
    public class Condit : IEntity<string>
    {
        [DataMember]
        public string Id { get; set; }

        [DataMember]
        public string LabelF { get; set; }

        [DataMember]
        public string LabelN { get; set; }

        [DataMember]
        public string LabelE { get; set; }

        [DataMember]
        public string LabelD { get; set; }

        [DataMember]
        public short Number { get; set; }

        [DataMember]
        public byte[] Timestamp { get; set; }

        [DataMember]
        public string Custid { get; set; }

        [DataMember]
        public string ServiId { get; set; }

        [DataMember]
        public string Scac { get; set; }

        [DataMember]
        public string Code { get; set; }

        [DataMember]
        public string TrackUrl { get; set; }

        [DataMember]
        public int ShipOrder { get; set; }

        [DataMember]
        public TimeSpan RequestedDateTime { get; set; }

        [DataMember]
        public string OutputPath { get; set; }

        [DataMember]
        public List<int> listPacktypes { get; set; }
    }
}

Body:
A colleague logged in and I managed to ask him the question.

Here's the result:

.MapComplex((entity, contractEntity, synchronizer) =>
            {
                contractEntity.listCondits = entity.CONDITs.Select(x => x.ID).ToList();

            });

entity automatically take the original type, contractEntity take the type you want to put the info into, and I don't know what the synchronizer is.
From there, you can manipulate them how you want. So in this case, I modified the contract entity by filling its listCondits with the info from the original entity.

Sorry for the trouble, my colleague was supposed to have left and not reconnect.


问:
Converting Django DeleteView to work with ajax
Im new to django and im stuck with an issue with ajax. I have the code below.

I have a django delte view. I want to use this with ajax. Right now the view is working but the CSRF Token doesnt  render.

I want to try and use a class based view as im new to learn. Im not sure why the CSRF TOKEN is not being rendered in the AJAX version. It appears when a browser is used but not when ajax is used.

Can someone please help ?

view.py

```<code>class DeleteOrderItemView(SuccessMessageMixin, generic.DeleteView):
    model = OrderItem
    template_name = 'pos/order_item_confirm_delte.html'

    # overwritten the delete to have a conformation code. Pending items do not need a conformation code.
    def delete(self, *args, **kwargs):
        print("I was called !")
        self.object = self.get_object()
        conformation_code = self.request.POST.get('cancellation_code')

        if conformation_code == str(12345) or self.object.status == "Pending":
            # Record code and logged in user
            messages.success(self.request, "Order item {} deleted.".format(self.object.item.name))

            # print cancelled KOT

            return super(DeleteOrderItemView, self).delete(*args, **kwargs)

        else:
            messages.warning(self.request, "Incorrect conformation code.")
            return HttpResponseRedirect(reverse('pos:delete_order_item', kwargs={'pk': self.object.pk}))

    def get_success_url(self, **kwargs):
        self.object = self.get_object()
        order_pk = self.object.order.pk
        return reverse_lazy('pos:order_details', kwargs={'pk': order_pk})

    def render_to_response(self, context, **response_kwargs):
        """ Allow AJAX requests to be handled more gracefully """
        if self.request.is_ajax():
            context = self.get_context_data(**response_kwargs)
            rendered = render_to_string(self.template_name, context)

            return JsonResponse({'delete_form': rendered}, safe=False, **response_kwargs)
        else:
            return super(generic.DeleteView, self).render_to_response(context, **response_kwargs)
</code>```

Javascript

```<code>/* Load the delete form */
$("#js_order_list_items").on("click", "#js_remove_item", function(){

    $("#modal-actions").modal("show");
    remove_url = $('#js_remove_item').attr('js_delete_url')

    $.ajax({
        url: remove_url,
        type: 'get',
        dataType: 'json',
        beforeSend: function () {
            $("#modal-actions").modal("show");
        },
        success: function (data) {
            console.log(data.delete_form)
         $("#modal-actions .modal-content").html(data.delete_form)
        }
    })
});
</code>```

HTML

```<code>{% load static %}
{% block content %}
    <div class="container">
    <br/>
    <div class="col-12 alert alert-danger">
        <h4>Delete item for {{ orderitem.order.customer.name }}</h4>
      </div>
    <div class="row">
      <div class="col-6">
        <ul class="list-group">
            <li class="list-group-item"><strong>{{ orderitem.item.name }}</strong></li>
            <li class="list-group-item">Quantity: {{ orderitem.quantity }}</li>
            <li class="list-group-item">Price: {{ orderitem.price }}</li>
            <li class="list-group-item">Ordered by: {{ orderitem.order.user.username }}</li>
            <li class="list-group-item">
                {% if messages %}
                    <div class="alert alert-danger" role="alert">
                            {% for message in messages %}
                                {{ message }}
                            {% endfor %}
                    </div>
                {% endif %}
            </li>
        </ul>
      </div>
    </div>
        <div class="row">
        <div class="col-12">
          <hr/>
        <form method="POST" action="{% url 'pos:delete_order_item' pk=orderitem.pk %}" class="js_confirm_delete_form">

            {% csrf_token %}

            {% if orderitem.status == 'Confirmed' %}
                <label>Cancellation Code: </label>  <input type="password" id="cancellation_code" name="cancellation_code"><br/><hr/>
            {% endif %}
            <input type="submit" value="Confirm" class="btn btn-danger btn-large btn-lg">
            <a href="{% url 'pos:order_details' pk=orderitem.order.pk %}" class="btn btn-default btn-lg"><button class="btn btn-secondary btn-large btn-lg" type="button">Cancel</button> </a>
        </form>

        </div>
        </div>
    </div>
{% endblock %}
</code>```

答:
I found the issue my self. The render_to_string needs the request passed to it for the csrf_token to work.</p>

```<code>rendered = render_to_string(self.template_name, context, request=self.request)
</code>```

Body:
Im new to django and im stuck with an issue with ajax. I have the code below.

I have a django delte view. I want to use this with ajax. Right now the view is working but the CSRF Token doesnt  render.

I want to try and use a class based view as im new to learn. Im not sure why the CSRF TOKEN is not being rendered in the AJAX version. It appears when a browser is used but not when ajax is used.

Can someone please help ?

view.py

class DeleteOrderItemView(SuccessMessageMixin, generic.DeleteView):
    model = OrderItem
    template_name = 'pos/order_item_confirm_delte.html'

    # overwritten the delete to have a conformation code. Pending items do not need a conformation code.
    def delete(self, *args, **kwargs):
        print("I was called !")
        self.object = self.get_object()
        conformation_code = self.request.POST.get('cancellation_code')

        if conformation_code == str(12345) or self.object.status == "Pending":
            # Record code and logged in user
            messages.success(self.request, "Order item {} deleted.".format(self.object.item.name))

            # print cancelled KOT

            return super(DeleteOrderItemView, self).delete(*args, **kwargs)

        else:
            messages.warning(self.request, "Incorrect conformation code.")
            return HttpResponseRedirect(reverse('pos:delete_order_item', kwargs={'pk': self.object.pk}))

    def get_success_url(self, **kwargs):
        self.object = self.get_object()
        order_pk = self.object.order.pk
        return reverse_lazy('pos:order_details', kwargs={'pk': order_pk})

    def render_to_response(self, context, **response_kwargs):
        """ Allow AJAX requests to be handled more gracefully """
        if self.request.is_ajax():
            context = self.get_context_data(**response_kwargs)
            rendered = render_to_string(self.template_name, context)

            return JsonResponse({'delete_form': rendered}, safe=False, **response_kwargs)
        else:
            return super(generic.DeleteView, self).render_to_response(context, **response_kwargs)

Javascript

/* Load the delete form */
$("#js_order_list_items").on("click", "#js_remove_item", function(){

    $("#modal-actions").modal("show");
    remove_url = $('#js_remove_item').attr('js_delete_url')

    $.ajax({
        url: remove_url,
        type: 'get',
        dataType: 'json',
        beforeSend: function () {
            $("#modal-actions").modal("show");
        },
        success: function (data) {
            console.log(data.delete_form)
         $("#modal-actions .modal-content").html(data.delete_form)
        }
    })
});

HTML

{% load static %}
{% block content %}

Delete item for {{ orderitem.order.customer.name }}

{{ orderitem.item.name }}

Quantity: {{ orderitem.quantity }}

Price: {{ orderitem.price }}

Ordered by: {{ orderitem.order.user.username }}

                {% if messages %}

                            {% for message in messages %}
                                {{ message }}
                            {% endfor %}

                {% endif %}

        <form method="POST" action="{% url 'pos:delete_order_item' pk=orderitem.pk %}" class="js_confirm_delete_form">

            {% csrf_token %}

            {% if orderitem.status == 'Confirmed' %}
                Cancellation Code:   <input type="password" id="cancellation_code" name="cancellation_code">

            {% endif %}
            <input type="submit" value="Confirm" class="btn btn-danger btn-large btn-lg">
            <button class="btn btn-secondary btn-large btn-lg" type="button">Cancel</button>
        </form>

{% endblock %}

Body:
I found the issue my self. The render_to_string needs the request passed to it for the csrf_token to work.

rendered = render_to_string(self.template_name, context, request=self.request)


答: Try the LoginStatus.LoggedOut Event. I have used it in the past and it seemed very reliable..

Title: how to detect logout of asp.net 4 session

Body: How do you detect when a user logs out using the ASP.Net 4 session management?  I have a site that is using the <LoginTemplate> with a <LoginStatus> control.  When the user clicks the "Log out" link, it should fire the LoggingOut event of the LoginStatus, but I cannot get it to do so.  Is there another way to detect when the user logs out of the application?  Session_End isn't being fired because the session itself is still valid, just that the user isn't logged in.


问:
Prevent node package from causing an error in a different environment
I have browser extension using Webpack and there is one package (webextension-polyfill) that throws an error when the script is run outside of the extension environment.

Normally that wouldn't be an issue, but my extension creates a standalone page that can be saved locally by the user and since all the javascript travels with it, this extension specific script throws an error when opened outside of the extension environment.

The only plausible idea I have to get around it is to generate two versions of the bundled javascript. One that imports webextension-polyfill and one that doesn't. Then I could just tell jszip to include that file instead... But that seems a little clunky.

答: I had a moment of clarity this morning and realized that when the user saves the page locally, I'm already feeding them a separate clean template of a html file, so I ended up getting around the issue by including the script via good old  instead of requiring it in the bundle and all I had to do was leave that out of the jsZipped html.

Body: I had a moment of clarity this morning and realized that when the user saves the page locally, I'm already feeding them a separate clean template of a html file, so I ended up getting around the issue by including the script via good old <script src="browser-polyfill.min.js"></script> instead of requiring it in the bundle and all I had to do was leave that out of the jsZipped html.


问:
Access Django variable from JavaScript variable
First of all, I will like to say this is my first question here! (pardon me if this is redundant or duplicated)

I am having some problems with calling JS scripts from Django template:

```<code>{% for suggestion in suggestions %}
    <img class="catalogue-poster" src="{{ suggestion.poster }}" alt="Portada"  onclick="
        document.getElementById('{{form.title.auto_id}}').value = '{{suggestion.title}}'
        document.getElementById('{{form.year.auto_id}}').value = '{{suggestion.year}}'
        document.getElementById('{{form.director.auto_id}}').value = '{{suggestion.director}}'
        document.getElementById('{{form.rating.auto_id}}').value = '{{suggestion.rating}}'
        document.getElementById('{{form.poster.auto_id}}').value = '{{suggestion.poster}}'
        document.getElementById('{{form.trailer.auto_id}}').value = '{{suggestion.trailer}}'
        document.getElementById('{{form.synopsis.auto_id}}').value = '{{suggestion.synopsis}}'
        document.getElementById('{{form.cast.auto_id}}').value = '{{suggestion.cast}}'
    " />
{% endfor %}
</code>```

So, first of all, how can I declare a function outside. I'm a C developer, sorry for my ignorance.

I've tried to create a script outside, such as

```<code><script>
    function foo() {
      console.log('Hey');
    });
</script>
</code>```

And invoke it this way:

```<code><img class="catalogue-poster" src="{{ suggestion.poster }}" alt="Portada"  onclick="foo()"/>
</code>```

But this simple thing that works on pure HTML, with django templates does not seem to work...

On the other hand, the real question was, is there a way to access a Django variable passed in render with a js variable?

Such as:

```<code>const jsVariable = 'title';
document.getElementById('{{form.jsVariable.auto_id}}').value = '{{suggestion.jsVariable}}'
</code>```

I have not found any way to accomplish this, maybe there is another great idea!

答:
Well, finally I found a solution for both exposed problems.

First of all, the script function I declared was not working because it seems that there is an attribute called autocomplete (see autocomplete HTML attribute)
So, you can not declare a JavaScript function with this name, my fail.
Uncaught TypeError: autocomplete is not a function

Finally, the simple solution I found was passing an array of dicts to the template:

return render(request, 'example.html', {'form': form, 'suggestions': suggestions })

And then in the template:

```<code>{% for suggestion in suggestions %}
    <img src="{{ suggestion.poster }}" onclick="autocompleteMovie({{suggestion}});" />
{% endfor %}

<script>
    function autocompleteMovie(suggestion){
        for (let field in suggestion)
            document.getElementById('id_' + field).value = suggestion[field]
    }
</script
</code>```

Which, comparing it with the question, really simplifies the problem.

Body:
First of all, I will like to say this is my first question here! (pardon me if this is redundant or duplicated)

I am having some problems with calling JS scripts from Django template:

{% for suggestion in suggestions %}
    <img class="catalogue-poster" src="{{ suggestion.poster }}" alt="Portada"  onclick="
        document.getElementById('{{form.title.auto_id}}').value = '{{suggestion.title}}'
        document.getElementById('{{form.year.auto_id}}').value = '{{suggestion.year}}'
        document.getElementById('{{form.director.auto_id}}').value = '{{suggestion.director}}'
        document.getElementById('{{form.rating.auto_id}}').value = '{{suggestion.rating}}'
        document.getElementById('{{form.poster.auto_id}}').value = '{{suggestion.poster}}'
        document.getElementById('{{form.trailer.auto_id}}').value = '{{suggestion.trailer}}'
        document.getElementById('{{form.synopsis.auto_id}}').value = '{{suggestion.synopsis}}'
        document.getElementById('{{form.cast.auto_id}}').value = '{{suggestion.cast}}'
    " />
{% endfor %}

So, first of all, how can I declare a function outside. I'm a C developer, sorry for my ignorance.

I've tried to create a script outside, such as

And invoke it this way:

But this simple thing that works on pure HTML, with django templates does not seem to work...

On the other hand, the real question was, is there a way to access a Django variable passed in render with a js variable?

Such as:

const jsVariable = 'title';
document.getElementById('{{form.jsVariable.auto_id}}').value = '{{suggestion.jsVariable}}'

I have not found any way to accomplish this, maybe there is another great idea!

Body:
Well, finally I found a solution for both exposed problems.

First of all, the script function I declared was not working because it seems that there is an attribute called autocomplete (see autocomplete HTML attribute)
So, you can not declare a JavaScript function with this name, my fail.
Uncaught TypeError: autocomplete is not a function

Finally, the simple solution I found was passing an array of dicts to the template:

return render(request, 'example.html', {'form': form, 'suggestions': suggestions })

And then in the template:

{% for suggestion in suggestions %}
    <img src="{{ suggestion.poster }}" onclick="autocompleteMovie({{suggestion}});" />
{% endfor %}

<script>
    function autocompleteMovie(suggestion){
        for (let field in suggestion)
            document.getElementById('id_' + field).value = suggestion[field]
    }
</script

Which, comparing it with the question, really simplifies the problem.


问:
Iterating through JSON objects with missing tags using powershell
Background : I'm trying to iterate through a REST API response and use the information to populate a mysql database. My problem is that some of the objects are missing tags so  the data doesn't align correctly with my current script .

Example of JSON : In this example , espl002 is missing the primary IP address tag.

```<code> {
  "cis" : [ {
    "udbId" : "40000c5e6b84af5588aa066a1569b17e",
    "globalId" : "40000c5e6b84af5588aa066a1569b17e",
    "type" : "netprinter",
    "properties" : {
      "discovered_vendor" : "Fuji Xerox",
      "name" : "xrx9c934e19ffa5",
      "global_id" : "40000c5e6b84af5588aa066a1569b17e",
      "primary_ip_address" : "182.19.323.23"
    }
      }, {
    "udbId" : "400050e64747c97b80a41358b7810c29",
    "globalId" : "400050e64747c97b80a41358b7810c29",
    "type" : "netprinter",
    "properties" : {
      "discovered_vendor" : "Fuji Xerox",
      "name" : "phaser 4510n",
      "global_id" : "400050e64747c97b80a41358b7810c29",
      "primary_ip_address" : "182.19.323.21"
    }
   }, {
    "udbId" : "4ffc72d7151c94ae850837effb45f3c2",
    "globalId" : "4ffc72d7151c94ae850837effb45f3c2",
    "type" : "netprinter",
    "properties" : {
      "discovered_vendor" : "Fuji Xerox",
      "name" : "espl002",
      "global_id" : "4ffc72d7151c94ae850837effb45f3c2",
    }
  } ],
  "relations" : null
}
</code>```

Current code being used :

```<code>[void][System.Reflection.Assembly]::LoadWithPartialName("System.Web.Extensions")
[void][System.Reflection.Assembly]::LoadFrom(“C:\Program Files (x86)\MySQL\MySQL Connector Net 8.0.20\Assemblies\v4.5.2\MySql.Data.dll”)
$token ="eyJ0eXAiOiJKV1QiLCJhbGl0b3J5IjoiVUNNREIiLCJleHAiOjE1ODk4MjgyNzUsImN1c3RvbWVyIjoxLCJ1c2VybmFtZSI6Im1zaW5naCJ9.AsOXTrVu8BIU2XUfk7_fxbMkwhylvBTsRHJ-imuP0mk"
#Total Printers
 $params = @{
    Uri         = 'https://test.ca/rest-api/topology'
    Headers     = @{ 'Authorization' = "Bearer $token" }
    Method      = 'POST'
    Body        = 'totalprinters'
    ContentType = 'application/json'
    Outfile     = 'C:\Users\test\Desktop\API\TOTALPRINTERS.json'
}
Invoke-RestMethod @params
$json  = Get-Content -Raw -Path C:\Users\test\Desktop\API\TOTALPRINTERS.json
$jsonserial = New-Object -TypeName System.Web.Script.Serialization.JavaScriptSerializer
$jsonserial.MaxJsonLength = [int]::MaxValue
$Obj = $jsonserial.DeserializeObject($json)
$Totalprinters= $obj.cis.properties.global_id.count   #Total printers count
$limit = $obj.cis.properties.global_id.count
$Connection = New-Object MySql.Data.MySqlClient.MySqlConnection
$ConnectionString = “server=187.15.43.434;uid=test;pwd=CM123$;database=test;pooling=false”
$Connection.ConnectionString = $ConnectionString
$Connection.Open()

$datasend = For ($i = 0; $i -lt $limit; $i++) {
$nameofprinter=$obj.cis.properties.name[$i]
$ipofprinter=$obj.cis.properties.primary_ip_address[$i]
$manufacturerofprinter=$obj.cis.properties.discovered_vendor[$i]
$Query = "INSERT INTO printers (name,ip,manufacturer, Divison) VALUES ('$nameofprinter','$ipofprinter','$manufacturerofprinter',' ')"
$Command = New-Object MySql.Data.MySqlClient.MySqlCommand($Query, $Connection)
$DataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter($Command)
$DataSet = New-Object System.Data.DataSet
$RecordCount = $dataAdapter.Fill($dataSet, "data")

}
</code>```

Attempt at Solution : From some research , I believe assigning the objects to a hash table would solve my issue then sending this data over to the mysql database. Unfortunately, I'm still learning powershell and not quite sure how to do this in this example.

答:
Thanks for your help everyone , I wasn't streaming each object properly . Modified script and used a hashtable . </p>

```<code>[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls13
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Web.Extensions")
[void][System.Reflection.Assembly]::LoadFrom(“C:\Program Files (x86)\MySQL\MySQL Connector Net 8.0.20\Assemblies\v4.5.2\MySql.Data.dll”)
$Connection = New-Object MySql.Data.MySqlClient.MySqlConnection
$ConnectionString = “server=199.32.3.3;uid=test;pwd=CM$;database=test;pooling=false”
$Connection.ConnectionString = $ConnectionString
$Connection.Open()

$json  = Get-Content -Raw -Path "C:\Users\test\Desktop\API\TOTALPRINTERS.json"

$jsonParts = $json -split "udbId"" :"

for ($part_Index = 1;$part_Index -lt $jsonParts.Length;$part_Index++)
{
$jsonPart = $jsonParts[$part_Index]
$name = ($jsonPart -split """name"" :")[1]
$name = ($name -split """")[1]
$name=$name -replace("'","")

$ip = ($jsonPart -split """primary_ip_address"" :")[1]
$ip = ($ip -split """")[1]

$manufacturer = ($jsonPart -split """discovered_vendor"" :")[1]
$manufacturer = ($manufacturer -split """")[1]

$Division = ""

$Query="INSERT INTO printers(name,ip,manufacturer,Divison) VALUES('$name','$ip','$manufacturer','$Divison')"
$Command = New-Object MySql.Data.MySqlClient.MySqlCommand($Query, $Connection)
$DataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter($Command)
$DataSet = New-Object System.Data.DataSet
$RecordCount = $dataAdapter.Fill($dataSet, "data")
}
</code>```

Body:
Background : I'm trying to iterate through a REST API response and use the information to populate a mysql database. My problem is that some of the objects are missing tags so  the data doesn't align correctly with my current script .

Example of JSON : In this example , espl002 is missing the primary IP address tag.

 {
  "cis" : [ {
    "udbId" : "40000c5e6b84af5588aa066a1569b17e",
    "globalId" : "40000c5e6b84af5588aa066a1569b17e",
    "type" : "netprinter",
    "properties" : {
      "discovered_vendor" : "Fuji Xerox",
      "name" : "xrx9c934e19ffa5",
      "global_id" : "40000c5e6b84af5588aa066a1569b17e",
      "primary_ip_address" : "182.19.323.23"
    }
      }, {
    "udbId" : "400050e64747c97b80a41358b7810c29",
    "globalId" : "400050e64747c97b80a41358b7810c29",
    "type" : "netprinter",
    "properties" : {
      "discovered_vendor" : "Fuji Xerox",
      "name" : "phaser 4510n",
      "global_id" : "400050e64747c97b80a41358b7810c29",
      "primary_ip_address" : "182.19.323.21"
    }
   }, {
    "udbId" : "4ffc72d7151c94ae850837effb45f3c2",
    "globalId" : "4ffc72d7151c94ae850837effb45f3c2",
    "type" : "netprinter",
    "properties" : {
      "discovered_vendor" : "Fuji Xerox",
      "name" : "espl002",
      "global_id" : "4ffc72d7151c94ae850837effb45f3c2",
    }
  } ],
  "relations" : null
}

Current code being used :

[void][System.Reflection.Assembly]::LoadWithPartialName("System.Web.Extensions")
[void][System.Reflection.Assembly]::LoadFrom(“C:\Program Files (x86)\MySQL\MySQL Connector Net 8.0.20\Assemblies\v4.5.2\MySql.Data.dll”)
$token ="eyJ0eXAiOiJKV1QiLCJhbGl0b3J5IjoiVUNNREIiLCJleHAiOjE1ODk4MjgyNzUsImN1c3RvbWVyIjoxLCJ1c2VybmFtZSI6Im1zaW5naCJ9.AsOXTrVu8BIU2XUfk7_fxbMkwhylvBTsRHJ-imuP0mk"
#Total Printers
 $params = @{
    Uri         = 'https://test.ca/rest-api/topology'
    Headers     = @{ 'Authorization' = "Bearer $token" }
    Method      = 'POST'
    Body        = 'totalprinters'
    ContentType = 'application/json'
    Outfile     = 'C:\Users\test\Desktop\API\TOTALPRINTERS.json'
}
Invoke-RestMethod @params
$json  = Get-Content -Raw -Path C:\Users\test\Desktop\API\TOTALPRINTERS.json
$jsonserial = New-Object -TypeName System.Web.Script.Serialization.JavaScriptSerializer
$jsonserial.MaxJsonLength = [int]::MaxValue
$Obj = $jsonserial.DeserializeObject($json)
$Totalprinters= $obj.cis.properties.global_id.count   #Total printers count
$limit = $obj.cis.properties.global_id.count
$Connection = New-Object MySql.Data.MySqlClient.MySqlConnection
$ConnectionString = “server=187.15.43.434;uid=test;pwd=CM123$;database=test;pooling=false”
$Connection.ConnectionString = $ConnectionString
$Connection.Open()

$datasend = For ($i = 0; $i -lt $limit; $i++) {
$nameofprinter=$obj.cis.properties.name[$i]
$ipofprinter=$obj.cis.properties.primary_ip_address[$i]
$manufacturerofprinter=$obj.cis.properties.discovered_vendor[$i]
$Query = "INSERT INTO printers (name,ip,manufacturer, Divison) VALUES ('$nameofprinter','$ipofprinter','$manufacturerofprinter',' ')"
$Command = New-Object MySql.Data.MySqlClient.MySqlCommand($Query, $Connection)
$DataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter($Command)
$DataSet = New-Object System.Data.DataSet
$RecordCount = $dataAdapter.Fill($dataSet, "data")

}

Attempt at Solution : From some research , I believe assigning the objects to a hash table would solve my issue then sending this data over to the mysql database. Unfortunately, I'm still learning powershell and not quite sure how to do this in this example.

Body:
Thanks for your help everyone , I wasn't streaming each object properly . Modified script and used a hashtable .

[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls13
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Web.Extensions")
[void][System.Reflection.Assembly]::LoadFrom(“C:\Program Files (x86)\MySQL\MySQL Connector Net 8.0.20\Assemblies\v4.5.2\MySql.Data.dll”)
$Connection = New-Object MySql.Data.MySqlClient.MySqlConnection
$ConnectionString = “server=199.32.3.3;uid=test;pwd=CM$;database=test;pooling=false”
$Connection.ConnectionString = $ConnectionString
$Connection.Open()

$json  = Get-Content -Raw -Path "C:\Users\test\Desktop\API\TOTALPRINTERS.json"

$jsonParts = $json -split "udbId"" :"

for ($part_Index = 1;$part_Index -lt $jsonParts.Length;$part_Index++)
{
$jsonPart = $jsonParts[$part_Index]
$name = ($jsonPart -split """name"" :")[1]
$name = ($name -split """")[1]
$name=$name -replace("'","")

$ip = ($jsonPart -split """primary_ip_address"" :")[1]
$ip = ($ip -split """")[1]

$manufacturer = ($jsonPart -split """discovered_vendor"" :")[1]
$manufacturer = ($manufacturer -split """")[1]

$Division = ""

$Query="INSERT INTO printers(name,ip,manufacturer,Divison) VALUES('$name','$ip','$manufacturer','$Divison')"
$Command = New-Object MySql.Data.MySqlClient.MySqlCommand($Query, $Connection)
$DataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter($Command)
$DataSet = New-Object System.Data.DataSet
$RecordCount = $dataAdapter.Fill($dataSet, "data")
}


问:
Determine time difference between now and stored date and time
in my sql table I save the date and time of a certain action, how can I print it via php on the contrary, or how long ago did it take place?

for example

```<code>|date                |
|05-28-2020 17:12:05 |
</code>```

and at 17:30:05 it will be written on my php page
"18 minutes ago"

答:
Load the date from the database using a mysqli_query and store the result in $original_date.

Create a date object from the string in the database.

$old_date = new DateTime($original_date);
```

<ol start="3">
<li>Get the current date in the same format and store it in another variable.</li>
</ol>

<pre class="lang-php prettyprint-override"><code>$current_date = new DateTime(date("m-d-Y H:m:s"));
</code>```

Get the difference between the two dates.

$difference = $old_date->diff($current_date);
```

<ol start="5">
<li>Convert the difference to minutes and display message.</li>
</ol>

<pre class="lang-php prettyprint-override"><code>echo($difference->m . "minutes ago");
</code>```

Here is the full code for you to use:

# Get database value and store in $original_date

$old_date = new DateTime($original_date);
$current_date = new DateTime(date("m-d-Y H:m:s"));
$difference = $old_date->diff($current_date);

echo($difference->m . "minutes ago");
```

Body:
in my sql table I save the date and time of a certain action, how can I print it via php on the contrary, or how long ago did it take place?

for example

|date                |
|05-28-2020 17:12:05 |

and at 17:30:05 it will be written on my php page
"18 minutes ago"

Body:
Load the date from the database using a mysqli_query and store the result in $original_date.

Create a date object from the string in the database.

$old_date = new DateTime($original_date);

Get the current date in the same format and store it in another variable.

$current_date = new DateTime(date("m-d-Y H:m:s"));

Get the difference between the two dates.

$difference = $old_date->diff($current_date);

Convert the difference to minutes and display message.

echo($difference->m . "minutes ago");

Here is the full code for you to use:

# Get database value and store in $original_date

$old_date = new DateTime($original_date);
$current_date = new DateTime(date("m-d-Y H:m:s"));
$difference = $old_date->diff($current_date);

echo($difference->m . "minutes ago");


问:
How to minimize the size of a flutter app
I was creating a flutter app without adding any thing to it and try launching it.
The problem is, size of the flutter app that was created is 65.88MB

Are these the flaws of flutter or not?

答:
I feel like you should give this a try, sometimes what happens is, you don't clear out your previous data and try to build the apk, which gives out more heavy file.

Always follow the below steps, and you will get a lighter file in respect of size.

Go to your console -> go inside your project directory -> type the following:

```<code> 1. flutter clean
 2. flutter build apk --release
</code>```

Now what the above command does, flutter clean, cleans up the previous data stored in the build file. Deletes build file

flutter build apk --release, builds the android apk in the release mode. It is generally lighter than the debug mode.

For more info on releasing the Android installation file, please follow this: Building Flutter Android App

Body:
I feel like you should give this a try, sometimes what happens is, you don't clear out your previous data and try to build the apk, which gives out more heavy file.

Always follow the below steps, and you will get a lighter file in respect of size.

Go to your console -> go inside your project directory -> type the following:

 1. flutter clean
 2. flutter build apk --release

Now what the above command does, flutter clean, cleans up the previous data stored in the build file. Deletes build file

flutter build apk --release, builds the android apk in the release mode. It is generally lighter than the debug mode.

For more info on releasing the Android installation file, please follow this: Building Flutter Android App


问:
Oracle SQL - How to merge multiple columns into new one
I need to merge multiple columns (there are quite a lot of columns and rows) into new one column.

Eg. shortened test_table

```<code>Col1    Col2    Col3    Col4    Col5    Col6
942 72987   14759   441277503   73553030    null
943 72987   14759   441278315   73553166    null
944 72987   14759   441362593   73570082    null
945 72987   14759   441380217   73572619    null
946 72987   14759   441394189   73574533    null
947 72987   14759   441394189   73574533    null
</code>```

and I'd like to merge Col1-Col5 with comma separator (",") and put created String into Col6

So in Col6 I'd like to have eg:
942,72987,14759,441277503,73553030

Is there any solution how can I do it in SQL / PL/SQL?
As I said there are a lot of column so I'd like to avoid to add them manually by using Col1 || Col2 || Col3 || Col4 || Col5

Thanks in advance,
Michał

答:
Try PL/SQL block like this:</p>

```<code>SET SERVEROUT ON
DECLARE
    LV_COLUMNS VARCHAR2(20000);
BEGIN
    SELECT LISTAGG('CASE WHEN ' || COLUMN_NAME || ' IS NOT NULL THEN ' || COLUMN_NAME || ' || '',''|| '
      || 'ELSE NULL END'
      , '||') WITHIN GROUP(ORDER BY COLUMN_ID)
      INTO LV_COLUMNS
      FROM USER_TAB_COLS
     WHERE TABLE_NAME = 'YOUR_TABLE_NAME'
       AND COLUMN_NAME <> 'COL6'
       AND HIDDEN_COLUMN = 'NO';

    DBMS_OUTPUT.PUT_LINE('UPDATE YOUR_TABLE_NAME SET COL6 = TRIM('','' FROM (' || LV_COLUMNS || '))');
    EXECUTE IMMEDIATE 'UPDATE YOUR_TABLE_NAME SET COL6 = TRIM('','' FROM (' || LV_COLUMNS || '))';
    COMMIT;
END;
/
</code>```

Body:
I need to merge multiple columns (there are quite a lot of columns and rows) into new one column.

Eg. shortened test_table

Col1    Col2    Col3    Col4    Col5    Col6
942 72987   14759   441277503   73553030    null
943 72987   14759   441278315   73553166    null
944 72987   14759   441362593   73570082    null
945 72987   14759   441380217   73572619    null
946 72987   14759   441394189   73574533    null
947 72987   14759   441394189   73574533    null

and I'd like to merge Col1-Col5 with comma separator (",") and put created String into Col6

So in Col6 I'd like to have eg:
942,72987,14759,441277503,73553030

Is there any solution how can I do it in SQL / PL/SQL?
As I said there are a lot of column so I'd like to avoid to add them manually by using Col1 || Col2 || Col3 || Col4 || Col5

Thanks in advance,
Michał

Body:
Try PL/SQL block like this:

SET SERVEROUT ON
DECLARE
    LV_COLUMNS VARCHAR2(20000);
BEGIN
    SELECT LISTAGG('CASE WHEN ' || COLUMN_NAME || ' IS NOT NULL THEN ' || COLUMN_NAME || ' || '',''|| '
      || 'ELSE NULL END'
      , '||') WITHIN GROUP(ORDER BY COLUMN_ID)
      INTO LV_COLUMNS
      FROM USER_TAB_COLS
     WHERE TABLE_NAME = 'YOUR_TABLE_NAME'
       AND COLUMN_NAME <> 'COL6'
       AND HIDDEN_COLUMN = 'NO';

    DBMS_OUTPUT.PUT_LINE('UPDATE YOUR_TABLE_NAME SET COL6 = TRIM('','' FROM (' || LV_COLUMNS || '))');
    EXECUTE IMMEDIATE 'UPDATE YOUR_TABLE_NAME SET COL6 = TRIM('','' FROM (' || LV_COLUMNS || '))';
    COMMIT;
END;
/


问:
unable to install the python library "requests" on windows 7
Encountering error while running the command

```<code>pip install requests
</code>```

or

```<code>pip3 install requests
</code>```

same error while installing any other python package on this system. Do I need to get any port opened on this system?

```<code>Collecting requests
  WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, stat
us=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL
: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate
in certificate chain (_ssl.c:1108)'))': /simple/requests/
  WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, stat
us=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL
: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate
in certificate chain (_ssl.c:1108)'))': /simple/requests/
  WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, stat
us=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL
: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate
in certificate chain (_ssl.c:1108)'))': /simple/requests/
  WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, stat
us=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL
: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate
in certificate chain (_ssl.c:1108)'))': /simple/requests/
  WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, stat
us=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL
: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate
in certificate chain (_ssl.c:1108)'))': /simple/requests/
  Could not fetch URL https://pypi.org/simple/requests/: There was a problem con
firming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max
 retries exceeded with url: /simple/requests/ (Caused by SSLError(SSLCertVerific
ationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self
signed certificate in certificate chain (_ssl.c:1108)'))) - skipping
  ERROR: Could not find a version that satisfies the requirement requests (from
versions: none)
ERROR: No matching distribution found for requests
Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming
 the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retrie
s exceeded with url: /simple/pip/ (Caused by SSLError(SSLCertVerificationError(1
, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certi
ficate in certificate chain (_ssl.c:1108)'))) - skipping
</code>```

答:
as suspected the issue was with the firewall. But the way i had to resolve is by finding the authorized process though which I can install libraries in my organization.
Regards
KK</p>

Body:
Encountering error while running the command

pip install requests

or

pip3 install requests

same error while installing any other python package on this system. Do I need to get any port opened on this system?

Collecting requests
  WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, stat
us=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL
: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate
in certificate chain (_ssl.c:1108)'))': /simple/requests/
  WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, stat
us=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL
: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate
in certificate chain (_ssl.c:1108)'))': /simple/requests/
  WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, stat
us=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL
: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate
in certificate chain (_ssl.c:1108)'))': /simple/requests/
  WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, stat
us=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL
: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate
in certificate chain (_ssl.c:1108)'))': /simple/requests/
  WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, stat
us=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL
: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate
in certificate chain (_ssl.c:1108)'))': /simple/requests/
  Could not fetch URL https://pypi.org/simple/requests/: There was a problem con
firming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max
 retries exceeded with url: /simple/requests/ (Caused by SSLError(SSLCertVerific
ationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self
signed certificate in certificate chain (_ssl.c:1108)'))) - skipping
  ERROR: Could not find a version that satisfies the requirement requests (from
versions: none)
ERROR: No matching distribution found for requests
Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming
 the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retrie
s exceeded with url: /simple/pip/ (Caused by SSLError(SSLCertVerificationError(1
, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certi
ficate in certificate chain (_ssl.c:1108)'))) - skipping


问:
How to print the " symbol in python
How do I print " symbol in python.

My code: print(f"{filefolder}" ", uid, " f"{usergroup}" " mode, " f"{permissions}" f"{capability}" f"{contexts}")

For example one of the outputs: acct, uid, 0000 0000 mode, 0755 u:object_r:cgroup:s0

But I need say, uid to be "uid". I've tried adding the "" around uid, but I get a syntax error.

答:
Escape the quote mark using a backslash, use single quotes, or use a raw triple quotes:

print("\"uid\"")
```

<pre class="lang-py prettyprint-override"><code>print('"uid"')
</code>```

print(r""""uid"""")
```

Title: How to print the " symbol in python

Body:
Escape the quote mark using a backslash, use single quotes, or use a raw triple quotes:

print("\"uid\"")

print('"uid"')

print(r""""uid"""")


问:
How to extract data from HDF file?
I have an HDF file (.h5) which has the following hierarchy

I have never worked with this kind of data. I think that 'barcodes' should be my columns and 'features/names' should be my rows, 'data' should be the values. How do I extract it in the form of a barcodesXnames dataframe preferably in Python?

I tried this

```<code>    filename = "filtered_feature_bc_matrix.h5"

    with h5py.File(filename, "r") as f:
    data = f.get('matrix/data')
    dataset=np.array(data)
    print(dataset)
</code>```

but it gives me an array of data like [1 1 1 ... 2 1 2]

答:
I'm going to start with an introduction to HDF5 data schema/objects. You need to understand this to work effectively with HDF5 data. There are 2 basic entities: 1) Groups and 2) Datasets. They are similar to Folders and Files on your computer. Groups are like Folders, and Datasets are like Files that hold data. (Note: Neither of these are columns or row names -- you get that info by interrogating each dataset).

Groups use a Folder icon in your image of the file layout. You have 2 Groups.

They are:

```<code>/matrix
/matrix/features
</code>```

Datasets have a different icon. You have 10 Datasets, 5 saved under each Group.

They are:

```<code>/matrix/barcodes
/matrix/data
/matrix/indices
/matrix/indptr
/matrix/shape

/matrix/features/_all_tag_keys
/matrix/features/feature_name
/matrix/features/genome
/matrix/features/id
/matrix/features/name
</code>```

I created a simple example to interrogate your model and output Groups/Datasets. In addition, it outputs the dtype and shape for datasets. This should help you pragmatically "see" what you have and compare to your image.

Dtype is the datatypes (int, float, string), and the field/column
names (if they are defined).

Shape depends on the dataset definition. For simple NumPy arrays, it is the dimension in all directions. For mixed datatypes (record arrays) it is the number of rows.

Code segment below:

```<code>import h5py

def visitor_func(name, node):
    if isinstance(node, h5py.Group):
        print(node.name, 'is a Group')
    elif isinstance(node, h5py.Dataset):
       if (node.dtype == 'object') :
            print (node.name, 'is an Object Dataset')
       else:
            print(node.name, 'is a Dataset')
            print ('Dataset dtype=', node.dtype)
            print ('Dataset shape=', node.shape)

    else:
        print('Node is unknown type: ', node.name)

print ('testing hdf5 file')
with h5py.File('filtered_feature_bc_matrix.h5','r') as h5f:
    h5f.visititems(visitor_func)
</code>```

Title: How to extract data from HDF file?

Body:
I have an HDF file (.h5) which has the following hierarchy

I have never worked with this kind of data. I think that 'barcodes' should be my columns and 'features/names' should be my rows, 'data' should be the values. How do I extract it in the form of a barcodesXnames dataframe preferably in Python?

I tried this

    filename = "filtered_feature_bc_matrix.h5"

    with h5py.File(filename, "r") as f:
    data = f.get('matrix/data')
    dataset=np.array(data)
    print(dataset)

but it gives me an array of data like [1 1 1 ... 2 1 2]

Body:
I'm going to start with an introduction to HDF5 data schema/objects. You need to understand this to work effectively with HDF5 data. There are 2 basic entities: 1) Groups and 2) Datasets. They are similar to Folders and Files on your computer. Groups are like Folders, and Datasets are like Files that hold data. (Note: Neither of these are columns or row names -- you get that info by interrogating each dataset).

Groups use a Folder icon in your image of the file layout. You have 2 Groups.

They are:

/matrix
/matrix/features

Datasets have a different icon. You have 10 Datasets, 5 saved under each Group.

They are:

/matrix/barcodes
/matrix/data
/matrix/indices
/matrix/indptr
/matrix/shape

/matrix/features/_all_tag_keys
/matrix/features/feature_name
/matrix/features/genome
/matrix/features/id
/matrix/features/name

I created a simple example to interrogate your model and output Groups/Datasets. In addition, it outputs the dtype and shape for datasets. This should help you pragmatically "see" what you have and compare to your image.

Dtype is the datatypes (int, float, string), and the field/column
names (if they are defined).

Shape depends on the dataset definition. For simple NumPy arrays, it is the dimension in all directions. For mixed datatypes (record arrays) it is the number of rows.

Code segment below:

import h5py

def visitor_func(name, node):
    if isinstance(node, h5py.Group):
        print(node.name, 'is a Group')
    elif isinstance(node, h5py.Dataset):
       if (node.dtype == 'object') :
            print (node.name, 'is an Object Dataset')
       else:
            print(node.name, 'is a Dataset')
            print ('Dataset dtype=', node.dtype)
            print ('Dataset shape=', node.shape)

    else:
        print('Node is unknown type: ', node.name)

print ('testing hdf5 file')
with h5py.File('filtered_feature_bc_matrix.h5','r') as h5f:
    h5f.visititems(visitor_func)


问:
TornadoFX _ Kotlin _ IntelliJ IDEA: How is it possible that I am getting an "Unresolved reference: javafx" since I am using openJDK 8 in my project?
I am trying to get start with Kotlin and TornadoFX.

I have download Java jdk8u252-b09 and set it as my project SDK. See the following image:

I have seen this post that inform us that the Unresolved reference: javafx's bugg is linked to the fact of running a version of Java greater or equal to v11 without importing JavaFX in the project.
I have read the v8 of Java come with JavaFX integrated. And in my project as I have already said, I am running Java 1.8 as SDK. So this problem should be prevented to occur.

Still, when I "debug run" my debug console returns me:

Unresolved reference: javafx

as in the following image:

The only place I see that could be problematic is the software running in my machine. When I am running java --version in a linux terminal it returns me:

openjdk 11.0.7 2020-04-14

Since I am on Debian Buster it seems openjdk 11 is the oldest version supported by the OS-version. So if the problem is linked to the openjdk installed in the system I am wondering if there is any workaround beside running a virtual machine. Also I would think that the SDK installed in IntelliJ IDEA would overcome the Java version installed in my system in the context of my project, hence preventing the software installed in my machine to cause any problem to run my project.

So how my bugg is possible? What can I do to fix that?

答:
I have found that most OpenJDK8s do not include JavaFX.  I know of two that do that you may want to try to make future updates easier:

Zulu : You must select "JDK FX" in the Java Package drop down

Liberica: You must select "Full JDK"

Liberica provides builds for raspberry pi and a wide variety of other architectures. If you need that, Liberica is the way to go.


问:
printing array not working
hello everyone i am printing array from the database in the following format

```<code>Array ( [0] => 14
        [task_id] => 14
        [1] => 123
        [user_id] => 123
        [2] => 456
        [employee_id] => 456
        [3] => 2
        [service_id] => 2
        [4] => 2:00 AM
        [starttime] => 2:00 AM
        [5] => 4:00 AM
        [endtime] => 4:00 AM
        [6] => se a
        [servicename] => se a
        [7] => ddsdsd
        [servicedescription] => ddsdsd
        [8] => dsd
        [employeename] => dsd
        [9] => pictures/noimage.gif
        [employeepicture] => pictures/noimage.gif
        [10] => pictures/noimage.gif
        [pic_path] => pictures/noimage.gif )
</code>```

It is the result of

```<code>$rd = $this->executeQuery();
$recordsArray = array();
while (($row = mysqli_fetch_array($rd)) ){
$recordsArray[] = $row;
</code>```

problem is how can i pick the single record from it like this

```<code>echo $row[$task_id]; // not working
</code>```

Thanks

答:
It's won't work, because you need to iterate the whole $recordsArray to the the right $row.

You can solve this by saving a row as an hash in the $recordsArray instead of an enumurated array like this:

```<code>$recordsArray[$row['task_id']] = $row;
</code>```

Now you can fetch the row from the records array like this:

```<code>$recordsArray[$task_id];
</code>```

(provided that $task_id exists).

Title: printing array not working

Body:
hello everyone i am printing array from the database in the following format

Array ( [0] => 14
        [task_id] => 14
        [1] => 123
        [user_id] => 123
        [2] => 456
        [employee_id] => 456
        [3] => 2
        [service_id] => 2
        [4] => 2:00 AM
        [starttime] => 2:00 AM
        [5] => 4:00 AM
        [endtime] => 4:00 AM
        [6] => se a
        [servicename] => se a
        [7] => ddsdsd
        [servicedescription] => ddsdsd
        [8] => dsd
        [employeename] => dsd
        [9] => pictures/noimage.gif
        [employeepicture] => pictures/noimage.gif
        [10] => pictures/noimage.gif
        [pic_path] => pictures/noimage.gif )

It is the result of

$rd = $this->executeQuery();
$recordsArray = array();
while (($row = mysqli_fetch_array($rd)) ){
$recordsArray[] = $row;

problem is how can i pick the single record from it like this

echo $row[$task_id]; // not working

Thanks

Body:
It's won't work, because you need to iterate the whole $recordsArray to the the right $row.

You can solve this by saving a row as an hash in the $recordsArray instead of an enumurated array like this:

$recordsArray[$row['task_id']] = $row;

Now you can fetch the row from the records array like this:

$recordsArray[$task_id];

(provided that $task_id exists).


问:
How to use animated material icons in vuetify
By the v-icon component of Vuetify, using mainstream material design icons is quite straightforward like:

```<code><v-icon>home</v-icon>
</code>```

Now, I wonder if animated material icons are supported and can be used in Vuetify in a similar fashion -I mean without having to add extra lines of css code etc. if possible.

In the examples, I have noticed the usage of fa-spin for Font Awesome; yet it is out of scope. I am bound to Google's material icons library.

EDIT: The specific kind of behavior I need is in the video examples in transitions section here: https://material.io/design/iconography/animated-icons.html# [See how a play button becomes pause with a smooth animation when clicked].

答:
I found this page when I wanted to mimic the animation of the chevron icon when toggling the expansion panels within a v-menu icon. I am not sure if this is exactly what you needed, but this is how I've done it:</p>

```<code><template>
  <v-menu offset-y v-model="menuValue">
    <template v-slot:activator="{ on }">
      <v-btn v-on="on" :class="{active: menuValue}">
        <v-icon>mdi-chevron-down</v-icon>
      </v-btn>
    </template>
  </v-menu>
</template>

<script>
  export default {
    data() {
      return {
        menuValue: null
      };
    }
  };
</script>

<style lang="scss" scoped>
  .v-btn.active .v-icon {
    transform: rotate(-180deg);
  }
</style>
</code>```

Body:
By the v-icon component of Vuetify, using mainstream material design icons is quite straightforward like:

<v-icon>home</v-icon>

Now, I wonder if animated material icons are supported and can be used in Vuetify in a similar fashion -I mean without having to add extra lines of css code etc. if possible.

In the examples, I have noticed the usage of fa-spin for Font Awesome; yet it is out of scope. I am bound to Google's material icons library.

EDIT: The specific kind of behavior I need is in the video examples in transitions section here: https://material.io/design/iconography/animated-icons.html# [See how a play button becomes pause with a smooth animation when clicked].

Body:
I found this page when I wanted to mimic the animation of the chevron icon when toggling the expansion panels within a v-menu icon. I am not sure if this is exactly what you needed, but this is how I've done it:

<template>
  <v-menu offset-y v-model="menuValue">
    <template v-slot:activator="{ on }">
      <v-btn v-on="on" :class="{active: menuValue}">
        <v-icon>mdi-chevron-down</v-icon>
      </v-btn>
    </template>
  </v-menu>
</template>

<script>
  export default {
    data() {
      return {
        menuValue: null
      };
    }
  };
</script>

<style lang="scss" scoped>
  .v-btn.active .v-icon {
    transform: rotate(-180deg);
  }
</style>


问:
Impersonate User in ASP.Net Core Web Api
I am planning a public Web Api in ASP.Net Core. Also there is a database connected and sign on is planned as well.

There is a connection from my application to the database open using Integrated Security=True;. Is it possible to connect to the database using a different user (from active directory). Not the one under which the application is running, but any other user from Active Diretory.

My understandin is:

The application runs as a certain user. Integrated Security=True; will open a connection as that user -> Not possible.

Impersonation of another user requires the app to have elevated rights and know the password from that user -> Not an option.

Doing it without a password means the applications right have to be elevated to the highest possible -> not an option.

So is there any way to connect to the database as a certain user from our AD? I have the feeling it's not possible.

Thank you!

答:
Is that MSDN Article what you are looking for?

ASP.NET Core doesn't implement impersonation. Apps run with the app's
  identity for all requests, using app pool or process identity. If the
  app should perform an action on behalf of a user, use
  WindowsIdentity.RunImpersonated in a terminal inline middleware in
  Startup.Configure. Run a single action in this context and then close
  the context.


问:
add image to uitableview cell
I have a tableview, how can I add image to the left of this cells?

答:
Swift 5 solution</p>

```<code>cell.imageView?.image = UIImage.init(named: "yourImageName")
</code>```

Title: add image to uitableview cell

Body:
Swift 5 solution

cell.imageView?.image = UIImage.init(named: "yourImageName")