问:
How to redirect URL via JavaScript based on a number (if 1, redirect to A; if 2, to B...)
I want to redirect a visitor based on a variable in their URL. Use case is a quiz with Gravity Forms where the user will be redirected to example.com/processing?quizresult={n}

Where n is a numerical value (0-50).

There are 3 possible outcomes (0-15, 16-30, 31-50).

I’ve found JavaScript to redirect based on if a URL contains a variable, but not a range of variables. Is there a better way than 50 “IF” statements?

```<code><script>
if(document.location.href.indexOf('1') > -1) {
    document.location.href = 'http://www.example.com/resultA';
}

if(document.location.href.indexOf('2') > -1) {
    document.location.href = 'http://www.example.com/resultA';
}

if(document.location.href.indexOf('3') > -1) {
    document.location.href = 'http://www.example.com/resultA';
}
</code>```

答:
Try this:

Extract {n} from your url string

Conditionally redirect according to
the value of n

Example:

```<code>// extract {n} from example.com/processing?quizresult={n}
const getParamValue = (url, parameterKey) => {
  const [urlWithoutParameters, parameters = ''] = url.split('?'); // ['example.com/processing', 'quizresult=1']
  const paramsArr = parameters.split('&'); // ['quizresult=1']

  for (let i = 0; i < paramsArr.length; i++) {
    const [k, v] = paramsArr[i].split('='); // k = 'quizresult', v = '1'
    if (k === parameterKey) {
      return v;
    }
  }
};

// conditionally redirect to the result urls.
const conditionallyRedirect = (url) => {
  const quizResult = getParamValue(url, 'quizresult');
  if (quizResult >= 0 && quizResult < 16) {
    console.log('resultA');
    // document.location.href = 'http://www.example.com/resultA';
  } else if (quizResult >= 16 && quizResult < 31) {
    console.log('resultB');
    // document.location.href = 'http://www.example.com/resultB';
  } else if (quizResult >= 31 && quizResult <= 50) {
    console.log('resultC');
    // document.location.href = 'http://www.example.com/resultC';
  }
  // do not redirect otherwise
};

// Examples
conditionallyRedirect('example.com/processing?quizresult=1'); // redirects to resultA
conditionallyRedirect('example.com/processing?quizresult=17&someotherparam=whatever'); // redirects to resultB
conditionallyRedirect('example.com/processing'); // does not redirect
conditionallyRedirect('example.com/processing?quizresult=100'); // does not redirect
</code>```

So this would work for you:

```<code>conditionallyRedirect(document.location.href);
</code>```

Body:
Try this:

Extract {n} from your url string

Conditionally redirect according to
the value of n

Example:

// extract {n} from example.com/processing?quizresult={n}
const getParamValue = (url, parameterKey) => {
  const [urlWithoutParameters, parameters = ''] = url.split('?'); // ['example.com/processing', 'quizresult=1']
  const paramsArr = parameters.split('&'); // ['quizresult=1']

  for (let i = 0; i < paramsArr.length; i++) {
    const [k, v] = paramsArr[i].split('='); // k = 'quizresult', v = '1'
    if (k === parameterKey) {
      return v;
    }
  }
};

// conditionally redirect to the result urls.
const conditionallyRedirect = (url) => {
  const quizResult = getParamValue(url, 'quizresult');
  if (quizResult >= 0 && quizResult < 16) {
    console.log('resultA');
    // document.location.href = 'http://www.example.com/resultA';
  } else if (quizResult >= 16 && quizResult < 31) {
    console.log('resultB');
    // document.location.href = 'http://www.example.com/resultB';
  } else if (quizResult >= 31 && quizResult <= 50) {
    console.log('resultC');
    // document.location.href = 'http://www.example.com/resultC';
  }
  // do not redirect otherwise
};

// Examples
conditionallyRedirect('example.com/processing?quizresult=1'); // redirects to resultA
conditionallyRedirect('example.com/processing?quizresult=17&someotherparam=whatever'); // redirects to resultB
conditionallyRedirect('example.com/processing'); // does not redirect
conditionallyRedirect('example.com/processing?quizresult=100'); // does not redirect

So this would work for you:

conditionallyRedirect(document.location.href);


来源: stackexchange

问:
Bitshift operations and bitmask not detecting duplicate characters
I've been trying to write a program that checks for duplicate letters in a lowercase input using a bitmask. However, the program returns true regardless of the presence of a duplicate letter. The code is as follows:</p>

```<code>#include <iostream>
#include <cctype>
#include <cstring>

using namespace std;

bool all_unique_letters(const string &s) {
    int bitset;

    for(char const &c : s)
    {
        unsigned char set = 1 << (c - 'a');

        if(set & bitset)
            return false;

        bitset |= set;
    }

    return true;
}

int main(int argc, char * const argv[]) {
    // TODO: reads and parses command line arguments.
    // Calls other functions to produce correct output.
    if(all_unique_letters(argv[1]))
        cout << "All letters are unique!" << endl;
    else
        cout << "Duplicate letters found." << endl;
}
</code>```

答:
I see two problems. First your bitset variable is uninitialized. Second, the type for your set variable is unsigned char an 8-bit type. For a lower-case alphabet you need at least 26 bits to test against your bitset. After fixing both issues your code seems to work.

```<code>bool all_unique_letters(const string &s) {
    int bitset = 0; // fixed

    for(char const &c : s)
    {
        int set = 1 << (c - 'a'); // fixed

        if(set & bitset)
            return false;

        bitset |= set;
    }
    return true;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've been trying to write a program that checks for duplicate letters in a lowercase input using a bitmask. However, the program returns true regardless of the presence of a duplicate letter. The code is as follows:

#include <iostream>
#include <cctype>
#include <cstring>

using namespace std;

bool all_unique_letters(const string &s) {
    int bitset;

    for(char const &c : s)
    {
        unsigned char set = 1 << (c - 'a');

        if(set & bitset)
            return false;

        bitset |= set;
    }

    return true;
}

int main(int argc, char * const argv[]) {
    // TODO: reads and parses command line arguments.
    // Calls other functions to produce correct output.
    if(all_unique_letters(argv[1]))
        cout << "All letters are unique!" << endl;
    else
        cout << "Duplicate letters found." << endl;
}

Body:
I see two problems. First your bitset variable is uninitialized. Second, the type for your set variable is unsigned char an 8-bit type. For a lower-case alphabet you need at least 26 bits to test against your bitset. After fixing both issues your code seems to work.

bool all_unique_letters(const string &s) {
    int bitset = 0; // fixed

    for(char const &c : s)
    {
        int set = 1 << (c - 'a'); // fixed

        if(set & bitset)
            return false;

        bitset |= set;
    }
    return true;
}


问:
What is the difference between driver.findElement() and driver.findElements()?
In driver.findElements() we get another function for finding size() which is not available in driver.findElement().

Is it the only difference?

答:
findElement is used to find the first matching element with the specified locator in the HTML page.

findElement's return type is WebElement.

findElement will throw an error if the specified locator is not find in the loaded web page.

ContentLicense: CC BY-SA 3.0


问:
Nginx: Prevent direct access to static files
I've been searching for a while now but didn't manage to find anything that fits my needs. I don't need hotlinking protection, as much as I'd like to prevent people from directly accessing my files. Let's say:

My website.com requests website.com/assets/custom.js, that'd work,but I'd like visitors which directly visit this file to get a 403 status code or something. I really have no idea if it's possible, and I don't have any logical steps in mind..

Regards !

答:
You can simply deny access to any folder or file just by putting these lines with your folders' name</p>

```<code>location ~ /(no_access_folder|folder_2)
{
     deny all;
     return 403;
}
</code>```

Body:
You can simply deny access to any folder or file just by putting these lines with your folders' name

location ~ /(no_access_folder|folder_2)
{
     deny all;
     return 403;
}


问:
How to change color of part of dynamic string in swift %@?
I am using the following placeholder in my string: %@

For instance my string is String(format: "greetings %@", str)

How can I provide a specific color for this dynamic placeholder?

答:
You can modify the attributes for a NSRange within an attributed string. But rather than build it with a format string and retroactively going back and updating the attributes for a NSRange, I’d just create an attributed string for the string to be appended, setting its attributes before you append it:

```<code>let name = NSAttributedString(string: str, attributes: [.foregroundColor: UIColor.green])

let greeting = NSMutableAttributedString(string: "greetings ")
greeting.append(name)

label.attributedText = greeting
</code>```

That yields:

Body:
You can modify the attributes for a NSRange within an attributed string. But rather than build it with a format string and retroactively going back and updating the attributes for a NSRange, I’d just create an attributed string for the string to be appended, setting its attributes before you append it:

let name = NSAttributedString(string: str, attributes: [.foregroundColor: UIColor.green])

let greeting = NSMutableAttributedString(string: "greetings ")
greeting.append(name)

label.attributedText = greeting

That yields:


问:
Firebase Functions HTTPS 403 Forbidden
I built a Firebase HTTP Event function with Node and Express. The function is working, but when I invoke the function on the client side I get 403 Forbidden. The first time I invoked the function I was asked to sign in with a Google account. I signed in with the same account I use for Firebase, but when I invoked the function I got:

Screenshot of 403 error

I looked at the use roles on Google cloud platform and the permission to invoke the function is set to allUsers. I signed out and back in again in the Firebase CLI.

Here is the index.js in the functions folder:

const functions = require('firebase-functions');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const port = process.env.port || 5600
const nodemailer = require('nodemailer');

app.use(express.static('Public'));

app.use(bodyParser.urlencoded({ extended: true }));

const urlencodedParser = bodyParser.urlencoded({extended: true});

app.post("/api/user", urlencodedParser, (req, res) => {
  res.sendFile('../Public/bedankt.html', {root: __dirname})
  const persGegevens = req.body

  const string = JSON.stringify(persGegevens, (key, value) => {
    if (typeof value === "string"){
      return value.toUpperCase();
    } else {
      return value
    }
  }, 1);

  var transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
      user: 'gietvloermakers@gmail.com',
      pass: 'Gietvloermakers2020!'
    }
  });

  var mailOptions = {
    from: 'gietvloermakers@gmail.com',
    to: 'gvbeusekom84@hotmail.com',
    subject: 'Nieuwe bestelling op Gietvloermakers',
    html: string
  };

  transporter.sendMail(mailOptions, function(error, info){
    if (error) {
      console.log(error);
    } else {
      console.log('Email sent: ' + info.response);
    }
  });
});

exports.app1 = functions.https.onRequest(app);

app.listen(port);

console.log(port);
```

<p>Here is the html:</p>

<pre class="lang-html prettyprint-override"><code><form id="controlleer-form" action="/api/user" method="post" enctype="application/x-www-form-urlencoded">
    <div class="controleer-div">
        <h2>Uw bestelling</h2>
        <p>Aantal m2</p>
        <input class="controle-input" type="text" name="aantalM2" id="aantalM2" readonly>
        <p>Kleur</p>
        <input class="controle-input" type="text" name="kleur" id="kleur" readonly>
        <p>Assistentie</p>
        <input class="controle-input" type="text" name="assistentie" id="assistentie" readonly>
        <p>Gereedschappen</p>
        <input class="controle-input" type="text" name="gereedschappen" id="gereedschappen" readonly>
        <p>Totale prijs</p>
        <input  class="controle-input" type="text" name="totale-prijs" id="totale-prijs" readonly>
        <p id="andere-kleur">Bestelling aanpassen</p>
    </div>
    <div class="controleer-div">
        <h2>Uw gegevens</h2>
        <p>Voornaam</p>
        <input type="text" name="voornaam" placeholder="Voornaam">
        <p>Achternaam</p>
        <input type="text" name="Achternaam" placeholder="Achternaam">
        <p>Straatnaam en huisnummer</p>
        <input type="text" name="Achternaam" placeholder="Straatnaam en huisnummer">
        <p>Postcode</p>
        <input type="text" name="Achternaam" placeholder="Postcode">
        <p>Telefoonnummer</p>
        <input type="tel" name="telefoonnummer" placeholder="Telefoonnummer">
        <p>Emailadres</p>
        <input type="email" name="email" placeholder="Emailadres"><br>
        <input id="verzenden" type="submit">
    </div>
</form>
</code>```

Here is the firebase.json:

```<code>{
  "hosting": {
    "public": "Public",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [{
      "source": "**",
      "function": "app1"
    }]
  }
}
</code>```

I tried but I exhausted all possible solutions I've found online so far.

答:
Your code exports the express application as the Cloud Function app1 on this line:

exports.app1 = functions.https.onRequest(app);
```

<p>In your screenshot, you have tried to access the non-existent <code>app</code> Cloud Function instead resulting in the <code>403 Forbidden</code> response.</p>

<p>This means the correct URL to call from your client is</p>

<pre class="lang-none prettyprint-override"><code>http://us-central1-gietvloermakers.cloudfunctions.net/app1/api/user
                                                      ^^^^
</code>```

(or you could change the name of the export to app)

Having a closer look at your source code, you should also remove the following lines. If you wanted to test your code you would instead use firebase serve.

```<code>const port = process.env.port || 5600
/* ... */
app.listen(port);
</code>```

On the following lines, you also inject the body parser twice.

```<code>app.use(bodyParser.urlencoded({ extended: true })); // use this

const urlencodedParser = bodyParser.urlencoded({extended: true}); // or this, not both

app.post("/api/user", urlencodedParser, ...
</code>```

In your code, you also have:

```<code>app.post("/api/user", urlencodedParser, (req, res) => {
  res.sendFile('../Public/bedankt.html', {root: __dirname})
  /* do some other stuff */
})
</code>```

This is invalid for a Cloud Function, because as soon as the Cloud Function handler (your code) calls end(), redirect() or send(), the Cloud Function is allowed to be terminated at any time which means that your email may never be sent. To fix this you need to send the file last.

```<code>app.post("/api/user", urlencodedParser, (req, res) => {
  /* do some other stuff */
  res.sendFile('../Public/bedankt.html', {root: __dirname})
});
</code>```

My last observation, is that the error may be caused by the folder Public not existing on the server. Based on your sendFile call, you are expecting that the folder "Public" is available to your deployed function but as it is not inside the functions folder, it will not be deployed with your code.

```<code>res.sendFile('../Public/bedankt.html', {root: __dirname})
</code>```

As this file would also be accessible at your-domain.com/bedankt.html, we'll redirect to it. If you wanted to send the HTML content of this file instead, move it inside your deployed functions directory.

```<code>res.redirect('/bedankt.html')
</code>```

Because you appear to be trying to use your express function behind Firebase hosting, we can trim your index.js file to the following:

```<code>const functions = require('firebase-functions');
const express = require('express');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');

const apiApp = express();

apiApp.use(bodyParser.urlencoded({ extended: true }));

apiApp.post("/api/user", (req, res) => {
  const persGegevens = req.body

  const string = JSON.stringify(persGegevens, (key, value) => {
    if (typeof value === "string"){
      return value.toUpperCase();
    } else {
      return value
    }
  }, 1);

  var transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
      user: 'gietvloermakers@gmail.com',
      pass: 'Gietvloermakers2020!'
    }
  });

  var mailOptions = {
    from: 'gietvloermakers@gmail.com',
    to: 'gvbeusekom84@hotmail.com',
    subject: 'Nieuwe bestelling op Gietvloermakers',
    html: string
  };

  transporter.sendMail(mailOptions, function(error, info){
    if (error) {
      console.log(error);
      res.redirect('/bedankt.html?success=0');
    } else {
      console.log('Email sent: ' + info.response);
      res.redirect('/bedankt.html?success=1');
    }
  });
});

// note rename to api
exports.api = functions.https.onRequest(apiApp);
</code>```

which requires updating your firebase.json file to:

```<code>{
  "hosting": {
    "public": "Public",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [{
      "source": "/api/**",
      "function": "api"
    }]
  }
}
</code>```

This configuration will first attempt to find a matching file in your Public directory. If it can't find a match, it will check if the requested path starts with /api and if so, launch your Cloud Function. If it still can't find a match, it will show your 404 page (or the built in one if it doesn't exist).

Title: Firebase Functions HTTPS 403 Forbidden

Body:
I built a Firebase HTTP Event function with Node and Express. The function is working, but when I invoke the function on the client side I get 403 Forbidden. The first time I invoked the function I was asked to sign in with a Google account. I signed in with the same account I use for Firebase, but when I invoked the function I got:

Screenshot of 403 error

I looked at the use roles on Google cloud platform and the permission to invoke the function is set to allUsers. I signed out and back in again in the Firebase CLI.

Here is the index.js in the functions folder:

const functions = require('firebase-functions');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const port = process.env.port || 5600
const nodemailer = require('nodemailer');

app.use(express.static('Public'));

app.use(bodyParser.urlencoded({ extended: true }));

const urlencodedParser = bodyParser.urlencoded({extended: true});

app.post("/api/user", urlencodedParser, (req, res) => {
  res.sendFile('../Public/bedankt.html', {root: __dirname})
  const persGegevens = req.body

  const string = JSON.stringify(persGegevens, (key, value) => {
    if (typeof value === "string"){
      return value.toUpperCase();
    } else {
      return value
    }
  }, 1);

  var transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
      user: 'gietvloermakers@gmail.com',
      pass: 'Gietvloermakers2020!'
    }
  });

  var mailOptions = {
    from: 'gietvloermakers@gmail.com',
    to: 'gvbeusekom84@hotmail.com',
    subject: 'Nieuwe bestelling op Gietvloermakers',
    html: string
  };

  transporter.sendMail(mailOptions, function(error, info){
    if (error) {
      console.log(error);
    } else {
      console.log('Email sent: ' + info.response);
    }
  });
});

exports.app1 = functions.https.onRequest(app);

app.listen(port);

console.log(port);

Here is the html:

<form id="controlleer-form" action="/api/user" method="post" enctype="application/x-www-form-urlencoded">

Uw bestelling

Aantal m2

        <input class="controle-input" type="text" name="aantalM2" id="aantalM2" readonly>

Kleur

        <input class="controle-input" type="text" name="kleur" id="kleur" readonly>

Assistentie

        <input class="controle-input" type="text" name="assistentie" id="assistentie" readonly>

Gereedschappen

        <input class="controle-input" type="text" name="gereedschappen" id="gereedschappen" readonly>

Totale prijs

        <input  class="controle-input" type="text" name="totale-prijs" id="totale-prijs" readonly>

Bestelling aanpassen

Uw gegevens

Voornaam

        <input type="text" name="voornaam" placeholder="Voornaam">

Achternaam

        <input type="text" name="Achternaam" placeholder="Achternaam">

Straatnaam en huisnummer

        <input type="text" name="Achternaam" placeholder="Straatnaam en huisnummer">

Postcode

        <input type="text" name="Achternaam" placeholder="Postcode">

Telefoonnummer

        <input type="tel" name="telefoonnummer" placeholder="Telefoonnummer">

Emailadres

        <input type="email" name="email" placeholder="Emailadres">

        <input id="verzenden" type="submit">

</form>

Here is the firebase.json:

{
  "hosting": {
    "public": "Public",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [{
      "source": "**",
      "function": "app1"
    }]
  }
}

I tried but I exhausted all possible solutions I've found online so far.

Body:
Your code exports the express application as the Cloud Function app1 on this line:

exports.app1 = functions.https.onRequest(app);

In your screenshot, you have tried to access the non-existent app Cloud Function instead resulting in the 403 Forbidden response.

This means the correct URL to call from your client is

http://us-central1-gietvloermakers.cloudfunctions.net/app1/api/user
                                                      ^^^^

(or you could change the name of the export to app)

Having a closer look at your source code, you should also remove the following lines. If you wanted to test your code you would instead use firebase serve.

const port = process.env.port || 5600
/* ... */
app.listen(port);

On the following lines, you also inject the body parser twice.

app.use(bodyParser.urlencoded({ extended: true })); // use this

const urlencodedParser = bodyParser.urlencoded({extended: true}); // or this, not both

app.post("/api/user", urlencodedParser, ...

In your code, you also have:

app.post("/api/user", urlencodedParser, (req, res) => {
  res.sendFile('../Public/bedankt.html', {root: __dirname})
  /* do some other stuff */
})

This is invalid for a Cloud Function, because as soon as the Cloud Function handler (your code) calls end(), redirect() or send(), the Cloud Function is allowed to be terminated at any time which means that your email may never be sent. To fix this you need to send the file last.

app.post("/api/user", urlencodedParser, (req, res) => {
  /* do some other stuff */
  res.sendFile('../Public/bedankt.html', {root: __dirname})
});

My last observation, is that the error may be caused by the folder Public not existing on the server. Based on your sendFile call, you are expecting that the folder "Public" is available to your deployed function but as it is not inside the functions folder, it will not be deployed with your code.

res.sendFile('../Public/bedankt.html', {root: __dirname})

As this file would also be accessible at your-domain.com/bedankt.html, we'll redirect to it. If you wanted to send the HTML content of this file instead, move it inside your deployed functions directory.

res.redirect('/bedankt.html')

Because you appear to be trying to use your express function behind Firebase hosting, we can trim your index.js file to the following:

const functions = require('firebase-functions');
const express = require('express');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');

const apiApp = express();

apiApp.use(bodyParser.urlencoded({ extended: true }));

apiApp.post("/api/user", (req, res) => {
  const persGegevens = req.body

  const string = JSON.stringify(persGegevens, (key, value) => {
    if (typeof value === "string"){
      return value.toUpperCase();
    } else {
      return value
    }
  }, 1);

  var transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
      user: 'gietvloermakers@gmail.com',
      pass: 'Gietvloermakers2020!'
    }
  });

  var mailOptions = {
    from: 'gietvloermakers@gmail.com',
    to: 'gvbeusekom84@hotmail.com',
    subject: 'Nieuwe bestelling op Gietvloermakers',
    html: string
  };

  transporter.sendMail(mailOptions, function(error, info){
    if (error) {
      console.log(error);
      res.redirect('/bedankt.html?success=0');
    } else {
      console.log('Email sent: ' + info.response);
      res.redirect('/bedankt.html?success=1');
    }
  });
});

// note rename to api
exports.api = functions.https.onRequest(apiApp);

which requires updating your firebase.json file to:

{
  "hosting": {
    "public": "Public",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [{
      "source": "/api/**",
      "function": "api"
    }]
  }
}

This configuration will first attempt to find a matching file in your Public directory. If it can't find a match, it will check if the requested path starts with /api and if so, launch your Cloud Function. If it still can't find a match, it will show your 404 page (or the built in one if it doesn't exist).


问:
How do docker-compose network aliases work if there are multiple instances for zero downtime container update?
So I have:

```<code>version: "3.6"

services:
  nginx:
    image: nginx
  app:
    image: node:latest
</code>```

And my nginx config is:

```<code>upstream project_app {
  server app:4000;
}

server {
  listen 80;
  server_name example.com;

  location / {
    proxy_pass http://project_app;
  }

</code>```

In order to update a container without downtime (rolling updates), I first upscale the app service to 2:

```<code>docker-compose up -d --no-deps --scale app=2 --no-recreate app
</code>```

It will create project_app_1 along project_app.

But at this step, even when the new project_app_1 container is ready, all the traffic goes to project_app, the former container.

To have them both used, I then need to run docker-compose restart nginx.

Now, the traffic is router to both project_app and project_app_1, which is really cool.

I am now ready to kill project_app which is outdated now.

My questions are:

Do I need to restart nginx again after it is killed, to make sure all the traffic gets routed to project_app_1 or is it somewhat automatic?

The fact that http://app:4000 works is because of DNS hostname config, right? Where can learn more on this?

If shutdown discovery works automatically in nginx, ain't there a way to make startup discovery also automatic in order to avoid restarting nginx, which induces a 2 seconds downtime?

Thanks

PS: If you are curious about the whole script I use, I reported it on the associated github issue.

答:
you can use:

```<code>upstream project_app {
  server app:4000 down;
  server app1:4000 down;
}
</code>```

if app is down it jumps to app1,if app is back up it use it.

Body:
So I have:

version: "3.6"

services:
  nginx:
    image: nginx
  app:
    image: node:latest

And my nginx config is:

upstream project_app {
  server app:4000;
}

server {
  listen 80;
  server_name example.com;

  location / {
    proxy_pass http://project_app;
  }

In order to update a container without downtime (rolling updates), I first upscale the app service to 2:

docker-compose up -d --no-deps --scale app=2 --no-recreate app

It will create project_app_1 along project_app.

But at this step, even when the new project_app_1 container is ready, all the traffic goes to project_app, the former container.

To have them both used, I then need to run docker-compose restart nginx.

Now, the traffic is router to both project_app and project_app_1, which is really cool.

I am now ready to kill project_app which is outdated now.

My questions are:

Do I need to restart nginx again after it is killed, to make sure all the traffic gets routed to project_app_1 or is it somewhat automatic?

The fact that http://app:4000 works is because of DNS hostname config, right? Where can learn more on this?

If shutdown discovery works automatically in nginx, ain't there a way to make startup discovery also automatic in order to avoid restarting nginx, which induces a 2 seconds downtime?

Thanks

PS: If you are curious about the whole script I use, I reported it on the associated github issue.

Body:
you can use:

upstream project_app {
  server app:4000 down;
  server app1:4000 down;
}

if app is down it jumps to app1,if app is back up it use it.


问:
How can I use `console.log` or `console.error` in a vue template?
I have a vue component with

```<code> <form @keydown="console.error($event.target.name);">
</code>```

gives

app.js:47961 [Vue warn]: Property or method "console" is not defined
on the instance but referenced during render.

window.console doesn't work either

What is the proper way to use console and window in a template to debug?

答:
Simplest way of providing global objects to the template is to place them in computed, like this:

console: () => console. Same goes for window,

```<code>computed: {
  console: () => console,
  window: () => window,
}
</code>```

See it here.

Body:
I have a vue component with

 <form @keydown="console.error($event.target.name);">

gives

app.js:47961 [Vue warn]: Property or method "console" is not defined
on the instance but referenced during render.

window.console doesn't work either

What is the proper way to use console and window in a template to debug?

Body:
Simplest way of providing global objects to the template is to place them in computed, like this:

console: () => console. Same goes for window,

computed: {
  console: () => console,
  window: () => window,
}

See it here.


问:
How to give each cell random digit number
I want to give each cell a random double-digit number between 50-500
i'm trying to use math.floor(math.random() as function but no success so far

also how I can target only one cell, for example i have 5x5 slots 5 rows 5 col, and I want to target the top left cell in the corner alone, and instead of random generated numbers like the rest cells, i want to give it a symbol where i can control it, so if the symbol is in top left corner, i click on middle for example and it moves there, replacing the generated number which was in the middle and keeping the top left right corner empty

sorry for the trouble, any help really appreciated

```<code><html>
<head>
<style>
td{
border:2px solid black;
width:10px;
height:10px;
}
td:hover{background-color:lightgreen;}
.grn{
background-color:green;
color:white;
}
</style>

<body>
<div id='ff'></div>

<script>
var isCol=0;
var board=[];
for(r=0;r<7;r++){
    var line=[];
    for(c=0;c<7;c++){
        line.push(r);
    }
    board.push(line);
}

function prs(c,r){
    showTable(c,r);
    isCol=(isCol+1)%2;
}

function toColor(col,row,chosen_col,chosen_row){
var ret=false;
switch(isCol){
    case 0:
        if(row==chosen_row){
            ret=true;
        }
        break;
    case 1:
        if(col==chosen_col){
            ret=true;
        }
        break;
}

return ret;
}

function showTable(chosen_col,chosen_row){
var str="";
str+="<table border=1>";
for(row=0;row<7;row++){
    str+="<tr>";
    for(col=0;col<7;col++){
        str+="<td onclick='prs("+col+","+row+")'";
        if(toColor(col,row,chosen_col,chosen_row)){
            str+=" class='grn' ";
        }
        str+=">";
str+=board[row][col];
        str+="</td>";
    }
    str+="</tr>";
}
str+="</table>";

 document.getElementById("ff").innerHTML=str;
}

showTable(-1);
</script>
</body>
</html>

</code>```

答:
I noticed you're using isCol as a toggle every time you click a cell. Instead of adding and then doing modulus; use a boolean.

```<code>isCol=false;

function prs(...) {
    showTable(...);
    isCol=!isCol;
}
</code>```

this way you can make your toColor statement simpler.

```<code>if(isCol) {
    return row === chosen_row;
}
else {
    return col === chosen_col;
}
</code>```

Body:
I noticed you're using isCol as a toggle every time you click a cell. Instead of adding and then doing modulus; use a boolean.

isCol=false;

function prs(...) {
    showTable(...);
    isCol=!isCol;
}

this way you can make your toColor statement simpler.

if(isCol) {
    return row === chosen_row;
}
else {
    return col === chosen_col;
}


问:
how can I turn off screen in android programmatically
I want to turn off the screen. So I tried to do it with PowerManager class but it didn't turn off screen.</p>

```<code>PowerManager pm = (PowerManager)getSystemService(POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
</code>```

答:
@SuperDev, add the following to your Manifest:

```<code><uses-permission android:name="android.permission.WRITE_SETTINGS"/>
</code>```

This will resolve your app crash.

Hope it helps :)

Body:
I want to turn off the screen. So I tried to do it with PowerManager class but it didn't turn off screen.

PowerManager pm = (PowerManager)getSystemService(POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();

Body:
@SuperDev, add the following to your Manifest:

<uses-permission android:name="android.permission.WRITE_SETTINGS"/>

This will resolve your app crash.

Hope it helps :)


问:
Apache .htaccess to use subfolder as root
I know this kind of question is recurrent. But after several hours of searching I didn't find anything.

I'm making a website using Slim. However, in their documentation, they use /public as root directory, which I don't want. I want the website root to be /. Quite concerned about security, I created a .htaccess to redirect http://www.example.com/ to http://www.example.com/public/, so no user can reach /src and other folders :

```<code><IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule ^$ /public [P]
</IfModule>
</code>```

This causes a problem : the URI remains /public/, therefore the public/index.php file below returns a 404 error :

<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;

require __DIR__ . '/../vendor/autoload.php';

$app = AppFactory::create();

$app->get('/', function (Request $request, Response $response, $args) {
    $response->getBody()->write("Hello world!");
    return $response;
});

$app->run();
```
<p>I have to replace <code>'/'</code> with <code>'/public/'</code> in the code for the page to work. I don't exactly like that.<br />
What should I add to Slim's <code>/public/.htaccess</code> below to remove the <code>/public</code> from the URI ?</p>
```<IfModule mod_rewrite.c>
  RewriteEngine On

  RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
  RewriteRule ^(.*) - [E=BASE:%1]

  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^ index.php [QSA,L]
</IfModule>
```

Edit: Solution used

I redirected my vhost to /public/. The web hosting service I use supports this, so it's the best solution.

Thanks to MrWhite.

答:
```<code><IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule ^$ /public [P]
</IfModule>
</code>```

This only "forwards" requests for the root / homepage, ie. /, not /foo, etc. This also forwards the request using mod_proxy (as a reverse proxy), whereas you only need a simple internal rewrite.

You need to rewrite every request that would otherwise go to the root directory (outside of /public) to the /public subdirectory. ie. /foo rewrites to /public/foo and /images/bar.jpg to /public/images/bar.jpg, etc.

```<code> RewriteEngine On
 RewriteRule (.*) /public/$1 [L]
</code>```

(No need for the <IfModule> wrapper since mod_rewrite is mandatory here, it's not optional.)

All your URLs (to everything) should then omit the /public subdirectory.

UPDATE: However, it would seem that the BASE environment variable is still being set to the /public subdirectory by the following directives in /public/.htaccess:

```<code>RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
RewriteRule ^(.*) - [E=BASE:%1]
</code>```

You could simply comment out (remove) the above directives and hardcode the BASE env var:

```<code>SetEnv BASE /
</code>```

However, it's unclear whether this would be a problem or not in the Slim framework. It's possible that this is being used to construct URLs (although it shouldn't, since this is the filesystem path, not the URL-path by which users access the pages - and can easily be calculated in PHP anyway).

Alternatively, everything in /public should be in your document root (ie. your public directory... public_html or htdocs etc.) then the /src (and other folders) will naturally be outside the document root and no additional directives / .htaccess files required to root the request. (Although not every shared server may give you access to above the document root - although they should.)

Or, simply change the DocumentRoot to /public in your server config.

Body:
I know this kind of question is recurrent. But after several hours of searching I didn't find anything.

I'm making a website using Slim. However, in their documentation, they use /public as root directory, which I don't want. I want the website root to be /. Quite concerned about security, I created a .htaccess to redirect http://www.example.com/ to http://www.example.com/public/, so no user can reach /src and other folders :

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule ^$ /public [P]
</IfModule>

This causes a problem : the URI remains /public/, therefore the public/index.php file below returns a 404 error :

<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;

require __DIR__ . '/../vendor/autoload.php';

$app = AppFactory::create();

$app->get('/', function (Request $request, Response $response, $args) {
    $response->getBody()->write("Hello world!");
    return $response;
});

$app->run();

I have to replace '/' with '/public/' in the code for the page to work. I don't exactly like that.

What should I add to Slim's /public/.htaccess below to remove the /public from the URI ?

<IfModule mod_rewrite.c>
  RewriteEngine On

  RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
  RewriteRule ^(.*) - [E=BASE:%1]

  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^ index.php [QSA,L]
</IfModule>

Edit: Solution used

I redirected my vhost to /public/. The web hosting service I use supports this, so it's the best solution.

Thanks to MrWhite.

Body:
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule ^$ /public [P]
</IfModule>

This only "forwards" requests for the root / homepage, ie. /, not /foo, etc. This also forwards the request using mod_proxy (as a reverse proxy), whereas you only need a simple internal rewrite.

You need to rewrite every request that would otherwise go to the root directory (outside of /public) to the /public subdirectory. ie. /foo rewrites to /public/foo and /images/bar.jpg to /public/images/bar.jpg, etc.

 RewriteEngine On
 RewriteRule (.*) /public/$1 [L]

(No need for the <IfModule> wrapper since mod_rewrite is mandatory here, it's not optional.)

All your URLs (to everything) should then omit the /public subdirectory.

UPDATE: However, it would seem that the BASE environment variable is still being set to the /public subdirectory by the following directives in /public/.htaccess:

RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
RewriteRule ^(.*) - [E=BASE:%1]

You could simply comment out (remove) the above directives and hardcode the BASE env var:

SetEnv BASE /

However, it's unclear whether this would be a problem or not in the Slim framework. It's possible that this is being used to construct URLs (although it shouldn't, since this is the filesystem path, not the URL-path by which users access the pages - and can easily be calculated in PHP anyway).

Alternatively, everything in /public should be in your document root (ie. your public directory... public_html or htdocs etc.) then the /src (and other folders) will naturally be outside the document root and no additional directives / .htaccess files required to root the request. (Although not every shared server may give you access to above the document root - although they should.)

Or, simply change the DocumentRoot to /public in your server config.


问:
XNA (Monogame) I need a short way for collisions
I have a code which looks like this:

```<code> /*Need  help here*/
if (car1.hitbox.Intersects(parkingLoot[0].hitbox) || car1.hitbox.Intersects(parkingLoot[1].hitbox))
        intersects = true;
    else
        intersects = false;
</code>```

where hitboxes are a Rectangle.
As you see there is 2 parkingLoot object in array and i checked them. But if i had 1000 parkingLoot objects?
I dont want to use "for loop" to check every parkingLoot objects hitbox if intersects with car.

How to detect if car1.hitbox intersects with ANY HITBOX OF ANY OBJECT WHICH IS A PARKINGLOOT OBJECT

答:
I don't know the enviorment of your scenario, but in my case I have a open world, and I use a grid in the map, and the objets are placed around the cells of the grid. You can do something like that, put every parkingLoot obstacle in a grid, and your car to. And then, using the dimentions of your car you can know the set of cells that the car ocupe, and do a checking of those cells to see if exist obstacles and them check the collision whit this subsets of obstacles collisions rectangles.

You always need to do a for (or whereever structure that you use) for a set of obstacles, but you need to try to minimaize the number of elements of this list for performance matters.

If you give me more details of your game envairoment maybe I can do code example.

Body:
I have a code which looks like this:

 /*Need  help here*/
if (car1.hitbox.Intersects(parkingLoot[0].hitbox) || car1.hitbox.Intersects(parkingLoot[1].hitbox))
        intersects = true;
    else
        intersects = false;

where hitboxes are a Rectangle.
As you see there is 2 parkingLoot object in array and i checked them. But if i had 1000 parkingLoot objects?
I dont want to use "for loop" to check every parkingLoot objects hitbox if intersects with car.

How to detect if car1.hitbox intersects with ANY HITBOX OF ANY OBJECT WHICH IS A PARKINGLOOT OBJECT


问:
How to create a trigger that checks when one value is updated for defined values still being null and if not updates a table
How can I create a trigger that is triggered by an update and then checks if there are certain values in the updated table and another table still null. If not it should change a value in a third table to sysdate.

My code:

```<code>    CREATE OR REPLACE TRIGGER TRG_UPDATE_VALUE
        BEFORE UPDATE OF column1
        ON table1
    REFERENCING OLD AS OLD NEW AS NEW
        for each row
    DECLARE
        value_one_null int;
        value_two_null int;

    BEGIN
        SELECT COUNT(table1_id)
        INTO value_one_null
        FROM table1
        WHERE column1 IS NULL
        AND column2 = :NEW.column2;

        SELECT COUNT(table2_id)
        INTO value_two_null
        FROM table2
        WHERE column1 IS NULL
        AND column2 = :NEW.column2;

        IF (value_one_null = 0 AND value_two_null = 0)
            THEN
            UPDATE table3 SET table3.column1 = sysdate
                WHERE table3_id = :NEW.column2;
        END IF;
    END;

</code>```

Compiling the trigger works. But if I try to update table 1 it errors ORA-04091, ORA-06512, ORA-04088

I am a total beginner in PL/SQL so it would be amazing if someone could help me to fix this error.

答:
The main problem is that you are trying to read  rows in row-level trigger from the target table (a table which  is the  trigger is associated to).
This operaration is prohibited by RDMS.

The general approach to implement the functionality is to use  a common memory by  COMPOUND triggers or packages and achieve the goal in a number of steps.

Please read initial topic of Tom Kyte about mutating tables and triggers to learn the topic.

Here is one of the hundreds of explanations:

Mutating table/trigger error and how to resolve it

Body:
How can I create a trigger that is triggered by an update and then checks if there are certain values in the updated table and another table still null. If not it should change a value in a third table to sysdate.

My code:

    CREATE OR REPLACE TRIGGER TRG_UPDATE_VALUE
        BEFORE UPDATE OF column1
        ON table1
    REFERENCING OLD AS OLD NEW AS NEW
        for each row
    DECLARE
        value_one_null int;
        value_two_null int;

    BEGIN
        SELECT COUNT(table1_id)
        INTO value_one_null
        FROM table1
        WHERE column1 IS NULL
        AND column2 = :NEW.column2;

        SELECT COUNT(table2_id)
        INTO value_two_null
        FROM table2
        WHERE column1 IS NULL
        AND column2 = :NEW.column2;

        IF (value_one_null = 0 AND value_two_null = 0)
            THEN
            UPDATE table3 SET table3.column1 = sysdate
                WHERE table3_id = :NEW.column2;
        END IF;
    END;

Compiling the trigger works. But if I try to update table 1 it errors ORA-04091, ORA-06512, ORA-04088

I am a total beginner in PL/SQL so it would be amazing if someone could help me to fix this error.


问:
I'm trying to use multiplot to combine plot and splot but x,y labels seem to be shifted
```<code>set xrange [-2:2]
set yrange [-2:2]

set xlabel 'X'
set ylabel 'Y'

set samples 300
set isosamples 300

set lmargin screen 0.1
set rmargin screen 0.9
set tmargin screen 0.9
set bmargin screen 0.1

set multiplot

set pm3d map
set palette grey
unset colorbox
splot x**2+y**2 < 1 ? 0:0.2
unset pm3d

plot sin(x) lc 0
</code>```

This code displays the problem - different positionning of x/y labels by splot, plot.

答:
Although you have the margins identical for both plots for some reason (which I don't know) the labels are not at identical positions. However, since the label values are identical anyway, no need for trying to plot the second labels on top of the first ones. Simply skip all labels and tics of the second plot.

Code:

```<code>### remove shifted tics in multiplot
reset session

set xrange [-2:2]
set yrange [-2:2]

set xlabel 'X'
set ylabel 'Y'

set samples 300
set isosamples 300

set lmargin screen 0.1
set rmargin screen 0.9
set tmargin screen 0.9
set bmargin screen 0.15

set multiplot
    set pm3d map
    set palette grey
    unset colorbox
    splot x**2+y**2 < 1 ? 0:0.2
    unset pm3d

    unset xlabel
    unset ylabel
    unset xtics
    unset ytics

    plot sin(x) lc 0
unset multiplot
### end of code
</code>```

Result:

Body:
set xrange [-2:2]
set yrange [-2:2]

set xlabel 'X'
set ylabel 'Y'

set samples 300
set isosamples 300

set lmargin screen 0.1
set rmargin screen 0.9
set tmargin screen 0.9
set bmargin screen 0.1

set multiplot

set pm3d map
set palette grey
unset colorbox
splot x**2+y**2 < 1 ? 0:0.2
unset pm3d

plot sin(x) lc 0

This code displays the problem - different positionning of x/y labels by splot, plot.

Body:
Although you have the margins identical for both plots for some reason (which I don't know) the labels are not at identical positions. However, since the label values are identical anyway, no need for trying to plot the second labels on top of the first ones. Simply skip all labels and tics of the second plot.

Code:

### remove shifted tics in multiplot
reset session

set xrange [-2:2]
set yrange [-2:2]

set xlabel 'X'
set ylabel 'Y'

set samples 300
set isosamples 300

set lmargin screen 0.1
set rmargin screen 0.9
set tmargin screen 0.9
set bmargin screen 0.15

set multiplot
    set pm3d map
    set palette grey
    unset colorbox
    splot x**2+y**2 < 1 ? 0:0.2
    unset pm3d

    unset xlabel
    unset ylabel
    unset xtics
    unset ytics

    plot sin(x) lc 0
unset multiplot
### end of code

Result:


问:
Ansible - Mode 755 for directories and 644 for files recursively
I'd like to allow anyone to list and read all files in my directory tree, but I don't want to make the files executable :

```<code>dir
  \subdir1
      file1
  \subdir2
      file2
  ...
  \subdirX
      fileX
</code>```

The following task makes my directories and files readable, but it makes all the files executable as well:

```<code>- name: Make my directory tree readable
  file:
    path: dir
    mode: 0755
    recurse: yes
</code>```

On the other hand, if I choose mode 0644, then all my files are not executable, but I'm not able to list my directories.

Is it possible to set mode 755 for all directories and 644 for all files in a directory tree?

答:
Due to a "inadequate" implementation Ansible supports symbolic modes only partially (see explanation below).

Other than using the command line chmod, setting mode to u=rwX,g=rX,o=rX with Ansible will not allways be sufficient to get your files set to 644.
The resulting permissions will also depend on the original mode of the file!

As stated in the docs for chmod and already pointed out by some comments to other answers of this question:
If file permission for either u, g, or o is executable, then X will set the file permission also to x.

For example. If one file has mode 740 -rwxr-----, setting mode u=rwX,g=rX,o=rX with ansible, you will get 755 -rwxr-xr-x instead the expected 644 -rw-r--r--.
Despite that this is not what you wanted, it will make the file executable by group and others with unwanted security problems.

In those cases, with Ansible you will need two steps to set file the permissions to 644.

```<code>- file:
    path: /path/to/dir
    state: directory
    recurse: yes
    mode: '{{ item }}'
  loop:
    - '-x'
    - 'u=rwX,g=rX,o=rX'
</code>```

Note that if you wanted mode 744 for files you'll need u=rwx,g=rX,o=rX (first x lowercase!). This will work in Ansible as for the current implementation BUT this is not the way command line chmod works. See **Symbolic nodes with* chmod below.

Why is this so:

Ansible states in the function _symbolic_mode_to_octal to include things like: u=rw-x+X,g=r-x+X,o=r-x+X.
Nonetheless if the given mode is g=-x+X, ansible ignores the -x perm.
The function _symbolic_mode_to_octal iterates over the given permissions,
when it comes to X the function _get_octal_mode_from_symbolic_perms doesn't compare the requested permissions to the already applied but to the original ones, thus ignoring it:

This is probably a bug in Ansible.

The simplest and efficient way is to delegate to a shell command: As proposed in @BruceP's answer.

If for some reason you are averse to use 'workarounds' and need an ansible-ish way to solve the problem AND you don't care about performance you could try the following:

NOTE: This will take very, very long depending on the number of files and directories!

```<code>- name: example
  hosts: 192.168.111.123
  become: yes
  gather_facts: no
  vars:
    path_to_dir: /path/to/dir
    target_mode_for_directories: 755
    target_mode_for_files: 644
  tasks:
    - name: collect list of directories '{{ path_to_dir }}'
      find:
        paths: '{{ path_to_dir }}'
        recurse: yes
        file_type: directory
      register: found_directories
    - name: set collected directories to mode '{{ target_mode_for_directories }}'
      file:
        dest: '{{ item.path }}'
        mode: '{{ target_mode_for_directories }}'
      loop: '{{ found_directories.files }}'
    - name: collect list of files under '{{ path_to_dir }}'
      find:
        paths: '{{ path_to_dir }}'
        recurse: yes
        file_type: file
      register: found_files
    - name: set collected files to mode '{{ target_mode_for_files }}'
      file:
        dest: '{{ item.path }}'
        mode: '{{ target_mode_for_files }}'
      loop: '{{ found_files.files }}'

</code>```

Symbolic modes with chmod

Remember that setting symbolic modes with chmod can be very tricky.
See the following examples that simply differ on the order of lowercase and uppercase X, i.e. u=X,g=X,o=x (o=lowercase x) vs. u=x,g=X,o=X (u=lowercase x) which results in 001 ---------x vs. 111 ---x--x--x:

```<code>$ sudo chmod -R 000 path/to/file; \
  sudo chmod -R u=X,g=X,o=x path/to/file; \
  sudo find path/to/file -printf ""%03m" "%M" "%p\\n"";

001 ---------x path/to/file

$ sudo chmod -R 000 path/to/file; \
  sudo chmod -R u=x,g=X,o=X path/to/file; \
  sudo find path/to/file -printf ""%03m" "%M" "%p\\n"";

111 ---x--x--x path/to/file

</code>```

This is due to the fact that the perms are processed first for u, then for g and last for o. In the first example X won't apply for files because there is no x perm. In the second case X will apply for files after u=x has been set, thus setting both g=x and o=x

Body:
I'd like to allow anyone to list and read all files in my directory tree, but I don't want to make the files executable :

dir
  \subdir1
      file1
  \subdir2
      file2
  ...
  \subdirX
      fileX

The following task makes my directories and files readable, but it makes all the files executable as well:

- name: Make my directory tree readable
  file:
    path: dir
    mode: 0755
    recurse: yes

On the other hand, if I choose mode 0644, then all my files are not executable, but I'm not able to list my directories.

Is it possible to set mode 755 for all directories and 644 for all files in a directory tree?

Body:
Due to a "inadequate" implementation Ansible supports symbolic modes only partially (see explanation below).

Other than using the command line chmod, setting mode to u=rwX,g=rX,o=rX with Ansible will not allways be sufficient to get your files set to 644.
The resulting permissions will also depend on the original mode of the file!

As stated in the docs for chmod and already pointed out by some comments to other answers of this question:
If file permission for either u, g, or o is executable, then X will set the file permission also to x.

For example. If one file has mode 740 -rwxr-----, setting mode u=rwX,g=rX,o=rX with ansible, you will get 755 -rwxr-xr-x instead the expected 644 -rw-r--r--.
Despite that this is not what you wanted, it will make the file executable by group and others with unwanted security problems.

In those cases, with Ansible you will need two steps to set file the permissions to 644.

- file:
    path: /path/to/dir
    state: directory
    recurse: yes
    mode: '{{ item }}'
  loop:
    - '-x'
    - 'u=rwX,g=rX,o=rX'

Note that if you wanted mode 744 for files you'll need u=rwx,g=rX,o=rX (first x lowercase!). This will work in Ansible as for the current implementation BUT this is not the way command line chmod works. See **Symbolic nodes with* chmod below.

Why is this so:

Ansible states in the function _symbolic_mode_to_octal to include things like: u=rw-x+X,g=r-x+X,o=r-x+X.
Nonetheless if the given mode is g=-x+X, ansible ignores the -x perm.
The function _symbolic_mode_to_octal iterates over the given permissions,
when it comes to X the function _get_octal_mode_from_symbolic_perms doesn't compare the requested permissions to the already applied but to the original ones, thus ignoring it:

This is probably a bug in Ansible.

The simplest and efficient way is to delegate to a shell command: As proposed in @BruceP's answer.

If for some reason you are averse to use 'workarounds' and need an ansible-ish way to solve the problem AND you don't care about performance you could try the following:

NOTE: This will take very, very long depending on the number of files and directories!

- name: example
  hosts: 192.168.111.123
  become: yes
  gather_facts: no
  vars:
    path_to_dir: /path/to/dir
    target_mode_for_directories: 755
    target_mode_for_files: 644
  tasks:
    - name: collect list of directories '{{ path_to_dir }}'
      find:
        paths: '{{ path_to_dir }}'
        recurse: yes
        file_type: directory
      register: found_directories
    - name: set collected directories to mode '{{ target_mode_for_directories }}'
      file:
        dest: '{{ item.path }}'
        mode: '{{ target_mode_for_directories }}'
      loop: '{{ found_directories.files }}'
    - name: collect list of files under '{{ path_to_dir }}'
      find:
        paths: '{{ path_to_dir }}'
        recurse: yes
        file_type: file
      register: found_files
    - name: set collected files to mode '{{ target_mode_for_files }}'
      file:
        dest: '{{ item.path }}'
        mode: '{{ target_mode_for_files }}'
      loop: '{{ found_files.files }}'

Symbolic modes with chmod

Remember that setting symbolic modes with chmod can be very tricky.
See the following examples that simply differ on the order of lowercase and uppercase X, i.e. u=X,g=X,o=x (o=lowercase x) vs. u=x,g=X,o=X (u=lowercase x) which results in 001 ---------x vs. 111 ---x--x--x:

$ sudo chmod -R 000 path/to/file; \
  sudo chmod -R u=X,g=X,o=x path/to/file; \
  sudo find path/to/file -printf ""%03m" "%M" "%p\\n"";

001 ---------x path/to/file

$ sudo chmod -R 000 path/to/file; \
  sudo chmod -R u=x,g=X,o=X path/to/file; \
  sudo find path/to/file -printf ""%03m" "%M" "%p\\n"";

111 ---x--x--x path/to/file

This is due to the fact that the perms are processed first for u, then for g and last for o. In the first example X won't apply for files because there is no x perm. In the second case X will apply for files after u=x has been set, thus setting both g=x and o=x


问:
Assign a cell a blank value instead of zero with =F
Here is my formula:

```<code>=IF('LBD Weigth Loss Tracking'!B6=ISBLANK('LBD Weigth Loss Tracking'!B6),"",'LBD Weigth Loss Tracking'!B6)
</code>```

What I want is for the cell to be blank instead of zero but haven't found a way to do that.

The reason is because the table is used in a forecast chart and when the source cell is blank then the cell in the forecast sheet shows 0 causing the forecast to plummet to zero after the last valid value is entered.

This is for my weight loss tracking where I have a sheet with the raw data and then a sheet with the forecast chart/graph.

Thanks for any tips/hints

答:
How about this:

```<code>=IF(ISBLANK('LBD Weigth Loss Tracking'!B6),0,'LBD Weigth Loss Tracking'!B6)
</code>```

Please check the name of the sheet you address as "weight" is not the same as "weigth" , note I have not changed the name in the example I gave you.

Body:
Here is my formula:

=IF('LBD Weigth Loss Tracking'!B6=ISBLANK('LBD Weigth Loss Tracking'!B6),"",'LBD Weigth Loss Tracking'!B6)

What I want is for the cell to be blank instead of zero but haven't found a way to do that.

The reason is because the table is used in a forecast chart and when the source cell is blank then the cell in the forecast sheet shows 0 causing the forecast to plummet to zero after the last valid value is entered.

This is for my weight loss tracking where I have a sheet with the raw data and then a sheet with the forecast chart/graph.

Thanks for any tips/hints

Body:
How about this:

=IF(ISBLANK('LBD Weigth Loss Tracking'!B6),0,'LBD Weigth Loss Tracking'!B6)

Please check the name of the sheet you address as "weight" is not the same as "weigth" , note I have not changed the name in the example I gave you.


问:
How to configure workflow runtime (Informatica)?
I would like the workflow to run for 20 minutes....If the running process does not complete within 20 minutes, the workflow should be ended immediately..However, I can only find the timer, but it is used for starting the process after the indicated time which is not I'm looking for...Does anyone know how to specify the duration for the workflow?</p>

答:
[updated to cover complete scenario and cover issues raised by Koushik Sinharoy in comments]

You can achieve it using the timer:

Link one to the Start task and set it to run for 20 minutes in
parallel with your session.

Have a Decision task with Treat the input links as set to OR. This will trigger the decision whenever any of the preceeding task ends, so either your session will get completed or timer runs out (whatever happens first).

Set the Decision condition to $s_your_session.Status = SUCCEEDED.

Link the Decision task to Control Task.

Set Control task to Fail parent.

Add a condition $Decision.Condition = False to the link between Decision task and Control task.

This should be the result:

```<code>Start--->s_your_session--\
    \                     > Decision [OR] ---(False)---> Control Task [Fail parent]
     \-->timer-----------/
</code>```

Thanks Koushik Sinharoy for the remarks below!

Body:
[updated to cover complete scenario and cover issues raised by Koushik Sinharoy in comments]

You can achieve it using the timer:

Link one to the Start task and set it to run for 20 minutes in
parallel with your session.

Have a Decision task with Treat the input links as set to OR. This will trigger the decision whenever any of the preceeding task ends, so either your session will get completed or timer runs out (whatever happens first).

Set the Decision condition to $s_your_session.Status = SUCCEEDED.

Link the Decision task to Control Task.

Set Control task to Fail parent.

Add a condition $Decision.Condition = False to the link between Decision task and Control task.

This should be the result:

Start--->s_your_session--\
    \                     > Decision [OR] ---(False)---> Control Task [Fail parent]
     \-->timer-----------/

Thanks Koushik Sinharoy for the remarks below!


问:
Can't import audio to spark ar
I tried to download song from YouTube and put it in spark ar.
It says that it must be m4a file so I converted it in every site in Google and I still can't upload it. Even when I downloaded Audacity it is not worked for me.</p>

答:
Use these settings and you'll be able to import the m4a files into your project:

Sampling rate: 44100 Hz

Audio channels: mono

Title: Can't import audio to spark ar


问:
Create a distinct List<String>
I have three lists of List<String> type, named as list1, list2, and list3.

I add some items into list1 then copy them to a new list which is list2. Then I create the list3 to add some more items then copy them again to list2. However, I need list2 to contain distinct items, so how would I exclude the duplicate items and avoid adding them into list2?

This is what I have tried out:

List<String> list2 = new ArrayList<>();
List<String> list1 = new ArrayList<>();

                list1.add("String1");
                list1.add("String2");

                list2.addAll(list1);

List<String> list3 = new ArrayList<>();

list3.add("String1");
list3.add("String3");

list2.addAll(list3);
```

答:
```<code>import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

public final class Answer {
    private static final List<String> LIST_ONE = Arrays.asList("String1", "String2");
    private static final List<String> LIST_THREE = Arrays.asList("String1", "String3");

    public static void main(String... args) {
        // if order is not important then use a java.util.HashSet instead
        final Set<String> strings = new LinkedHashSet<>(LIST_ONE);
        strings.addAll(LIST_THREE);

        final List<String> list_two = new ArrayList<>(strings);

        System.out.println("list_two = " + list_two);
    }

}
</code>```

Title: Create a distinct List<String>


问:
onclick event doesn't work after form closing tag
The problem is that onclick event button works fine before form starting tag (at the begining of the html document)
but it doesn't work after form closing tag!
I want to know why this happens?
What is the relation between the place of my button and js function call?

```<code>    <form name="Register" action="#" method="post">
      <fieldset>
        <legend>Personal Information</legend>
      <label>Username</label>
      <input type="text" name="username" placeholder="Enter your name">

      <br><br>

      <label>Password</label>
      <input type="password" name="password" placeholder="Enter your password">

      <br><br>
      <label>Message</label>
      <br>
      <textarea name="message" rows="8" cols="50" readonly>Your Message (currently disabled)</textarea>
      <br><br>

      <label>Upload your cv</label>
      <input type="file" name="cv">

      <br><br>

      <label>Remember me</label>
      <input type="checkbox" name="remember">
      </fieldset>

      <br><br>

      <fieldset>
      <legend>Favourits</legend>
      <label>Choose your browser</label>
      <br>
      <input type="radio" name="browser"> Oprera
      <br>
      <input type="radio" name="browser"> Chrome
      <br>
      <input type="radio" name="browser"> Firefox

      <br><br>

      <label>Choose your Mobile</label>
      <br>
      <input type="radio" name="mobile"> Samsung
      <br>
      <input type="radio" name="mobile"> Apple
      <br>
      <input type="radio" name="mobile"> Nokia
      </fieldset>
      <br><br>

      <fieldset>
      <legend>Button Options</legend>
      <input type="hidden" value="testing">
      <input type="submit" name="submit_Register" value="submit">
      <input type="reset" name="" value="reset">
      </fieldset
    </form>

    <input type="button" name="sayHello" value="sayHello" onclick="sayHello()" />
</code>```

and here's the script

```<code><script>
      function sayHello()
      {
        alert("Hello");
      }
</script>
</code>```

答:
Your button is not working because of invalid closing </fieldset> tag:

```<code></fieldset
</code>```

function sayHello()
  {
    alert("Hello");
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="button" name="sayHello" value="sayHello" onclick="sayHello()" />
<form name="Register" action="#" method="post">
  <fieldset>
    <legend>Personal Information</legend>
  <label>Username</label>
  <input type="text" name="username" placeholder="Enter your name">

  <br><br>

  <label>Password</label>
  <input type="password" name="password" placeholder="Enter your password">

  <br><br>
  <label>Message</label>
  <br>
  <textarea name="message" rows="8" cols="50" readonly>Your Message (currently disabled)</textarea>
  <br><br>

  <label>Upload your cv</label>
  <input type="file" name="cv">

  <br><br>

  <label>Remember me</label>
  <input type="checkbox" name="remember">
  </fieldset>

  <br><br>

  <fieldset>
  <legend>Favourits</legend>
  <label>Choose your browser</label>
  <br>
  <input type="radio" name="browser"> Oprera
  <br>
  <input type="radio" name="browser"> Chrome
  <br>
  <input type="radio" name="browser"> Firefox

  <br><br>

  <label>Choose your Mobile</label>
  <br>
  <input type="radio" name="mobile"> Samsung
  <br>
  <input type="radio" name="mobile"> Apple
  <br>
  <input type="radio" name="mobile"> Nokia
  </fieldset>
  <br><br>

  <fieldset>
  <legend>Button Options</legend>
  <input type="hidden" value="testing">
  <input type="submit" name="submit_Register" value="submit">
  <input type="reset" name="" value="reset">
  </fieldset>
</form>
<input type="button" name="sayHello" value="sayHello" onclick="sayHello()" /></code>```

Body:
The problem is that onclick event button works fine before form starting tag (at the begining of the html document)
but it doesn't work after form closing tag!
I want to know why this happens?
What is the relation between the place of my button and js function call?

    <form name="Register" action="#" method="post">
      <fieldset>
        <legend>Personal Information</legend>
      Username
      <input type="text" name="username" placeholder="Enter your name">

      Password
      <input type="password" name="password" placeholder="Enter your password">

      Message

      <textarea name="message" rows="8" cols="50" readonly>Your Message (currently disabled)</textarea>

      Upload your cv
      <input type="file" name="cv">

      Remember me
      <input type="checkbox" name="remember">
      </fieldset>

      <fieldset>
      <legend>Favourits</legend>
      Choose your browser

      <input type="radio" name="browser"> Oprera

      <input type="radio" name="browser"> Chrome

      <input type="radio" name="browser"> Firefox

      Choose your Mobile

      <input type="radio" name="mobile"> Samsung

      <input type="radio" name="mobile"> Apple

      <input type="radio" name="mobile"> Nokia
      </fieldset>

      <fieldset>
      <legend>Button Options</legend>
      <input type="hidden" value="testing">
      <input type="submit" name="submit_Register" value="submit">
      <input type="reset" name="" value="reset">
      </fieldset
    </form>

    <input type="button" name="sayHello" value="sayHello" onclick="sayHello()" />

and here's the script

Body:
Your button is not working because of invalid closing </fieldset> tag:

</fieldset

function sayHello()
  {
    alert("Hello");
  }

<input type="button" name="sayHello" value="sayHello" onclick="sayHello()" />
<form name="Register" action="#" method="post">
  <fieldset>
    <legend>Personal Information</legend>
  <label>Username</label>
  <input type="text" name="username" placeholder="Enter your name">

  <br><br>

  <label>Password</label>
  <input type="password" name="password" placeholder="Enter your password">

  <br><br>
  <label>Message</label>
  <br>
  <textarea name="message" rows="8" cols="50" readonly>Your Message (currently disabled)</textarea>
  <br><br>

  <label>Upload your cv</label>
  <input type="file" name="cv">

  <br><br>

  <label>Remember me</label>
  <input type="checkbox" name="remember">
  </fieldset>

  <br><br>

  <fieldset>
  <legend>Favourits</legend>
  <label>Choose your browser</label>
  <br>
  <input type="radio" name="browser"> Oprera
  <br>
  <input type="radio" name="browser"> Chrome
  <br>
  <input type="radio" name="browser"> Firefox

  <br><br>

  <label>Choose your Mobile</label>
  <br>
  <input type="radio" name="mobile"> Samsung
  <br>
  <input type="radio" name="mobile"> Apple
  <br>
  <input type="radio" name="mobile"> Nokia
  </fieldset>
  <br><br>

  <fieldset>
  <legend>Button Options</legend>
  <input type="hidden" value="testing">
  <input type="submit" name="submit_Register" value="submit">
  <input type="reset" name="" value="reset">
  </fieldset>
</form>
<input type="button" name="sayHello" value="sayHello" onclick="sayHello()" />


问:
Creating a Model Layer with PDO
Im currently developing a MVC application Framework and I have come for some advise in regards to the way I should construct my Model Layers.

The model is constructed so that each model is mapped to a table within the database for that applications, so a typical application would have

Configuration

Topics

Forums

and each would be mapped to there named PHP file such as app/models/configuration.php

Now the problem I am having is creating the parent database class to be able handle specific table data, for example:

```<code>class PDOModel
{
    public function __construct()
    {
        $this->__Communicator = Registry::getPDOInstance();
    }

    public function getSingle($id)
    {
         return /*Row*/;
    }

    /*Etc*/
}
</code>```

And then something like this for the application model's

```<code>class Model_Topic extends PDOModel
{
    protected $__id_column = 'id';
}
</code>```

and then within my controller I can use like so:

```<code>$Topic = $this->model->topic->get(22);
</code>```

But i would also like to take into considerations auto joining tables as well, are there any simple lightweight libraries about that have been tested and fit the my requirements.

Any help would be highly appreciated.

答:
The closest thing ive seen is Zend_Db which implements Table and Row gateways on top of PDO. It has support for joining related tables and what not.

Typically what youre asking for isnt going to be all that "light weight", its going to be a full ORM of sorts. Personally if i were you i would just go with a decent ORM. Propel >= 1.5, Doctrine 1.2, or Doctrine2.

Title: Creating a Model Layer with PDO

Body:
Im currently developing a MVC application Framework and I have come for some advise in regards to the way I should construct my Model Layers.

The model is constructed so that each model is mapped to a table within the database for that applications, so a typical application would have

Configuration

Topics

Forums

and each would be mapped to there named PHP file such as app/models/configuration.php

Now the problem I am having is creating the parent database class to be able handle specific table data, for example:

class PDOModel
{
    public function __construct()
    {
        $this->__Communicator = Registry::getPDOInstance();
    }

    public function getSingle($id)
    {
         return /*Row*/;
    }

    /*Etc*/
}

And then something like this for the application model's

class Model_Topic extends PDOModel
{
    protected $__id_column = 'id';
}

and then within my controller I can use like so:

$Topic = $this->model->topic->get(22);

But i would also like to take into considerations auto joining tables as well, are there any simple lightweight libraries about that have been tested and fit the my requirements.

Any help would be highly appreciated.


问:
How can I add sms auto verification in flutter app using firebase_auth (Phone Authentication)?
In my flutter app I am using firebase phone authentication for login purpose. in all way, its working perfectly. By using my current code I have to add sms code explicitly when I receive the code.

How can I make this sms verification automatically in my flutter app?

    Future<void> _sendCodeToPhoneNumber() async {

    final String phone = country + phoneNumberController.text;

    final PhoneVerificationCompleted verificationCompleted =
        (AuthCredential credential) {
      setState(() {
        print(
            'Inside _sendCodeToPhoneNumber: signInWithPhoneNumber auto succeeded: $credential');
      });
    };

    final PhoneVerificationFailed verificationFailed =
        (AuthException authException) {
      setState(() {
        print(
            'Phone number verification failed. Code: ${authException.code}. Message: ${authException.message}');
      });
    };

    final PhoneCodeSent codeSent =
        (String verificationId, [int forceResendingToken]) async {
      this._verificationId = verificationId;
      print("code sent to " + phone);
      setState(() {
        this.status = AuthStatus.SMS_AUTH;
      });
    };

    final PhoneCodeAutoRetrievalTimeout codeAutoRetrievalTimeout =
        (String verificationId) {
      this._verificationId = verificationId;

      print("time out");
    };

    await FirebaseAuth.instance.verifyPhoneNumber(
        phoneNumber: phone,
        timeout: const Duration(seconds: 1),
        verificationCompleted: verificationCompleted,
        verificationFailed: verificationFailed,
        codeSent: codeSent,
        codeAutoRetrievalTimeout: codeAutoRetrievalTimeout);
  }
```

答: I didn't use this google sms receiver API. I think this one can be used for auto fill sms code https://developers.google.com/identity/sms-retriever/overview</p>


问:
Powershell - add duplicate key but different values into a hash table
how to add duplicate keys with different values into a hash table so it could be later used in a foreach loop in Powershell? i.e.

```<code>$VM = "computer1"

$HashTable = @{ }
$HashTable.Add("key", $VM)

...some script, if statements, ....

$VM = "computer2"
$HashTable.Add("key", $VM)
.....

ForEach ($machine in $HashTable.values)
{
do something for $machine
}
</code>```

I get an error:
"Exception calling "Add" with "2" argument(s): "Item has already been added. Key in dictionary: 'key'  Key being added: 'key'"

答:
You can't have duplicate keys in a Hash Table (or dictionary), but you can do this:

```<code>$HashTable = @{}

$VM = "computer1"
[Array]$HashTable['Key'] += $VM

$VM = "computer2"
[Array]$HashTable['Key'] += $VM

ForEach ($machine in $HashTable['Key'])
{
    Write-Host $Machine
}
</code>```

But I really question if you want to do this. Instead, I guess your $VM is actually supposed to be the key and than you can do: ForEach ($machine in $HashTable.Keys) {...}

Body:
how to add duplicate keys with different values into a hash table so it could be later used in a foreach loop in Powershell? i.e.

$VM = "computer1"

$HashTable = @{ }
$HashTable.Add("key", $VM)

...some script, if statements, ....

$VM = "computer2"
$HashTable.Add("key", $VM)
.....

ForEach ($machine in $HashTable.values)
{
do something for $machine
}

I get an error:
"Exception calling "Add" with "2" argument(s): "Item has already been added. Key in dictionary: 'key'  Key being added: 'key'"

Body:
You can't have duplicate keys in a Hash Table (or dictionary), but you can do this:

$HashTable = @{}

$VM = "computer1"
[Array]$HashTable['Key'] += $VM

$VM = "computer2"
[Array]$HashTable['Key'] += $VM

ForEach ($machine in $HashTable['Key'])
{
    Write-Host $Machine
}

But I really question if you want to do this. Instead, I guess your $VM is actually supposed to be the key and than you can do: ForEach ($machine in $HashTable.Keys) {...}


问:
VBA macro through Python script
I am trying to execute a macro through python script. When I run it first time it runs properly, but when I run it again after few minutes, it throws error as

File "<COMObject <unknown>>", line 2, in run pywintypes.com_error:

  (-2147352567, 'Exception occurred.', (0, None, None, None, 0,
  -2146827284), None)

My script:

```<code>import win32com.client as win32
import  time
excel=win32.Dispatch("Excel.Application")
excel.visible=1
book=excel.Workbooks.open('C:\\Users\\C296442\\Documents\Application07012020.xlsm')
excel.application.run("Application07012020.xlsm!Sheet5.CommandButton12_Click")
</code>```

答:
I have found 2 ways to do this and both seem to work fine.

```<code>from __future__ import print_function
import unittest
import os.path
import win32com.client

class ExcelMacro(unittest.TestCase):
    def test_excel_macro(self):
        try:
            xlApp = win32com.client.DispatchEx('Excel.Application')
            xlsPath = os.path.expanduser('C:\\Users\\rshuell001\\Desktop\\Valuation Code Rollover.xlsb')
            wb = xlApp.Workbooks.Open(Filename=xlsPath)
            xlApp.Run('Macro1')
            wb.Save()
            xlApp.Quit()
            print("Macro ran successfully!")
        except:
            print("Error found while running the excel macro!")
            xlApp.Quit()
if __name__ == "__main__":
    unittest.main()
</code>```

```<code>import os
import win32com.client

#Launch Excel and Open Wrkbook
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="C:\Full Location\To\excelsheet.xlsm") #opens workbook in readonly mode.

#Run Macro
xl.Application.Run("excelsheet.xlsm!modulename.macroname")

#Save Document and Quit.
xl.Application.Save()
xl.Application.Quit()

#Cleanup the com reference.
del xl
</code>```

Title: VBA macro through Python script

Body:
I am trying to execute a macro through python script. When I run it first time it runs properly, but when I run it again after few minutes, it throws error as

File "<COMObject <unknown>>", line 2, in run pywintypes.com_error:

  (-2147352567, 'Exception occurred.', (0, None, None, None, 0,
  -2146827284), None)

My script:

import win32com.client as win32
import  time
excel=win32.Dispatch("Excel.Application")
excel.visible=1
book=excel.Workbooks.open('C:\\Users\\C296442\\Documents\Application07012020.xlsm')
excel.application.run("Application07012020.xlsm!Sheet5.CommandButton12_Click")

Body:
I have found 2 ways to do this and both seem to work fine.

from __future__ import print_function
import unittest
import os.path
import win32com.client

class ExcelMacro(unittest.TestCase):
    def test_excel_macro(self):
        try:
            xlApp = win32com.client.DispatchEx('Excel.Application')
            xlsPath = os.path.expanduser('C:\\Users\\rshuell001\\Desktop\\Valuation Code Rollover.xlsb')
            wb = xlApp.Workbooks.Open(Filename=xlsPath)
            xlApp.Run('Macro1')
            wb.Save()
            xlApp.Quit()
            print("Macro ran successfully!")
        except:
            print("Error found while running the excel macro!")
            xlApp.Quit()
if __name__ == "__main__":
    unittest.main()

import os
import win32com.client

#Launch Excel and Open Wrkbook
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="C:\Full Location\To\excelsheet.xlsm") #opens workbook in readonly mode.

#Run Macro
xl.Application.Run("excelsheet.xlsm!modulename.macroname")

#Save Document and Quit.
xl.Application.Save()
xl.Application.Quit()

#Cleanup the com reference.
del xl


问:
How do I start workflow session only when the indicator file show up? (Informatica)
What does this mean to start the session only when an indicator file show up for the workflow? Where do I create the text file and how do I insert it to the session? Also, what type of content should be in the text file? I'm quite new into informatica so I really need help... It is because everytime I want to start the session, I would right-click to start the workflow..</p>

答:
Use Event wait taks and set it to wait for a file you're expecting. There is a downside: you can only monitor for a file with a predefined name, there are no wildcards allowed.

Here's more: https://www.tutorialgateway.org/event-wait-task-in-informatica/


问:
ImportError: cannot import name Minio
I am using minio 5.0.1 with this command:

```<code>pip install minio
</code>```

But I still get this error

```<code>Traceback (most recent call last):
  File "minio.py", line 2, in <module>
    from minio import Minio
  File "/root/minio.py", line 2, in <module>
    from minio import Minio
ImportError: cannot import name Minio
</code>```

答:
i guess it's to late for this answer but anyways:

since you call your python file minio.py he tries to import this file instead of the minio package and failes to find an object inside called Minio.

Rename your py file to miniotest.py and it should work.

Title: ImportError: cannot import name Minio

Body:
I am using minio 5.0.1 with this command:

pip install minio

But I still get this error

Traceback (most recent call last):
  File "minio.py", line 2, in <module>
    from minio import Minio
  File "/root/minio.py", line 2, in <module>
    from minio import Minio
ImportError: cannot import name Minio


问:
C# testing - mock class in contructor call
I'm new to using Moq with Xunit in Visual Studio 2019.

I want to mock the contructor call of a class that is being called in the contructor of my tested class.
A simple demonstration of my problem:

```<code>public class MockedClass : IMockedClass
{
   public MockedClass()
   {
      // don't call this
   }
   public List<string> Function1()
   { /* return a List<string> here */ }
}
</code>```

```<code>public class MyClass
{
   readonly IMockedClass mockedClass = null;
   public MyClass()
   {
      mockedClass = new MockedClass();
   }
   public string Function2()
   { /* return a string here */ }
}
</code>```

```<code>public class MyClassTest
{
   [Fact]
   public string Function2Test()
   {
      var returnMock = new List<string>() { "1", "2", "3" };
      var mockMockedClass = new Mock<IMockedClass>();
      mockMockedClass.Setup(x => x.Function1()).Returns(returnMock);
      var myClass = new MyClass();
      var result = myClass.Function2();
      ...
   }
}
</code>```

My problem is, that in the test Function2Test the constructor of MyClass is being called that calls the constructor of MockedClass.
But I don't want the constructor of MockedClass being called.

How can I mock the constructor of MockedClass?

答:
I think you might need to slightly modify your code. You see, obtaining a mock of an interface by itself does not automatically change how other implementations behave when instantiated from other parts of code. You generally want to inject your mocked implementations into tested code via Dependency Injection.

public class MyClass
{
    readonly IMockedClass mockedClass = null;
    public MyClass(IMockedClass c)
    {
        mockedClass = c; // now you'll get the correct implemetation
    }
    public string Function2()
    { /* return a string here */ }
}
void Main()
{

        var returnMock = new List<string>() { "1", "2", "3" };
        var mockMockedClass = new Mock<IMockedClass>(); // get your mock here
        mockMockedClass.Setup(x => x.Function1()).Returns(returnMock);
        var myClass = new MyClass(mockMockedClass.Object); // inject it here
        var result = myClass.Function2();
}
```

Then you will need to set up your Dependency Injection container to provide you with a concrete MockedClass when your actual application code runs. Depending on your code and requirements, there are heaps of options so I won't recommend a specific framework here.

Theoretically, you might be able to mock out the class in your current code structure. I could potentially see how you either opt for Fakes or fancy reflection techniques. However it likely will be way to much effort for going against what seems to be community-accepted best practice.

Body:
I'm new to using Moq with Xunit in Visual Studio 2019.

I want to mock the contructor call of a class that is being called in the contructor of my tested class.
A simple demonstration of my problem:

public class MockedClass : IMockedClass
{
   public MockedClass()
   {
      // don't call this
   }
   public List<string> Function1()
   { /* return a List<string> here */ }
}

public class MyClass
{
   readonly IMockedClass mockedClass = null;
   public MyClass()
   {
      mockedClass = new MockedClass();
   }
   public string Function2()
   { /* return a string here */ }
}

public class MyClassTest
{
   [Fact]
   public string Function2Test()
   {
      var returnMock = new List<string>() { "1", "2", "3" };
      var mockMockedClass = new Mock<IMockedClass>();
      mockMockedClass.Setup(x => x.Function1()).Returns(returnMock);
      var myClass = new MyClass();
      var result = myClass.Function2();
      ...
   }
}

My problem is, that in the test Function2Test the constructor of MyClass is being called that calls the constructor of MockedClass.
But I don't want the constructor of MockedClass being called.

How can I mock the constructor of MockedClass?

Body:
I think you might need to slightly modify your code. You see, obtaining a mock of an interface by itself does not automatically change how other implementations behave when instantiated from other parts of code. You generally want to inject your mocked implementations into tested code via Dependency Injection.

public class MyClass
{
    readonly IMockedClass mockedClass = null;
    public MyClass(IMockedClass c)
    {
        mockedClass = c; // now you'll get the correct implemetation
    }
    public string Function2()
    { /* return a string here */ }
}
void Main()
{

        var returnMock = new List<string>() { "1", "2", "3" };
        var mockMockedClass = new Mock<IMockedClass>(); // get your mock here
        mockMockedClass.Setup(x => x.Function1()).Returns(returnMock);
        var myClass = new MyClass(mockMockedClass.Object); // inject it here
        var result = myClass.Function2();
}

Then you will need to set up your Dependency Injection container to provide you with a concrete MockedClass when your actual application code runs. Depending on your code and requirements, there are heaps of options so I won't recommend a specific framework here.

Theoretically, you might be able to mock out the class in your current code structure. I could potentially see how you either opt for Fakes or fancy reflection techniques. However it likely will be way to much effort for going against what seems to be community-accepted best practice.


问:
message from webpage invalid postback or callback argument. event validation is enabled using
My goal is to have the user be able to click the row and the row will be the selected row almost like having the select button but the entire row clickable to do the same thing

the error i get popups when i click the row, not when the webpage is loaded

this is the onrowdatabound portion i just added that causes the error

```<code>        If e.Row.RowType = DataControlRowType.DataRow Then
            ' Get reference to button field in the gridview.
            Dim _singleClickButton As LinkButton = DirectCast(selectbutton, LinkButton)
            Dim _jsSingle As String = ClientScript.GetPostBackClientHyperlink(_singleClickButton, "Select$" & Convert.ToString(e.Row.RowIndex))
            e.Row.Style("cursor") = "hand"
            e.Row.Attributes("onclick") = _jsSingle
        End If
</code>```

This is my full on rowdatabound

```<code> Protected Sub GridView6_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
            ' CHECK THE ROW TYPE HERE. ONLY EXECUTE ON DataRow
            If e.Row.RowType = DataControlRowType.DataRow Then
                Dim date1 As Date
                date1 = Date.Now
                Dim date2 As Date

                Dim ddate As Label = CType(e.Row.FindControl("duedate"), Label)
                date2 = Date.Parse(ddate.Text)
                Dim ts As TimeSpan = date2.Subtract(date1)
                Dim days As Integer = ts.TotalDays

                If days <= 14 And days >= 0 Then
                    e.Row.ForeColor = System.Drawing.Color.Blue
                    bluecount = bluecount + 1
                ElseIf days > 14 And days < 30 Then
                    e.Row.ForeColor = System.Drawing.Color.Black
                    blackcount = blackcount + 1
                ElseIf days >= 30 Then
                    e.Row.ForeColor = System.Drawing.Color.Green
                    greencount = greencount + 1
                ElseIf days < 0 Then
                    e.Row.ForeColor = System.Drawing.Color.Red
                    redcount = redcount + 1
                End If

                Dim link As HyperLink = CType(e.Row.FindControl("HyperLink1"), HyperLink)
                Dim id As Label = CType(e.Row.FindControl("id"), Label)

                Dim selectbutton As LinkButton = CType(e.Row.FindControl("linkbutton1"), LinkButton)

            If e.Row.RowType = DataControlRowType.DataRow Then
                ' Get reference to button field in the gridview.
                Dim _singleClickButton As LinkButton = DirectCast(selectbutton, LinkButton)
                Dim _jsSingle As String = ClientScript.GetPostBackClientHyperlink(_singleClickButton, "Select$" & Convert.ToString(e.Row.RowIndex))
                e.Row.Style("cursor") = "hand"
                e.Row.Attributes("onclick") = _jsSingle
            End If

                link.NavigateUrl = "Default7.aspx?id=" + id.Text + "&uid=" + user1

                pduecount.Text = redcount
                next14count.Text = bluecount
                fteencount.Text = blackcount
                thirtycount.Text = greencount

            End If

        End Sub
</code>```

答: Set EnableEventValidation to False in Page directive of the aspx page (markup).</p>

Body:
My goal is to have the user be able to click the row and the row will be the selected row almost like having the select button but the entire row clickable to do the same thing

the error i get popups when i click the row, not when the webpage is loaded

this is the onrowdatabound portion i just added that causes the error

        If e.Row.RowType = DataControlRowType.DataRow Then
            ' Get reference to button field in the gridview.
            Dim _singleClickButton As LinkButton = DirectCast(selectbutton, LinkButton)
            Dim _jsSingle As String = ClientScript.GetPostBackClientHyperlink(_singleClickButton, "Select$" & Convert.ToString(e.Row.RowIndex))
            e.Row.Style("cursor") = "hand"
            e.Row.Attributes("onclick") = _jsSingle
        End If

This is my full on rowdatabound

 Protected Sub GridView6_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
            ' CHECK THE ROW TYPE HERE. ONLY EXECUTE ON DataRow
            If e.Row.RowType = DataControlRowType.DataRow Then
                Dim date1 As Date
                date1 = Date.Now
                Dim date2 As Date

                Dim ddate As Label = CType(e.Row.FindControl("duedate"), Label)
                date2 = Date.Parse(ddate.Text)
                Dim ts As TimeSpan = date2.Subtract(date1)
                Dim days As Integer = ts.TotalDays

                If days <= 14 And days >= 0 Then
                    e.Row.ForeColor = System.Drawing.Color.Blue
                    bluecount = bluecount + 1
                ElseIf days > 14 And days < 30 Then
                    e.Row.ForeColor = System.Drawing.Color.Black
                    blackcount = blackcount + 1
                ElseIf days >= 30 Then
                    e.Row.ForeColor = System.Drawing.Color.Green
                    greencount = greencount + 1
                ElseIf days < 0 Then
                    e.Row.ForeColor = System.Drawing.Color.Red
                    redcount = redcount + 1
                End If

                Dim link As HyperLink = CType(e.Row.FindControl("HyperLink1"), HyperLink)
                Dim id As Label = CType(e.Row.FindControl("id"), Label)

                Dim selectbutton As LinkButton = CType(e.Row.FindControl("linkbutton1"), LinkButton)

            If e.Row.RowType = DataControlRowType.DataRow Then
                ' Get reference to button field in the gridview.
                Dim _singleClickButton As LinkButton = DirectCast(selectbutton, LinkButton)
                Dim _jsSingle As String = ClientScript.GetPostBackClientHyperlink(_singleClickButton, "Select$" & Convert.ToString(e.Row.RowIndex))
                e.Row.Style("cursor") = "hand"
                e.Row.Attributes("onclick") = _jsSingle
            End If

                link.NavigateUrl = "Default7.aspx?id=" + id.Text + "&uid=" + user1

                pduecount.Text = redcount
                next14count.Text = bluecount
                fteencount.Text = blackcount
                thirtycount.Text = greencount

            End If

        End Sub


问:
TypeError: Cannot set property 'Id' of "Null"
When I run the code it does work in browser but the error keeps appearing.
Here is my code:

```<code><div id="dashboardJob">
  <script>
     var i = 0;
     do {
        document.getElementById("dashboardJob").id = "dashboardJob" + i;
        i++;
     }
     while (i < 40)
  </script>
</div>
</code>```

Is anyone able to point out what i'm missing here?

Cheers

答:
During the first iteration of the do-while loop, document.getElementById("dashboardJob").id will return null as it hasn't encountered the div's closing tag.

Also, you're trying to dynamically change the id 40 times for the same element. Not sure if that is what you're trying to achieve with the code. However, it won't again during the 2nd iteration since during the 2nd iteration there is no element with id dashboardJob.

Body:
When I run the code it does work in browser but the error keeps appearing.
Here is my code:

Is anyone able to point out what i'm missing here?

Cheers


问:
Is there a way to check whether NSPhotoLibraryAddUsageDescription permission was granted or denied?
I have an application that should save a picture to the Photo library if permission is granted and if not, it should write to another folder in the app sandbox.
I do not need read access on the photo library, so I tried adding the NSPhotoLibraryAddUsageDescription in the info.plist and it works but I can't find out if and what the user has selected. I have found

```<code>PHAuthorizationStatus authStatus = [PHPhotoLibrary authorizationStatus];
</code>```

for checking the status, but it seems there isn't a PHAuthorizationStatus to signal the add-Photo authorization status. I always get PHAuthorizationStatusNotDetermined for both settings, denied and consented.
Is there a known workaround? Did I miss an API call for determining the add-Photo-auth-status?

答: You're correct. If all you're going to do is add a photo to the library using UIImageWriteToSavedPhotosAlbum, the way to find out if the user denied you access is that you'll get that as an error in the completion handler. (That's because this very crude way of adding a photo to the library predates the whole Photos framework.)</p>

Body:
I have an application that should save a picture to the Photo library if permission is granted and if not, it should write to another folder in the app sandbox.
I do not need read access on the photo library, so I tried adding the NSPhotoLibraryAddUsageDescription in the info.plist and it works but I can't find out if and what the user has selected. I have found

PHAuthorizationStatus authStatus = [PHPhotoLibrary authorizationStatus];

for checking the status, but it seems there isn't a PHAuthorizationStatus to signal the add-Photo authorization status. I always get PHAuthorizationStatusNotDetermined for both settings, denied and consented.
Is there a known workaround? Did I miss an API call for determining the add-Photo-auth-status?