问:
Express doesn't set a cookie
I have problem with setting a cookies via express. I'm using Este.js dev stack and I try to set a cookie in API auth /login route. Here is the code that I use in /api/v1/auth/login route

```<code>res.cookie('token', jwt.token, {expires: new Date(Date.now() + 9999999)});
res.status(200).send({user, token: jwt.token});
</code>```

In src/server/main.js I have registered cookie-parser as first middleware

```<code>app.use(cookieParser());
</code>```

The response header for /api/v1/auth/login route contains

```<code>Set-Cookie:token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ..
</code>```

but the cookie isn't saved in browser (document.cookie is empty, also Resources - Cookies tab in develepoers tools is empty) :(

EDIT:
I'm found that when I call this in /api/v1/auth/login (without call res.send or res.json)

res.cookie('token', jwt.token, {expires: new Date(Date.now() + 9999999), httpOnly: false});
next();

then the cookie is set AND response header has set X-Powered-By:Este.js ... this sets esteMiddleware in expres frontend rendering part.

When I use res.send

```<code>res.cookie('token', jwt.token, {expires: new Date(Date.now() + 9999999), httpOnly: false}).send({user, token: jwt.token});`
next();
</code>```

then I get error Can't set headers after they are sent. because send method is used, so frontend render throw this error.

But I have to send a data from API, so how I can deal with this?

答:
Struggling with this for a 3h, and finally realized, with axios, I should set withCredentials to true, even though I am only receiving cookies.

axios.defaults.withCredentials = true;

Title: Express doesn't set a cookie

Body:
I have problem with setting a cookies via express. I'm using Este.js dev stack and I try to set a cookie in API auth /login route. Here is the code that I use in /api/v1/auth/login route

res.cookie('token', jwt.token, {expires: new Date(Date.now() + 9999999)});
res.status(200).send({user, token: jwt.token});

In src/server/main.js I have registered cookie-parser as first middleware

app.use(cookieParser());

The response header for /api/v1/auth/login route contains

Set-Cookie:token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ..

but the cookie isn't saved in browser (document.cookie is empty, also Resources - Cookies tab in develepoers tools is empty) :(

EDIT:
I'm found that when I call this in /api/v1/auth/login (without call res.send or res.json)

res.cookie('token', jwt.token, {expires: new Date(Date.now() + 9999999), httpOnly: false});
next();

then the cookie is set AND response header has set X-Powered-By:Este.js ... this sets esteMiddleware in expres frontend rendering part.

When I use res.send

res.cookie('token', jwt.token, {expires: new Date(Date.now() + 9999999), httpOnly: false}).send({user, token: jwt.token});`
next();

then I get error Can't set headers after they are sent. because send method is used, so frontend render throw this error.

But I have to send a data from API, so how I can deal with this?


来源: stackexchange

问:
Pagination with selected check boxes. Checkboxes will only work on current pagination page. jQuery datatables
I'm using the jquery datatables plugin.

I have just a straight html table layout for it.

```<code><table  class="display" id="contactsTable">
    <thead>
        <tr>
            <th>Id</th>
            <th>Email</th>
            <th>Name</th>
            <th>Phone</th>
            <th>City</th>
            <th>State</th>
            <th>Arrival</th>
            <th>Departure</th>
            <th>Inserted</th>
            <th>Check</th>
        </tr>
    </thead>
    <tbody>
                    <tr>
            <td>301</td>
            <td>email address</td>
            <td>Test</td>
            <td></td>
            <td></td>
            <td></td>
            <td>July 14 2011</td>
            <td>July 23 2011</td>
            <td>April 12 2011 07:05</td>
            <td><input type="checkbox" name="selected[]" value="301" class="chkbox"/></td>
        </tr>
                    <tr>
            <td>300</td>
            <td>email</td>
            <td>Test</td>
<td></td>
            <td></td>
            <td></td>
            <td>September 02 2011</td>
            <td>September 10 2011</td>
            <td>April 11 2011 12:01</td>
            <td><input type="checkbox" name="selected[]" value="300" class="chkbox"/></td>
        </tr>
</code>```

Here is my code for submit (just temp).

```<code><input id="submitButton" type="submit" value="Submit" onclick="test()" />
</code>```

And my javascript to map the checkboxes to an array.

```<code>function test() {
        var values = $('input:checkbox:checked.chkbox').map(function () {
            return this.value;
        }).get();
        console.log(values);
    }
</code>```

Here is the datatables code

```<code> $(document).ready(function() {

    var selected;
    var selectedOutput = '#selectedOutput';
    var template = 'selectedTemplate';
    var submitButton = '#submitButton'

    var  dTable = $('#contactsTable').dataTable({
        "bJQueryUI": true,
        "sPaginationType": "full_numbers",
        "bPaginate": true,
        "bLengthChange": true,
        "bFilter": true,
        "bSort": false,
        "bInfo": true,
        "bAutoWidth": false,
        "bProcessing": true,
        "aoColumns": [
            {"bVisible": false }, //keep the id invisble
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null
        ]
    });
</code>```

The problem is, I can't do a checkbox selection across a page.  The table has mutiple pages to it.  If I click submit, it only submits the array of checkboxes for the current page I am on.

I hope this is clear enough.  I'm not sure what is happening.  Thanks for any help.

答:
i think you might have a look at this, it might solve your problem.

This example might be of help to you as it seems to be exactly your case (this one uses fnGetNodes(), while in the other link it is explained how to use fnGetHiddenNodes() if the first function doesn't work ): http://datatables.net/examples/api/form.html

ContentLicense: CC BY-SA 3.0

Body:
I'm using the jquery datatables plugin.

I have just a straight html table layout for it.

            Id
            Email
            Name
            Phone
            City
            State
            Arrival
            Departure
            Inserted
            Check

            301
            email address
            Test

            July 14 2011
            July 23 2011
            April 12 2011 07:05
            <input type="checkbox" name="selected[]" value="301" class="chkbox"/>

            300
            email
            Test

            September 02 2011
            September 10 2011
            April 11 2011 12:01
            <input type="checkbox" name="selected[]" value="300" class="chkbox"/>

Here is my code for submit (just temp).

<input id="submitButton" type="submit" value="Submit" onclick="test()" />

And my javascript to map the checkboxes to an array.

function test() {
        var values = $('input:checkbox:checked.chkbox').map(function () {
            return this.value;
        }).get();
        console.log(values);
    }

Here is the datatables code

 $(document).ready(function() {

    var selected;
    var selectedOutput = '#selectedOutput';
    var template = 'selectedTemplate';
    var submitButton = '#submitButton'

    var  dTable = $('#contactsTable').dataTable({
        "bJQueryUI": true,
        "sPaginationType": "full_numbers",
        "bPaginate": true,
        "bLengthChange": true,
        "bFilter": true,
        "bSort": false,
        "bInfo": true,
        "bAutoWidth": false,
        "bProcessing": true,
        "aoColumns": [
            {"bVisible": false }, //keep the id invisble
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null
        ]
    });

The problem is, I can't do a checkbox selection across a page.  The table has mutiple pages to it.  If I click submit, it only submits the array of checkboxes for the current page I am on.

I hope this is clear enough.  I'm not sure what is happening.  Thanks for any help.


问:
How to grant file system access outside of container?
According to Apple's documentation, for an app to access the file system outside of its container, and outside of the directories listed here, it needs to specify a File Access Temporary Exceptions Entitlement.

My app needs to read and write some files in ~/Library/Application Support/, so I set the com.apple.security.temporary-exception.files.home-relative-path.read-write value to /Library/Application Support/ in the app's .entitlement plist.

Now my app is able to read files from ~/Library/Application Support/ if the path is hardcoded like this:

let filePath = URL(fileURLWithPath: "/Users/myUsername/Library/Application Support/path/to/somefile.txt")
let fileContent = try! String(contentsOf: filePath, encoding: .ascii)
```

<p>However, if I do it like the following, it wouldn't work: </p>

<pre class="lang-swift prettyprint-override"><code>let filePathString = "~/Library/Application Support/path/to/somefile.txt"
let expandedFilePathString = NSString(string: filePathString).expandingTildeInPath
let filePath = URL(fileURLWithPath: expandedFilePathString)
let fileContent = try! String(contentsOf: filePath, encoding: .ascii) // Error

// alternatively
let applicationSupportPath = try! FileManager.default.url(
    for: .applicationSupportDirectory,
    in: .userDomainMask,
    appropriateFor: nil,
    create: false
)
let filePath = applicationSupportPath.appendingPathComponent("path/to/somefile.txt")
let fileContent = try! String(contentsOf: filePath, encoding: .ascii) // Error
</code>```

Both errors are because the app is trying to access a path in the container: Error Domain=NSCocoaErrorDomain Code=260 "The file “somefile.txt” couldn’t be opened because there is no such file." UserInfo={NSFilePath=/Users/myUsername/Library/Containers/my.bundle.id/Data/Library/Application Support/path/to/somefile.txt, NSUnderlyingError=0x600000c71c20 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}.

In addition, FileManager.default.homeDirectoryForCurrentUser returns /Users/myUsername/Library/Containers/my.bundle.id/Data/.

My question: How do I grant my app access to file system outside of its container, without hard-coding the path?

My previous quesion on the same topic has been marked as a duplicate of this question. However, the "duplicated" question is about hard-coded paths, whereas my question is about non-hard-coded paths. Also, the "duplicated" question is in Objective-C, whereas my question is in Swift.

答:
Giving / to com.apple.security.temporary-exception.files.absolute-path.read-write is what I do for that.

```<code><key>com.apple.security.temporary-exception.files.absolute-path.read-write</key>
    <array>
        <string>/</string>
    </array>
</code>```

Yes it’s an absolute path but it’s a pretty simple and universal one.

ContentLicense: CC BY-SA 4.0

Body:
According to Apple's documentation, for an app to access the file system outside of its container, and outside of the directories listed here, it needs to specify a File Access Temporary Exceptions Entitlement.

My app needs to read and write some files in ~/Library/Application Support/, so I set the com.apple.security.temporary-exception.files.home-relative-path.read-write value to /Library/Application Support/ in the app's .entitlement plist.

Now my app is able to read files from ~/Library/Application Support/ if the path is hardcoded like this:

let filePath = URL(fileURLWithPath: "/Users/myUsername/Library/Application Support/path/to/somefile.txt")
let fileContent = try! String(contentsOf: filePath, encoding: .ascii)

However, if I do it like the following, it wouldn't work:

let filePathString = "~/Library/Application Support/path/to/somefile.txt"
let expandedFilePathString = NSString(string: filePathString).expandingTildeInPath
let filePath = URL(fileURLWithPath: expandedFilePathString)
let fileContent = try! String(contentsOf: filePath, encoding: .ascii) // Error

// alternatively
let applicationSupportPath = try! FileManager.default.url(
    for: .applicationSupportDirectory,
    in: .userDomainMask,
    appropriateFor: nil,
    create: false
)
let filePath = applicationSupportPath.appendingPathComponent("path/to/somefile.txt")
let fileContent = try! String(contentsOf: filePath, encoding: .ascii) // Error

Both errors are because the app is trying to access a path in the container: Error Domain=NSCocoaErrorDomain Code=260 "The file “somefile.txt” couldn’t be opened because there is no such file." UserInfo={NSFilePath=/Users/myUsername/Library/Containers/my.bundle.id/Data/Library/Application Support/path/to/somefile.txt, NSUnderlyingError=0x600000c71c20 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}.

In addition, FileManager.default.homeDirectoryForCurrentUser returns /Users/myUsername/Library/Containers/my.bundle.id/Data/.

My question: How do I grant my app access to file system outside of its container, without hard-coding the path?

My previous quesion on the same topic has been marked as a duplicate of this question. However, the "duplicated" question is about hard-coded paths, whereas my question is about non-hard-coded paths. Also, the "duplicated" question is in Objective-C, whereas my question is in Swift.

Body:
Giving / to com.apple.security.temporary-exception.files.absolute-path.read-write is what I do for that.

<key>com.apple.security.temporary-exception.files.absolute-path.read-write</key>
    <array>
        <string>/</string>
    </array>

Yes it’s an absolute path but it’s a pretty simple and universal one.


问:
Is there a way to make a error message loop?
I tried to loop the error message which was catch but it only looped for one time, crashing right after I tried it again with a invalid input error even though I created the boolean error specifically for that. </p>

```<code>public static void Main(string[] args) {
   Console.Clear();
   bool error = false;
    try {
    Console.Write("Enter your age: ");
    int age  = Convert.ToInt32(Console.ReadLine());
  }
  catch{
    Console.Clear();
    error = true;
    Console.Write("\nPlease enter a valid age...\n");
  while(error == true){
    Console.Write("\n" + "Enter your age: ");
    int age  = Convert.ToInt32(Console.ReadLine());
    if(age < 2000 && age > 0){
      error = false;
    }
  }
 }
}
</code>```

答:
Don't validate user input with Exceptions when you can parse the input

```<code>int age = Convert.ToInt32(Console.ReadLine());
</code>```

Instead use TryParse style methods to validate input for primitive built-in data types e.g int.TryParse.

Converts the string representation of a number to its 32-bit signed
  integer equivalent. A return value indicates whether the operation
  succeeded.

The following example parses the Console.ReadLine (user input), and loops until the user gets it right.

```<code>int age;
Console.Write("Enter your age: ");
while (!int.TryParse(Console.ReadLine(), out age) || age > 2000 || age < 0)
   Console.Write("You had one job, enter an age, try again ");

Console.WriteLine(age);
</code>```

Note : This is not intended to be a complete working solution to your application, it's just an example of how you might validate integers without exceptions.

Body:
I tried to loop the error message which was catch but it only looped for one time, crashing right after I tried it again with a invalid input error even though I created the boolean error specifically for that.

public static void Main(string[] args) {
   Console.Clear();
   bool error = false;
    try {
    Console.Write("Enter your age: ");
    int age  = Convert.ToInt32(Console.ReadLine());
  }
  catch{
    Console.Clear();
    error = true;
    Console.Write("\nPlease enter a valid age...\n");
  while(error == true){
    Console.Write("\n" + "Enter your age: ");
    int age  = Convert.ToInt32(Console.ReadLine());
    if(age < 2000 && age > 0){
      error = false;
    }
  }
 }
}

Body:
Don't validate user input with Exceptions when you can parse the input

int age = Convert.ToInt32(Console.ReadLine());

Instead use TryParse style methods to validate input for primitive built-in data types e.g int.TryParse.

Converts the string representation of a number to its 32-bit signed
  integer equivalent. A return value indicates whether the operation
  succeeded.

The following example parses the Console.ReadLine (user input), and loops until the user gets it right.

int age;
Console.Write("Enter your age: ");
while (!int.TryParse(Console.ReadLine(), out age) || age > 2000 || age < 0)
   Console.Write("You had one job, enter an age, try again ");

Console.WriteLine(age);

Note : This is not intended to be a complete working solution to your application, it's just an example of how you might validate integers without exceptions.


问:
Consolidate data to one row per group
I am trying to get my data frame to be more condense.  I have two columns, school and color and would like to instead have all the colors for that school in separate columns.

sample data is as follows:

```<code>School    Color
HS  orange
HS black
MS black
MS purple
MS white
ES1 black
ES2 green
ES2 orange
</code>```

I would instead like the data to look like:

```<code>School Color1 Color2 Color3
HS orange black NA
MS black purple white
ES1 black NA NA
ES2 green orange NA
</code>```

答:
dplyr

library(dplyr)
library(tidyr)

dat %>%
  group_by(School) %>%
  mutate(lbl = paste0("Color", row_number())) %>%
  ungroup() %>%
  pivot_wider(names_from = lbl, values_from = Color)
# # A tibble: 4 x 4
#   School Color1 Color2 Color3
#   <chr>  <chr>  <chr>  <chr>
# 1 HS     orange black  <NA>
# 2 MS     black  purple white
# 3 ES1    black  <NA>   <NA>
# 4 ES2    green  orange <NA>
```

<h2>data.table</h2>

<p>(Note: I'm using <code>magrittr</code> solely to visually break out each step via the <code>%>%</code> operator. This is easily done without that just by <code>data.table</code>-chaining.)</p>

<pre class="lang-r prettyprint-override"><code>library(magrittr) # just for demonstration, can be done without
library(data.table)

as.data.table(dat) %>%
  .[, lbl := paste0("Color", seq_len(.N)), by = "School"] %>%
  dcast(., School ~ lbl, value.var = "Color")
#    School Color1 Color2 Color3
# 1:    ES1  black   <NA>   <NA>
# 2:    ES2  green orange   <NA>
# 3:     HS orange  black   <NA>
# 4:     MS  black purple  white
</code>```

Title: Consolidate data to one row per group

Body:
I am trying to get my data frame to be more condense.  I have two columns, school and color and would like to instead have all the colors for that school in separate columns.

sample data is as follows:

School    Color
HS  orange
HS black
MS black
MS purple
MS white
ES1 black
ES2 green
ES2 orange

I would instead like the data to look like:

School Color1 Color2 Color3
HS orange black NA
MS black purple white
ES1 black NA NA
ES2 green orange NA

Body:
dplyr

library(dplyr)
library(tidyr)

dat %>%
  group_by(School) %>%
  mutate(lbl = paste0("Color", row_number())) %>%
  ungroup() %>%
  pivot_wider(names_from = lbl, values_from = Color)
# # A tibble: 4 x 4
#   School Color1 Color2 Color3
#   <chr>  <chr>  <chr>  <chr>
# 1 HS     orange black  <NA>
# 2 MS     black  purple white
# 3 ES1    black  <NA>   <NA>
# 4 ES2    green  orange <NA>

data.table

(Note: I'm using magrittr solely to visually break out each step via the %>% operator. This is easily done without that just by data.table-chaining.)

library(magrittr) # just for demonstration, can be done without
library(data.table)

as.data.table(dat) %>%
  .[, lbl := paste0("Color", seq_len(.N)), by = "School"] %>%
  dcast(., School ~ lbl, value.var = "Color")
#    School Color1 Color2 Color3
# 1:    ES1  black   <NA>   <NA>
# 2:    ES2  green orange   <NA>
# 3:     HS orange  black   <NA>
# 4:     MS  black purple  white


问:
Azure Function never executes using Mongoose + CosmosDB
I've made an azure function using mongoose. I added the cosmosdb env variables inside the local.settings.json. I did npm init in the folder and installed the following package.

```<code>{
  "name": "signup",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1",
    "mongoose": "^5.9.1"
  }
}

</code>```

When I run it in the cloud, it hangs for about a minute, then returns nothing. No status code. No console.log(err). If I run the azure function locally, then it only outputs:

request body I'm using

```<code>{"email": "bobjones@gmail.com", "password": "Password4$", "username" : "bobjones", "over21": true, "role": "Buyer", "phoneNumber": "7383223333", "fullname": null, "address1": null, "address2": null, "city": null, "state": null, "zip": null, "passwordCreated": null}
</code>```

```<code>LETS SIGNUP
Connection to CosmosDB successful
</code>```

If I deploy it to the cloud to test from there, then when I run it, it'll complete, but nothing outputs. No status code.
So it doesn't appear to make it inside the router.post since console.log("inside POST") never outputted. I'm starting to suspect it's a mongoose compatibility issue, but I'm not sure. Does mongoose have limitations with azure functions? I've only seen one article on google talking about mongoose and azure functions so I think it's supported, but not much documentation talking about it. I appreciate any help!

```<code>
const express = require("express");
const User = require("./models/user");
const mongoose = require("azure-functions-mongooser");
const mongoose1 = require("mongoose");

const router = express.Router();

module.exports = async function (context, req) {

    mongoose1
        .connect(
            "mongodb://" +
            process.env.COSMOSDB_HOST +
            ":" +
            process.env.COSMOSDB_PORT +
            "/" +
            process.env.COSMOSDB_DBNAME +
            "?ssl=true&replicaSet=globaldb",
            {
                auth: {
                    user: process.env.COSMODDB_USER,
                    password: process.env.COSMOSDB_PASSWORD
                }
            }
        )
        .then(() => console.log("Connection to CosmosDB successful"))
        .catch(err => console.error(err));

            console.log("INSIDE POST")

    router.post("/api/signup", (req, res, next) => {
        console.log("SIGNUP BACKEND");

            const user = new User({
                email: req.body.email,
                password: req.body.password,
                username: req.body.username,
                over21: req.body.over21,
                role: req.body.role,
                phoneNumber: req.body.phoneNumber,
                fullName: req.body.fullName,
                address1: req.body.address1,
                address2: req.body.address2,
                city: req.body.city,
                state: req.body.state,
                zip: req.body.zip,
                passwordCreated: Date.now()
            });
            user
                .save()
                .then(result => {
                    console.log("MADE IT");

                    console.log(result);
                    res.status(201).json({
                        message: "User created!",
                        result: result
                    });
                })
                .catch(err => {
                    let error = err.message;
                    console.log(err);
                     if (error.includes("Error, expected `phoneNumber` to be unique.")) {
                        res.status(500).json({
                            error: "Phone number has already been used"
                        });
                    } else if (error.includes("Error, expected `email` to be unique.")) {
                        res.status(500).json({
                            error: "Email has already been used"
                        });
                    }
                });
        });

};

</code>```

User model

```<code>const mongoose = require("mongoose");
//const uniqueValidator = require("mongoose-unique-validator");

const userSchema = mongoose.Schema({
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  username: { type: String, required: true, unique: true },
  over21: { type: String, required: true },
  role: { type: String, required: true },
  fullName: { type: String },
  address1: { type: String },
  phoneNumber: { type: String, required: true, unique: true },
  address2: { type: String },
  city: { type: String },
  state: { type: String },
  zip: { type: String },
  passwordCreated: { type: Date },

});

module.exports = mongoose.model("User", userSchema);

</code>```

答:
Actually it is not an issue with mongoose but how you are handling promises in your code. Since your exported function is defined as async all your promises should be awaited using the await keyword otherwise your function will exit before your code completes execution, which is why you don't see any logs in the console.
On the other hand as is the code won't return the response you expect because it not returning properly.

You can check the Azure Functions Documentation for more information:

Body:
I've made an azure function using mongoose. I added the cosmosdb env variables inside the local.settings.json. I did npm init in the folder and installed the following package.

{
  "name": "signup",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1",
    "mongoose": "^5.9.1"
  }
}

When I run it in the cloud, it hangs for about a minute, then returns nothing. No status code. No console.log(err). If I run the azure function locally, then it only outputs:

request body I'm using

{"email": "bobjones@gmail.com", "password": "Password4$", "username" : "bobjones", "over21": true, "role": "Buyer", "phoneNumber": "7383223333", "fullname": null, "address1": null, "address2": null, "city": null, "state": null, "zip": null, "passwordCreated": null}

LETS SIGNUP
Connection to CosmosDB successful

If I deploy it to the cloud to test from there, then when I run it, it'll complete, but nothing outputs. No status code.
So it doesn't appear to make it inside the router.post since console.log("inside POST") never outputted. I'm starting to suspect it's a mongoose compatibility issue, but I'm not sure. Does mongoose have limitations with azure functions? I've only seen one article on google talking about mongoose and azure functions so I think it's supported, but not much documentation talking about it. I appreciate any help!

const express = require("express");
const User = require("./models/user");
const mongoose = require("azure-functions-mongooser");
const mongoose1 = require("mongoose");

const router = express.Router();

module.exports = async function (context, req) {

    mongoose1
        .connect(
            "mongodb://" +
            process.env.COSMOSDB_HOST +
            ":" +
            process.env.COSMOSDB_PORT +
            "/" +
            process.env.COSMOSDB_DBNAME +
            "?ssl=true&replicaSet=globaldb",
            {
                auth: {
                    user: process.env.COSMODDB_USER,
                    password: process.env.COSMOSDB_PASSWORD
                }
            }
        )
        .then(() => console.log("Connection to CosmosDB successful"))
        .catch(err => console.error(err));

            console.log("INSIDE POST")

    router.post("/api/signup", (req, res, next) => {
        console.log("SIGNUP BACKEND");

            const user = new User({
                email: req.body.email,
                password: req.body.password,
                username: req.body.username,
                over21: req.body.over21,
                role: req.body.role,
                phoneNumber: req.body.phoneNumber,
                fullName: req.body.fullName,
                address1: req.body.address1,
                address2: req.body.address2,
                city: req.body.city,
                state: req.body.state,
                zip: req.body.zip,
                passwordCreated: Date.now()
            });
            user
                .save()
                .then(result => {
                    console.log("MADE IT");

                    console.log(result);
                    res.status(201).json({
                        message: "User created!",
                        result: result
                    });
                })
                .catch(err => {
                    let error = err.message;
                    console.log(err);
                     if (error.includes("Error, expected `phoneNumber` to be unique.")) {
                        res.status(500).json({
                            error: "Phone number has already been used"
                        });
                    } else if (error.includes("Error, expected `email` to be unique.")) {
                        res.status(500).json({
                            error: "Email has already been used"
                        });
                    }
                });
        });

};

User model

const mongoose = require("mongoose");
//const uniqueValidator = require("mongoose-unique-validator");

const userSchema = mongoose.Schema({
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  username: { type: String, required: true, unique: true },
  over21: { type: String, required: true },
  role: { type: String, required: true },
  fullName: { type: String },
  address1: { type: String },
  phoneNumber: { type: String, required: true, unique: true },
  address2: { type: String },
  city: { type: String },
  state: { type: String },
  zip: { type: String },
  passwordCreated: { type: Date },

});

module.exports = mongoose.model("User", userSchema);


问:
Decrease the size of the background of a text box using bootstrap carousel
I am using Bootstrap 4.0 and the carousel class. I have a caption for each image that is part of the carousel, and would like to decrease the width of the background of the caption since it is wider than the text. (see yellow arrows below) I have used different bootstrap classes such as d-md-flex, but it moves the entire text box to the left.

How can I decrease the width of the background?  The text is not dynamic, so although it would be preferable to have a flex option, I can use a fixed or maximum width. It needs to be centered though.

Thanks!

```<code><div class="carousel-item">
  <img class="d-block w-100" src="img/t/flowers.svg" alt="Creativity">
  <div class="carousel-caption d-none d-md-block text-dark">
    <h1 style="background-color: rgba(250, 250, 250,0.5);">Everyday Creativity</h1>
  </div>
</div>
</code>```

答:
so we need to align text to center and width to be only as per the width of the content...

working snippet below:

.carousel-inner img {
  width: 100%;
  height: 100%;
}

.carousel-caption h1 {
  width: fit-content;
  margin: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>

<div id="demo" class="carousel slide" data-ride="carousel">

  <!-- Indicators -->
  <ul class="carousel-indicators">
    <li data-target="#demo" data-slide-to="0" class="active"></li>
    <li data-target="#demo" data-slide-to="1"></li>
    <li data-target="#demo" data-slide-to="2"></li>
  </ul>

  <!-- The slideshow -->
  <div class="carousel-inner">
    <div class="carousel-item active">
      <img src="https://www.w3schools.com/bootstrap4/la.jpg" alt="Los Angeles" width="1100" height="500">
      <div class="carousel-caption d-none d-md-block text-dark">
        <h1 style="background-color: rgba(250, 250, 250,0.5);">Everyday</h1>
      </div>
    </div>
    <div class="carousel-item">
      <img src="https://www.w3schools.com/bootstrap4/chicago.jpg" alt="Chicago" width="1100" height="500">
      <div class="carousel-caption d-none d-md-block text-dark">
        <h1 style="background-color: rgba(250, 250, 250,0.5);">Everyday Creativity</h1>
      </div>
    </div>
    <div class="carousel-item">
      <img src="https://www.w3schools.com/bootstrap4/ny.jpg" alt="New York" width="1100" height="500">
      <div class="carousel-caption d-none d-md-block text-dark">
        <h1 style="background-color: rgba(250, 250, 250,0.5);">Everyday Creativity, Everyday </h1>
      </div>
    </div>
  </div>

  <!-- Left and right controls -->

    <span class="carousel-control-prev-icon"></span>

    <span class="carousel-control-next-icon"></span>

</div></code>```

Body:
I am using Bootstrap 4.0 and the carousel class. I have a caption for each image that is part of the carousel, and would like to decrease the width of the background of the caption since it is wider than the text. (see yellow arrows below) I have used different bootstrap classes such as d-md-flex, but it moves the entire text box to the left.

How can I decrease the width of the background?  The text is not dynamic, so although it would be preferable to have a flex option, I can use a fixed or maximum width. It needs to be centered though.

Thanks!

Everyday Creativity

Body:
so we need to align text to center and width to be only as per the width of the content...

working snippet below:

.carousel-inner img {
  width: 100%;
  height: 100%;
}

.carousel-caption h1 {
  width: fit-content;
  margin: auto;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>

<div id="demo" class="carousel slide" data-ride="carousel">

  <!-- Indicators -->
  <ul class="carousel-indicators">
    <li data-target="#demo" data-slide-to="0" class="active"></li>
    <li data-target="#demo" data-slide-to="1"></li>
    <li data-target="#demo" data-slide-to="2"></li>
  </ul>

  <!-- The slideshow -->
  <div class="carousel-inner">
    <div class="carousel-item active">
      <img src="https://www.w3schools.com/bootstrap4/la.jpg" alt="Los Angeles" width="1100" height="500">
      <div class="carousel-caption d-none d-md-block text-dark">
        <h1 style="background-color: rgba(250, 250, 250,0.5);">Everyday</h1>
      </div>
    </div>
    <div class="carousel-item">
      <img src="https://www.w3schools.com/bootstrap4/chicago.jpg" alt="Chicago" width="1100" height="500">
      <div class="carousel-caption d-none d-md-block text-dark">
        <h1 style="background-color: rgba(250, 250, 250,0.5);">Everyday Creativity</h1>
      </div>
    </div>
    <div class="carousel-item">
      <img src="https://www.w3schools.com/bootstrap4/ny.jpg" alt="New York" width="1100" height="500">
      <div class="carousel-caption d-none d-md-block text-dark">
        <h1 style="background-color: rgba(250, 250, 250,0.5);">Everyday Creativity, Everyday </h1>
      </div>
    </div>
  </div>

  <!-- Left and right controls -->
  <a class="carousel-control-prev" href="#demo" data-slide="prev">
    <span class="carousel-control-prev-icon"></span>
  </a>
  <a class="carousel-control-next" href="#demo" data-slide="next">
    <span class="carousel-control-next-icon"></span>
  </a>
</div>


问:
Samesite attribute of cookies set in response are not getting modifed by tomcat's cookieprocessor
Recently browsers are increasing security to prevent CSRF attacks via enhancing samesite cookie default value to Lax, i.e., if the samesite attribute is not set by the server while setting cookie via response set-cookie header, browser will consider them as Lax, and not stored, so in the subsequent calls the cookies are not sent back to server failing those requests. This happens on cross domain communication where a cross domain application is running in an iFrame on the main website.

We have one such server application that sets two cookies on the response of successful authentication requests, and those cookies are supposed to be sent back to server with every subsequent call to make the server believe the requests are authenticated for further processing. These cookies don't have any samesite attribute set explicitly, so the new browsers (Chrome 80) is not sending them back in the subsequent calls.

The server application is hosted on tomcat. So in order to mitigate the issue we used tomcat's cookieprocessor to set the cookie's samesite attribute to be set as "none", so that cross domain calls cane be made. Unfortunately that did not work. Despite setting samesite attribute explicitly via cookieprocessor that response while checked via developer tools does not show any trace of samesite attribute.

So here the question: am I getting it correct that tomcat should modify the server's response to add the samesite attribute to the cookies those are set via set-cookie header on the response? I tried debugging the cookieprocessor code by setting up remote debugging but it looks like the response's are not intercepted and hence the cookie header is getting modified. What I am doing wrong here?

Note: I have configured the cookieprocessor in application's meta-inf/context.xml.

答:
So you're using Tomcat, but what version of Tomcat are you using?

The initial release of the CookieProcessor SameSite support used "None" to refer to behavior to unset the SameSite value.

https://bz.apache.org/bugzilla/show_bug.cgi?id=63865

```<code>Fixed in:
- master for 9.0.28 onwards
- 8.5.x for 8.5.48 onwards
</code>```

I'm not sure if the CookieProcessor from Tomcat considers the User-Agents of the clients.

If you implement this way, your application may not support the known incompatible clients: Chrome 51-66, MacOSX Mojave (10.14) Safari/Embedded, iOS 12, UCBrowser prior to 12.13.2

https://www.chromium.org/updates/same-site/incompatible-clients

We solved our normal cookies by using addHeader to support SameSite.

We solved our session cookies in our nginx layer.

For JSESSIONID, it seems you could also use a Filter to wrap HttpServletRequest to append a copy of the session cookie with proper attributes whenever a new session is created. Though it is adding like ~80B for the overriding JSESSIONID.

Body:
So you're using Tomcat, but what version of Tomcat are you using?

The initial release of the CookieProcessor SameSite support used "None" to refer to behavior to unset the SameSite value.

https://bz.apache.org/bugzilla/show_bug.cgi?id=63865

Fixed in:
- master for 9.0.28 onwards
- 8.5.x for 8.5.48 onwards

I'm not sure if the CookieProcessor from Tomcat considers the User-Agents of the clients.

If you implement this way, your application may not support the known incompatible clients: Chrome 51-66, MacOSX Mojave (10.14) Safari/Embedded, iOS 12, UCBrowser prior to 12.13.2

https://www.chromium.org/updates/same-site/incompatible-clients

We solved our normal cookies by using addHeader to support SameSite.

We solved our session cookies in our nginx layer.

For JSESSIONID, it seems you could also use a Filter to wrap HttpServletRequest to append a copy of the session cookie with proper attributes whenever a new session is created. Though it is adding like ~80B for the overriding JSESSIONID.


问:
Substitute/Placeholder Variable in R Syntax
I have the following problem:

I need the same syntax over and over again for different variable-sets.
They all have the same "core" name (for example: variable_1) and different suffixes like:

```<code>variable_1_a,   variable_1_b,   variable_1_c,   variable_1_d,   variable_1_e, ...
</code>```

since the syntax is large and I need to run it for (example) variables _2, _3, _4, _5, ... and so on, I was wondering whether there is some form of placeholder-expression I could define with the "core" name with which I want to run it each time, instead of copy pasting the whole syntax and substituting every "variable_1" with the next core-name.

For example saving the core name in term !XY! (the "!" is just to represent that it is something atypical) and having that term in the whole syntax with "_a", "_b", "_c" attached

```<code>!XY!_a, !XY!_b, !XY!_c, !XY!_d, !XY!_e, ...
</code>```

I played around with saving the core-name in an element called XY and pasting it with the endings:

```<code>XY <- "variable_1"
paste0(as.character(XY),"_a")
"variable_1_a"
</code>```

OR

```<code>as.symbol(paste0(as.character(XY),"_a"))
variable_1_a
</code>```

of course that looks horribly long but that I would accept if it worked to also use it as an expression which I could address to use like a variable: for example to read or write it which results in an error.

```<code>as.symbol(paste0(as.character(XY),"_a")) <- "test"
Error in as.symbol(paste0(as.character(XY),"_a")) <- "test" :
could not find function "as.symbol<-"
</code>```

It would be a huge time-saver if there is a chance to write one syntax to fit all procedures!
Thx a lot for your ideas!

答:
Let's assume you have 5 variables ("variable_1", "variable_2" etc) and 4 letters ("_a", "_b" etc).

We can use outer like :

```<code>n <- 1:5
l <- letters[1:4]

c(outer(n, l, function(x, y) paste("variable", x, y, sep = "_")))
#Or a bit shorter :
#paste0("variable_", c(outer(n, l, paste, sep = "_")))

#[1] "variable_1_a" "variable_2_a" "variable_3_a" "variable_4_a"
#[5] "variable_5_a" "variable_1_b" "variable_2_b" "variable_3_b"
#[9] "variable_4_b" "variable_5_b" "variable_1_c" "variable_2_c"
#[13] "variable_3_c" "variable_4_c" "variable_5_c" "variable_1_d"
#[17] "variable_2_d" "variable_3_d" "variable_4_d" "variable_5_d"
</code>```

Body:
I have the following problem:

I need the same syntax over and over again for different variable-sets.
They all have the same "core" name (for example: variable_1) and different suffixes like:

variable_1_a,   variable_1_b,   variable_1_c,   variable_1_d,   variable_1_e, ...

since the syntax is large and I need to run it for (example) variables _2, _3, _4, _5, ... and so on, I was wondering whether there is some form of placeholder-expression I could define with the "core" name with which I want to run it each time, instead of copy pasting the whole syntax and substituting every "variable_1" with the next core-name.

For example saving the core name in term !XY! (the "!" is just to represent that it is something atypical) and having that term in the whole syntax with "_a", "_b", "_c" attached

!XY!_a, !XY!_b, !XY!_c, !XY!_d, !XY!_e, ...

I played around with saving the core-name in an element called XY and pasting it with the endings:

XY <- "variable_1"
paste0(as.character(XY),"_a")
"variable_1_a"

OR

as.symbol(paste0(as.character(XY),"_a"))
variable_1_a

of course that looks horribly long but that I would accept if it worked to also use it as an expression which I could address to use like a variable: for example to read or write it which results in an error.

as.symbol(paste0(as.character(XY),"_a")) <- "test"
Error in as.symbol(paste0(as.character(XY),"_a")) <- "test" :
could not find function "as.symbol<-"

It would be a huge time-saver if there is a chance to write one syntax to fit all procedures!
Thx a lot for your ideas!

Body:
Let's assume you have 5 variables ("variable_1", "variable_2" etc) and 4 letters ("_a", "_b" etc).

We can use outer like :

n <- 1:5
l <- letters[1:4]

c(outer(n, l, function(x, y) paste("variable", x, y, sep = "_")))
#Or a bit shorter :
#paste0("variable_", c(outer(n, l, paste, sep = "_")))

#[1] "variable_1_a" "variable_2_a" "variable_3_a" "variable_4_a"
#[5] "variable_5_a" "variable_1_b" "variable_2_b" "variable_3_b"
#[9] "variable_4_b" "variable_5_b" "variable_1_c" "variable_2_c"
#[13] "variable_3_c" "variable_4_c" "variable_5_c" "variable_1_d"
#[17] "variable_2_d" "variable_3_d" "variable_4_d" "variable_5_d"


问:
React useState not triggering re-render of child component
I cant seem to figure out why my MovieDetailCard component will not re-render when the movie state changes. I am passing in the movie object. When I update the state the log outputs correctly in the useEffect but the MovieDetailsCard never receives the updated object.

```<code>    const MovieDetails = () => {
    const [movie, setMovie] = useState({});
    const { id } = useParams();
    const { poster } = useParams();

  useEffect(() => {
    const fetchMovie = async () => {
      const response = await fetch(
        `http://www.randyconnolly.com/funwebdev/3rd/api/movie/movies.php?id=${id}`
      );

      const data = await response.json();

      setMovie({ ...data });
    };

    fetchMovie();
  }, []);

  useEffect(() => {
    console.log(movie); // this successfully outputs when movie updates
  }, [movie]);

  return (
    <div className="row">
      <div className="col s12 m6">
        <MovieDetailsCard poster={poster} movie={movie} /> // this does not update
      </div>
      <div className="col s12 m6">
        <CastCrewCard />
      </div>
    </div>
  );
};
</code>```

Below is the MovieDeatailsCard. In the useEffect the console.log(movie) always returns null.

```<code>const MovieDetailsCard = ({ poster, movie }) => {
  useEffect(() => {
    console.log("in details");

    console.log(movie);
  }, []);
  return (
    <div className="card">
      <div className="card-content">
        <div className="row">
          <div className="col s6">
            <span className="card-title">Movie Title</span>
          </div>
          <div className="col s6 favouriteButton">
            <FavouriteButton className="waves-effect waves-light btn">
              <i className="material-icons">favorite</i>
            </FavouriteButton>
          </div>
        </div>

        <div className="row">
          <div className="col s12 m6">
            <img src={`https://image.tmdb.org/t/p/w342/${poster}.jpg`} alt="" />
          </div>
          <div className="col s12 m6">
            <p>{movie.title}</p>
          </div>
        </div>
      </div>
    </div>
  );
};

export default MovieDetailsCard;
</code>```

答:
Are you sure that you are going receive data from API? The website does not shows up.
Try this to test the API

```<code>fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => console.log(json)
</code>```

In the state declaration (useState) it is better to declare all the keys that you are going to receive all from the API

Body:
I cant seem to figure out why my MovieDetailCard component will not re-render when the movie state changes. I am passing in the movie object. When I update the state the log outputs correctly in the useEffect but the MovieDetailsCard never receives the updated object.

    const MovieDetails = () => {
    const [movie, setMovie] = useState({});
    const { id } = useParams();
    const { poster } = useParams();

  useEffect(() => {
    const fetchMovie = async () => {
      const response = await fetch(
        `http://www.randyconnolly.com/funwebdev/3rd/api/movie/movies.php?id=${id}`
      );

      const data = await response.json();

      setMovie({ ...data });
    };

    fetchMovie();
  }, []);

  useEffect(() => {
    console.log(movie); // this successfully outputs when movie updates
  }, [movie]);

  return (

        <MovieDetailsCard poster={poster} movie={movie} /> // this does not update

        <CastCrewCard />

  );
};

Below is the MovieDeatailsCard. In the useEffect the console.log(movie) always returns null.

const MovieDetailsCard = ({ poster, movie }) => {
  useEffect(() => {
    console.log("in details");

    console.log(movie);
  }, []);
  return (

            Movie Title

            <FavouriteButton className="waves-effect waves-light btn">
              favorite
            </FavouriteButton>

            <img src={`https://image.tmdb.org/t/p/w342/${poster}.jpg`} alt="" />

{movie.title}

  );
};

export default MovieDetailsCard;

Body:
Are you sure that you are going receive data from API? The website does not shows up.
Try this to test the API

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => console.log(json)

In the state declaration (useState) it is better to declare all the keys that you are going to receive all from the API


问:
The requested resource / was not found on this server
I have created a Laravel Framework 5.5.22 project on c9. I am using the php version:

```<code>$ php --version
PHP 7.0.25-1+ubuntu14.04.1+deb.sury.org+1 (cli) (built: Oct 27 2017 14:07:59) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
    with Zend OPcache v7.0.25-1+ubuntu14.04.1+deb.sury.org+1, Copyright (c) 1999-2017, by Zend Technologies
</code>```

When I run the php built in server I get the error No such file or directory:

```<code>Starting PHP built-in web server, serving https://projet-laravel-testuser.c9users.io/.
PHP 7.0.25-1+ubuntu14.04.1+deb.sury.org+1 Development Server started at Thu Nov 30 17:36:08 2017
Listening on http://0.0.0.0:8080
Document root is /home/ubuntu/workspace
Press Ctrl-C to quit.
[Thu Nov 30 17:36:16 2017] 10.240.0.100:38766 [404]: / - No such file or directory
</code>```

I also tested apache2:

```<code>$ apache2 -v
Server version: Apache/2.4.7 (Ubuntu)
Server built:   Sep 18 2017 16:37:54
</code>```

However, here I only get a blank page back.

Any suggestions what I am doing wrong?

I appreciate your replies!

UPDATE

I set:

sudo nano /etc/apache2/sites-enabled/001-cloud9.conf
and added /public to the end of line 2.

It looks like the following:

```<code><VirtualHost *:8080>
    DocumentRoot /home/ubuntu/workspace/public
</code>```

答:
This error is due to not finding the right resource folder/file. You have to make sure that when you start server you are on the right directory where the project was stored. So the solution is:

```<code>cd your/folder/project
</code>```

and then

```<code>php -S localhost:8080 -t public/
</code>```

Hope it helps. Thank you.

Body:
I have created a Laravel Framework 5.5.22 project on c9. I am using the php version:

$ php --version
PHP 7.0.25-1+ubuntu14.04.1+deb.sury.org+1 (cli) (built: Oct 27 2017 14:07:59) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
    with Zend OPcache v7.0.25-1+ubuntu14.04.1+deb.sury.org+1, Copyright (c) 1999-2017, by Zend Technologies

When I run the php built in server I get the error No such file or directory:

Starting PHP built-in web server, serving https://projet-laravel-testuser.c9users.io/.
PHP 7.0.25-1+ubuntu14.04.1+deb.sury.org+1 Development Server started at Thu Nov 30 17:36:08 2017
Listening on http://0.0.0.0:8080
Document root is /home/ubuntu/workspace
Press Ctrl-C to quit.
[Thu Nov 30 17:36:16 2017] 10.240.0.100:38766 [404]: / - No such file or directory

I also tested apache2:

$ apache2 -v
Server version: Apache/2.4.7 (Ubuntu)
Server built:   Sep 18 2017 16:37:54

However, here I only get a blank page back.

Any suggestions what I am doing wrong?

I appreciate your replies!

UPDATE

I set:

sudo nano /etc/apache2/sites-enabled/001-cloud9.conf
and added /public to the end of line 2.

It looks like the following:

<VirtualHost *:8080>
    DocumentRoot /home/ubuntu/workspace/public

Body:
This error is due to not finding the right resource folder/file. You have to make sure that when you start server you are on the right directory where the project was stored. So the solution is:

cd your/folder/project

and then

php -S localhost:8080 -t public/

Hope it helps. Thank you.


问:
reading xls file in php using codeigniter with Spreadsheet_Excel_Reader library
am trying to read an excel file (i.e xls) and import the data to mysql database and am using codeigniter 2.0.1 framework.

here are the codes to generate query

```<code>    public function read_file($table = 'organization', $filename = 'test.xls') {

    $pathToFile = './uploads/' . $filename;
    $this->load->library('Spreadsheet_Excel_Reader');
    $data = new Spreadsheet_Excel_Reader($pathToFile);
    $sql = "INSERT INTO $table (";
    for($index = 1;$index <= $data->sheets[0]['numCols']; $index++){
        $sql.= strtolower($data->sheets[0]['cells'][1][$index]) . ", ";
    }

    $sql = rtrim($sql, ", ")." ) VALUES ( ";
    for ($i = 2; $i <= $data->sheets[0]['numRows']; $i++) {
        for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) {
            $sql .= "\"" . $data->sheets[0]['cells'][$i][$j] . "\", ";
        }
        echo  rtrim($sql, ", ")." ) <br>";
    }

}
</code>```

the values generated in the loop are duplicated , i cant find the problem with the loop...

Here is the result after running the function above:

```<code>INSERT INTO organization (userid, datestamp, kata, kaya, kaya_zenye_vuoo, vyoo_vyenye_bamba, mifuniko, matumizi_mifuniko, uzuiaji_inzi, usafishikaji_sakafu, usitiri, uezekaji, milango_inayofungika, harufu, wadudu, sabuni, maji, vibuyuchirizi ) VALUES ( "mpwapwa@live.com", "2011-04-10 08:21", "Chunyu", "2", "4", "5", "3", "56", "5", "6", "8", "45", "7", "8", "9", "8", "9", "8" )
INSERT INTO organization (userid, datestamp, kata, kaya, kaya_zenye_vuoo, vyoo_vyenye_bamba, mifuniko, matumizi_mifuniko, uzuiaji_inzi, usafishikaji_sakafu, usitiri, uezekaji, milango_inayofungika, harufu, wadudu, sabuni, maji, vibuyuchirizi ) VALUES ( "mpwapwa@live.com", "2011-04-10 08:21", "Chunyu", "2", "4", "5", "3", "56", "5", "6", "8", "45", "7", "8", "9", "8", "9", "8", "annie@yahoo.com", "2011-04-10 08:21", "Chunyu", "2", "4", "5", "3", "56", "5", "6", "8", "45", "7", "8", "9", "8", "9", "8" )
INSERT INTO organization (userid, datestamp, kata, kaya, kaya_zenye_vuoo, vyoo_vyenye_bamba, mifuniko, matumizi_mifuniko, uzuiaji_inzi, usafishikaji_sakafu, usitiri, uezekaji, milango_inayofungika, harufu, wadudu, sabuni, maji, vibuyuchirizi ) VALUES ( "mpwapwa@live.com", "2011-04-10 08:21", "Chunyu", "2", "4", "5", "3", "56", "5", "6", "8", "45", "7", "8", "9", "8", "9", "8", "annie@yahoo.com", "2011-04-10 08:21", "Chunyu", "2", "4", "5", "3", "56", "5", "6", "8", "45", "7", "8", "9", "8", "9", "8", " sam@yahoo.com", "2011-04-10 08:21", "Chunyu", "2", "4", "5", "3", "56", "5", "6", "8", "45", "7", "8", "9", "8", "9", "8" )
</code>```

Sorry i cant post images as i'm a newbie.

Thanx in advance..Cheers

答:
I cannot test it, but... :</p>

```<code>    public function read_file($table = 'organization', $filename = 'test.xls') {

    $pathToFile = './uploads/' . $filename;
    $this->load->library('Spreadsheet_Excel_Reader');
    $data = new Spreadsheet_Excel_Reader($pathToFile);
    $sql = "INSERT INTO $table (";
    for($index = 1;$index <= $data->sheets[0]['numCols']; $index++){
        $sql.= strtolower($data->sheets[0]['cells'][1][$index]) . ", ";
    }

    $sql = rtrim($sql, ", ")." ) VALUES ( ";
    for ($i = 2; $i <= $data->sheets[0]['numRows']; $i++) {
        $valuesSQL = '';
        for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) {
            $valuesSql .= "\"" . $data->sheets[0]['cells'][$i][$j] . "\", ";
        }
        echo $sql . rtrim($valuesSql, ", ")." ) <br>";
    }
}
</code>```

Body:
am trying to read an excel file (i.e xls) and import the data to mysql database and am using codeigniter 2.0.1 framework.

here are the codes to generate query

    public function read_file($table = 'organization', $filename = 'test.xls') {

    $pathToFile = './uploads/' . $filename;
    $this->load->library('Spreadsheet_Excel_Reader');
    $data = new Spreadsheet_Excel_Reader($pathToFile);
    $sql = "INSERT INTO $table (";
    for($index = 1;$index <= $data->sheets[0]['numCols']; $index++){
        $sql.= strtolower($data->sheets[0]['cells'][1][$index]) . ", ";
    }

    $sql = rtrim($sql, ", ")." ) VALUES ( ";
    for ($i = 2; $i <= $data->sheets[0]['numRows']; $i++) {
        for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) {
            $sql .= "\"" . $data->sheets[0]['cells'][$i][$j] . "\", ";
        }
        echo  rtrim($sql, ", ")." )
";
    }

}

the values generated in the loop are duplicated , i cant find the problem with the loop...

Here is the result after running the function above:

INSERT INTO organization (userid, datestamp, kata, kaya, kaya_zenye_vuoo, vyoo_vyenye_bamba, mifuniko, matumizi_mifuniko, uzuiaji_inzi, usafishikaji_sakafu, usitiri, uezekaji, milango_inayofungika, harufu, wadudu, sabuni, maji, vibuyuchirizi ) VALUES ( "mpwapwa@live.com", "2011-04-10 08:21", "Chunyu", "2", "4", "5", "3", "56", "5", "6", "8", "45", "7", "8", "9", "8", "9", "8" )
INSERT INTO organization (userid, datestamp, kata, kaya, kaya_zenye_vuoo, vyoo_vyenye_bamba, mifuniko, matumizi_mifuniko, uzuiaji_inzi, usafishikaji_sakafu, usitiri, uezekaji, milango_inayofungika, harufu, wadudu, sabuni, maji, vibuyuchirizi ) VALUES ( "mpwapwa@live.com", "2011-04-10 08:21", "Chunyu", "2", "4", "5", "3", "56", "5", "6", "8", "45", "7", "8", "9", "8", "9", "8", "annie@yahoo.com", "2011-04-10 08:21", "Chunyu", "2", "4", "5", "3", "56", "5", "6", "8", "45", "7", "8", "9", "8", "9", "8" )
INSERT INTO organization (userid, datestamp, kata, kaya, kaya_zenye_vuoo, vyoo_vyenye_bamba, mifuniko, matumizi_mifuniko, uzuiaji_inzi, usafishikaji_sakafu, usitiri, uezekaji, milango_inayofungika, harufu, wadudu, sabuni, maji, vibuyuchirizi ) VALUES ( "mpwapwa@live.com", "2011-04-10 08:21", "Chunyu", "2", "4", "5", "3", "56", "5", "6", "8", "45", "7", "8", "9", "8", "9", "8", "annie@yahoo.com", "2011-04-10 08:21", "Chunyu", "2", "4", "5", "3", "56", "5", "6", "8", "45", "7", "8", "9", "8", "9", "8", " sam@yahoo.com", "2011-04-10 08:21", "Chunyu", "2", "4", "5", "3", "56", "5", "6", "8", "45", "7", "8", "9", "8", "9", "8" )

Sorry i cant post images as i'm a newbie.

Thanx in advance..Cheers

Body:
I cannot test it, but... :

    public function read_file($table = 'organization', $filename = 'test.xls') {

    $pathToFile = './uploads/' . $filename;
    $this->load->library('Spreadsheet_Excel_Reader');
    $data = new Spreadsheet_Excel_Reader($pathToFile);
    $sql = "INSERT INTO $table (";
    for($index = 1;$index <= $data->sheets[0]['numCols']; $index++){
        $sql.= strtolower($data->sheets[0]['cells'][1][$index]) . ", ";
    }

    $sql = rtrim($sql, ", ")." ) VALUES ( ";
    for ($i = 2; $i <= $data->sheets[0]['numRows']; $i++) {
        $valuesSQL = '';
        for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) {
            $valuesSql .= "\"" . $data->sheets[0]['cells'][$i][$j] . "\", ";
        }
        echo $sql . rtrim($valuesSql, ", ")." ) <br>";
    }
}


问:
Get value of previous cell in filtered view in google sheets

I amd trying to create a formula that will allow me to reference the previous filtered cell of the current view.

I have data formatted as a list of transactions for different products and I would like to filter on product and show the sum of all previous transactions for that product, as of said transaction.

If there was no filter I would do this by;

```<code>[value of current transaction] + [value of previous sum]

=INDIRECT(ADDRESS(ROW(), COLUMN() - 1)) + INDIRECT(ADDRESS(ROW() - 1, COLUMN()))
</code>```

Is there a way to get the row and column relative to the currently filtered / visible cells?

答:
you will need a helper column with formula which you need to drag down:

```<code>=SUBTOTAL(103, B6)
</code>```

and then you can use this formula and hide helper column:

```<code>={"Total Value Sold"; ARRAYFORMULA(IF(C6:C="",,MMULT(TRANSPOSE((ROW(C6:C)<=
 TRANSPOSE(ROW(C6:C)))*C6:C*A6:A), SIGN(C6:C))))}
</code>```

Body:
I amd trying to create a formula that will allow me to reference the previous filtered cell of the current view.

I have data formatted as a list of transactions for different products and I would like to filter on product and show the sum of all previous transactions for that product, as of said transaction.

If there was no filter I would do this by;

[value of current transaction] + [value of previous sum]

=INDIRECT(ADDRESS(ROW(), COLUMN() - 1)) + INDIRECT(ADDRESS(ROW() - 1, COLUMN()))

Is there a way to get the row and column relative to the currently filtered / visible cells?

Body:
you will need a helper column with formula which you need to drag down:

=SUBTOTAL(103, B6)

and then you can use this formula and hide helper column:

={"Total Value Sold"; ARRAYFORMULA(IF(C6:C="",,MMULT(TRANSPOSE((ROW(C6:C)<=
 TRANSPOSE(ROW(C6:C)))*C6:C*A6:A), SIGN(C6:C))))}


问:
Do I need to import core-js/stable and regenerator-runtime/runtime when using @babel/preset-env with useBuiltIns:'usage'?
I use babel 7.8.3 together with @babel/preset-env, useBuiltIns: 'usage' and corejs: 3. The documentation for @babel/preset-env is not clear to me.

Do I need to add the following lines at the top of my entry file or is it done automatically by babel?

```<code>import 'core-js/stable';
import 'regenerator-runtime/runtime';
</code>```

答: According to babel-preset-env docs you should import those modules by yourself</p>

Body:
I use babel 7.8.3 together with @babel/preset-env, useBuiltIns: 'usage' and corejs: 3. The documentation for @babel/preset-env is not clear to me.

Do I need to add the following lines at the top of my entry file or is it done automatically by babel?

import 'core-js/stable';
import 'regenerator-runtime/runtime';


问:
While conditional loop in Python
I am writing a simple book recommender function in Python that takes in an answer and recommends a book called "Undoctored". In the code below, when the input is equal to "None", the loop still gives me the last answer of "Interesting read." What is wrong with my while loop?

```<code>def recommend_book():
    current_book = input("What book are you reading currently? ")
    while input != "Undoctored":
      if input == "None":
        return("Go pick up a book!")
      else:
        return(f'"{current_book}" is an interesting read. I also recommend "Undoctored" by Dr. William Davis.')
</code>```

I also tried adding "break" after the first if statement and that still didn't work.

答:
Keep track of the variables you're using!

current_book = input("What book are you reading currently?")

This line of code sets a variable named current_book, and the value of that variable is whatever the user inputs.

Your next lines of code, though, are:

```<code>while input != "Undoctored":
      if input == "None":
...
</code>```

Specifically, while input != "Undoctored": isn't checking for what the variable current_book is, it's checking for what the variable input is. Since input is a standard function, it is certainly not equal to "None". :)

Title: While conditional loop in Python

Body:
I am writing a simple book recommender function in Python that takes in an answer and recommends a book called "Undoctored". In the code below, when the input is equal to "None", the loop still gives me the last answer of "Interesting read." What is wrong with my while loop?

def recommend_book():
    current_book = input("What book are you reading currently? ")
    while input != "Undoctored":
      if input == "None":
        return("Go pick up a book!")
      else:
        return(f'"{current_book}" is an interesting read. I also recommend "Undoctored" by Dr. William Davis.')

I also tried adding "break" after the first if statement and that still didn't work.

Body:
Keep track of the variables you're using!

current_book = input("What book are you reading currently?")

This line of code sets a variable named current_book, and the value of that variable is whatever the user inputs.

Your next lines of code, though, are:

while input != "Undoctored":
      if input == "None":
...

Specifically, while input != "Undoctored": isn't checking for what the variable current_book is, it's checking for what the variable input is. Since input is a standard function, it is certainly not equal to "None". :)


问:
Ag-Grid require delete button for each row
I am trying to implement a solution with ag-grid and not got stuck into a problem. I am trying to implement edit and delete button in each row .edit button implementation is successful but problem is with delete button. I have tried best of my knowledge (which is little for angular 2) .Please see the implementation as per below code:-

court.component.ts

```<code>import { Component } from '@angular/core';
import { Court } from './court.model';
//import './../utils/array.extensions';

import { GridOptions } from "ag-grid";
import { DataCourtService } from '../services/data-court.service';
import { EditButtonComponent } from "../utils/editbutton.component";

 @Component({
     selector: 'court',
    template: require('./court.component.html'),
    providers: [DataCourtService]
})

export class CourtComponent {
   private gridOptions: GridOptions;
   public courts : Court[];
   onQuickFilterChanged(event: any) {
    this.gridOptions.api.setQuickFilter(event.target.value);
   }
    constructor() {
        var courtservice = new DataCourtService();
        this.gridOptions = {
            rowSelection: 'single'
        };

      //   this.gridOptions.angularCompileRows = true;
        this.gridOptions.columnDefs = [

            {
                headerName: "Court Name",
                field: "courtname",
                editable: true
            } ,
            {
                headerName: "Action",
                cellRendererFramework: EditButtonComponent,
                colId: "edit"
            }

        ];

        this.gridOptions.rowData = courtservice.getCourt();

    }
}
</code>```

EditButton.component.ts

```<code>import {Component} from "@angular/core";
import {ICellRendererAngularComp} from "ag-grid-angular/main";

@Component({
    selector: 'edit-button',
    template: `<button (click)="invokeEditMethod()" class="btn btn-primary btn-xs"><span class="glyphicon glyphicon-edit"></span>Edit</button>
               <button (click)="invokeDeleteMethod()" class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-remove"></span>Delete</button>`
})
export class EditButtonComponent implements ICellRendererAngularComp {
    public params: any;

    agInit(params: any): void {
        this.params = params;
    }
public invokeDeleteMethod() {
       var selectedData = this.params.api.getSelectedRows();
       this.params.api.updateRowsData({remove: selectedData});
     alert("hi");

}
    public invokeEditMethod() {

         this.params.api.setFocusedCell(this.params.node.rowIndex, 'courtname');
         this.params.api.startEditingCell({
         rowIndex: this.params.node.rowIndex,
        colKey: 'courtname',
        }
     );
    }

}
</code>```

In this function

```<code>public invokeDeleteMethod() {
           var selectedData = this.params.api.getSelectedRows();
           this.params.api.updateRowsData({remove: selectedData});
         alert("hi");

    }
</code>```

I am recieving an error as UpdateRowData is not an function. Can you please help me to achieve this??

答:
The real problem with that code is that

```<code>this.params.api.updateRowsData({remove: selectedData});
</code>```

Expects an array in version 22.X.X

```<code>this.params.api.updateRowsData({remove: [selectedData]});
</code>```

Body:
I am trying to implement a solution with ag-grid and not got stuck into a problem. I am trying to implement edit and delete button in each row .edit button implementation is successful but problem is with delete button. I have tried best of my knowledge (which is little for angular 2) .Please see the implementation as per below code:-

court.component.ts

import { Component } from '@angular/core';
import { Court } from './court.model';
//import './../utils/array.extensions';

import { GridOptions } from "ag-grid";
import { DataCourtService } from '../services/data-court.service';
import { EditButtonComponent } from "../utils/editbutton.component";

 @Component({
     selector: 'court',
    template: require('./court.component.html'),
    providers: [DataCourtService]
})

export class CourtComponent {
   private gridOptions: GridOptions;
   public courts : Court[];
   onQuickFilterChanged(event: any) {
    this.gridOptions.api.setQuickFilter(event.target.value);
   }
    constructor() {
        var courtservice = new DataCourtService();
        this.gridOptions = {
            rowSelection: 'single'
        };

      //   this.gridOptions.angularCompileRows = true;
        this.gridOptions.columnDefs = [

            {
                headerName: "Court Name",
                field: "courtname",
                editable: true
            } ,
            {
                headerName: "Action",
                cellRendererFramework: EditButtonComponent,
                colId: "edit"
            }

        ];

        this.gridOptions.rowData = courtservice.getCourt();

    }
}

EditButton.component.ts

import {Component} from "@angular/core";
import {ICellRendererAngularComp} from "ag-grid-angular/main";

@Component({
    selector: 'edit-button',
    template: `<button (click)="invokeEditMethod()" class="btn btn-primary btn-xs">Edit</button>
               <button (click)="invokeDeleteMethod()" class="btn btn-danger btn-xs">Delete</button>`
})
export class EditButtonComponent implements ICellRendererAngularComp {
    public params: any;

    agInit(params: any): void {
        this.params = params;
    }
public invokeDeleteMethod() {
       var selectedData = this.params.api.getSelectedRows();
       this.params.api.updateRowsData({remove: selectedData});
     alert("hi");

}
    public invokeEditMethod() {

         this.params.api.setFocusedCell(this.params.node.rowIndex, 'courtname');
         this.params.api.startEditingCell({
         rowIndex: this.params.node.rowIndex,
        colKey: 'courtname',
        }
     );
    }

}

In this function

public invokeDeleteMethod() {
           var selectedData = this.params.api.getSelectedRows();
           this.params.api.updateRowsData({remove: selectedData});
         alert("hi");

    }

I am recieving an error as UpdateRowData is not an function. Can you please help me to achieve this??

Body:
The real problem with that code is that

this.params.api.updateRowsData({remove: selectedData});

Expects an array in version 22.X.X

this.params.api.updateRowsData({remove: [selectedData]});


问:
Open CV trivial circle detection -- how to get least squares instead of a contour?
My goal is to accurately measure the diameter of a hole from a microscope. Workflow is: take an image, process for fitting, fit, convert radius in pixels to mm, write to a csv

This is an output of my image processing script used to measure the diameter of a hole. I'm having an issue where it seems like my circle fitting is prioritizing matching the contour rather than something like a least squares approach.

I've alternatively averaged many fits in something like this:

My issue here is I like to quickly scan to make sure the circle fit is appropriate. The trade off is the more fits I have, the more realistic the fit, the fewer I have the easier is to make sure the number is correct. My circles aren't always as pretty and circular as this one so it's important to me.

Here's the piece of my script fitting circles if you could take a look and tell me how to do more of a least squares approach on the order of 5 circles. I don't want to use minimum circle detection because a fluid is flowing through this hole so I'd like it to be more like a hydraulic diameter-- thanks!

```<code>(thresh, blackAndWhiteImage0) = cv2.threshold(img0, 100, 255, cv2.THRESH_BINARY) #make black + white
median0 = cv2.medianBlur(blackAndWhiteImage0, 151) #get rid of noise
circles0 = cv2.HoughCircles(median0,cv2.HOUGH_GRADIENT,1,minDist=5,param1= 25, param2=10, minRadius=min_radius_small,maxRadius=max_radius_small) #fit circles to image
</code>```

答:
Here is another way to fit a circle by getting the equivalent circle center and radius from the binary image using connected components and drawing a circle from that using Python/OpenCV/Skimage.

Input:

```<code>import cv2
import numpy as np
from skimage import measure

# load image and set the bounds
img = cv2.imread("dark_circle.png")

# convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# blur
blur = cv2.GaussianBlur(gray, (3,3), 0)

# threshold
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# apply morphology open with a circular shaped kernel
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))
binary = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2)

# find contour and draw on input (for comparison with circle)
cnts = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
c = cnts[0]
result = img.copy()
cv2.drawContours(result, [c], -1, (0, 255, 0), 1)

# find radius and center of equivalent circle from binary image and draw circle
# see https://scikit-image.org/docs/dev/api/skimage.measure.html#skimage.measure.regionprops
# Note: this should be the same as getting the centroid and area=cv2.CC_STAT_AREA from cv2.connectedComponentsWithStats and computing radius = 0.5*sqrt(4*area/pi) or approximately from the area of the contour and computed centroid via image moments.
regions = measure.regionprops(binary)
circle = regions[0]
yc, xc = circle.centroid
radius = circle.equivalent_diameter / 2.0
print("radius =",radius, "  center =",xc,",",yc)
xx = int(round(xc))
yy = int(round(yc))
rr = int(round(radius))
cv2.circle(result, (xx,yy), rr, (0, 0, 255), 1)

# write result to disk
cv2.imwrite("dark_circle_fit.png", result)

# display it
cv2.imshow("image", img)
cv2.imshow("thresh", thresh)
cv2.imshow("binary", binary)
cv2.imshow("result", result)
cv2.waitKey(0)
</code>```

Result showing contour (green) compared to circle fit (red):

Circle Radius and Center:

```<code>radius = 117.6142467296168   center = 220.2169911178609 , 150.26823599797507
</code>```

A least squares fit method (between the contour points and a circle) can be obtained using Scipy. For example, see:

https://gist.github.com/lorenzoriano/6799568

https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html

Body:
My goal is to accurately measure the diameter of a hole from a microscope. Workflow is: take an image, process for fitting, fit, convert radius in pixels to mm, write to a csv

This is an output of my image processing script used to measure the diameter of a hole. I'm having an issue where it seems like my circle fitting is prioritizing matching the contour rather than something like a least squares approach.

I've alternatively averaged many fits in something like this:

My issue here is I like to quickly scan to make sure the circle fit is appropriate. The trade off is the more fits I have, the more realistic the fit, the fewer I have the easier is to make sure the number is correct. My circles aren't always as pretty and circular as this one so it's important to me.

Here's the piece of my script fitting circles if you could take a look and tell me how to do more of a least squares approach on the order of 5 circles. I don't want to use minimum circle detection because a fluid is flowing through this hole so I'd like it to be more like a hydraulic diameter-- thanks!

(thresh, blackAndWhiteImage0) = cv2.threshold(img0, 100, 255, cv2.THRESH_BINARY) #make black + white
median0 = cv2.medianBlur(blackAndWhiteImage0, 151) #get rid of noise
circles0 = cv2.HoughCircles(median0,cv2.HOUGH_GRADIENT,1,minDist=5,param1= 25, param2=10, minRadius=min_radius_small,maxRadius=max_radius_small) #fit circles to image

Body:
Here is another way to fit a circle by getting the equivalent circle center and radius from the binary image using connected components and drawing a circle from that using Python/OpenCV/Skimage.

Input:

import cv2
import numpy as np
from skimage import measure

# load image and set the bounds
img = cv2.imread("dark_circle.png")

# convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# blur
blur = cv2.GaussianBlur(gray, (3,3), 0)

# threshold
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# apply morphology open with a circular shaped kernel
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))
binary = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2)

# find contour and draw on input (for comparison with circle)
cnts = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
c = cnts[0]
result = img.copy()
cv2.drawContours(result, [c], -1, (0, 255, 0), 1)

# find radius and center of equivalent circle from binary image and draw circle
# see https://scikit-image.org/docs/dev/api/skimage.measure.html#skimage.measure.regionprops
# Note: this should be the same as getting the centroid and area=cv2.CC_STAT_AREA from cv2.connectedComponentsWithStats and computing radius = 0.5*sqrt(4*area/pi) or approximately from the area of the contour and computed centroid via image moments.
regions = measure.regionprops(binary)
circle = regions[0]
yc, xc = circle.centroid
radius = circle.equivalent_diameter / 2.0
print("radius =",radius, "  center =",xc,",",yc)
xx = int(round(xc))
yy = int(round(yc))
rr = int(round(radius))
cv2.circle(result, (xx,yy), rr, (0, 0, 255), 1)

# write result to disk
cv2.imwrite("dark_circle_fit.png", result)

# display it
cv2.imshow("image", img)
cv2.imshow("thresh", thresh)
cv2.imshow("binary", binary)
cv2.imshow("result", result)
cv2.waitKey(0)

Result showing contour (green) compared to circle fit (red):

Circle Radius and Center:

radius = 117.6142467296168   center = 220.2169911178609 , 150.26823599797507

A least squares fit method (between the contour points and a circle) can be obtained using Scipy. For example, see:

https://gist.github.com/lorenzoriano/6799568

https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html


问:
oci_connect on PHP 5.2.0-8 not working with Oracle 11g
I was using PHP 5.2.0-8+etch16 / oci_connect to connect to my company's Oracle DB and show information on our website (accessible to external IPs). Ever since we upgraded our DB version (to 11g Release 11.2.0.4.0), I cannot connect to the database anymore.

The page stays loading (oci_set_call_timeout doesn't work), and nothing is shown. I know the code works and the credentials are OK because I use the same code in another page (visible only to internal IPs) and I didn't have any problems after the upgrade. I'm using the following code:

```<code>$conn = oci_connect('user', 'password', 'server', 'charset');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
    echo "Error";
}
else{
    echo "OK";
}
</code>```

Running phpinfo, the oci section returns:

```<code>oci8
OCI8 Support    enabled
Version     1.4.5
Revision    $Revision: 305257 $
Active Persistent Connections   0
Active Connections  0
Oracle Instant Client Version   11.1
Temporary Lob support   enabled
Collections support     enabled

Directive   Local Value Master Value
oci8.connection_class   no value    no value
oci8.default_prefetch   100 100
oci8.events Off Off
oci8.max_persistent -1  -1
oci8.old_oci_close_semantics    Off Off
oci8.persistent_timeout -1  -1
oci8.ping_interval  60  60
oci8.privileged_connect Off Off
oci8.statement_cache_size   20  20
</code>```

In the page accessible only to internal IPs, the version of oci is 1.4.9 and it is running on a Windows Server 2003 (I know it's old). The external page (the one that doesn't work) has an oci version of 1.4.5 and runs in a Linux jedi-ng 2.6.25. I don't have access to the linux server (only to the folder where the php/html is stored), but I can run some things using shell_exec().

Is it a version problem (I cannot connect to Oracle 11g using an old version of php/oci anymore) or this is just a connection problem that I can solve by trying another approach?

Feel free to ask questions if you need to.

Thanks in advance.

答:
Add this to the top of your test script and see if you get a better error message:

```<code>error_reporting(E_ALL|E_STRICT);
ini_set('display_errors', 'On');
</code>```

The key thing is the version of the Oracle libraries used by PHP OCI8, not the version of the database that you are connecting to.  There is a bit of overlap in some environments because the libraries could be used from the database software installation.  If you have a remote database then PHP OCI8 may (should) use the libraries from Oracle Instant Client (that link is for the 64-bit packages - use the 32-bit Instant Client if you are running 32-bit PHP).

Unless you have OCI8 PHP 2.2.2 and are using Oracle client libraries 18c or later, then oci_set_call_timeout() won't be available.

If I read your question correctly, you have a problem on Linux?  In that case make sure that LD_LIBRARY_PATH is set correctly for your version of the webserver, e.g you might need to set it in /etc/sysconfig/httpd (I don't know your Linux flavor, so this may differ).  Often it is much easier to use ldconfig as shown in the Instant Client installation instructions

Body:
I was using PHP 5.2.0-8+etch16 / oci_connect to connect to my company's Oracle DB and show information on our website (accessible to external IPs). Ever since we upgraded our DB version (to 11g Release 11.2.0.4.0), I cannot connect to the database anymore.

The page stays loading (oci_set_call_timeout doesn't work), and nothing is shown. I know the code works and the credentials are OK because I use the same code in another page (visible only to internal IPs) and I didn't have any problems after the upgrade. I'm using the following code:

$conn = oci_connect('user', 'password', 'server', 'charset');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
    echo "Error";
}
else{
    echo "OK";
}

Running phpinfo, the oci section returns:

oci8
OCI8 Support    enabled
Version     1.4.5
Revision    $Revision: 305257 $
Active Persistent Connections   0
Active Connections  0
Oracle Instant Client Version   11.1
Temporary Lob support   enabled
Collections support     enabled

Directive   Local Value Master Value
oci8.connection_class   no value    no value
oci8.default_prefetch   100 100
oci8.events Off Off
oci8.max_persistent -1  -1
oci8.old_oci_close_semantics    Off Off
oci8.persistent_timeout -1  -1
oci8.ping_interval  60  60
oci8.privileged_connect Off Off
oci8.statement_cache_size   20  20

In the page accessible only to internal IPs, the version of oci is 1.4.9 and it is running on a Windows Server 2003 (I know it's old). The external page (the one that doesn't work) has an oci version of 1.4.5 and runs in a Linux jedi-ng 2.6.25. I don't have access to the linux server (only to the folder where the php/html is stored), but I can run some things using shell_exec().

Is it a version problem (I cannot connect to Oracle 11g using an old version of php/oci anymore) or this is just a connection problem that I can solve by trying another approach?

Feel free to ask questions if you need to.

Thanks in advance.

Body:
Add this to the top of your test script and see if you get a better error message:

error_reporting(E_ALL|E_STRICT);
ini_set('display_errors', 'On');

The key thing is the version of the Oracle libraries used by PHP OCI8, not the version of the database that you are connecting to.  There is a bit of overlap in some environments because the libraries could be used from the database software installation.  If you have a remote database then PHP OCI8 may (should) use the libraries from Oracle Instant Client (that link is for the 64-bit packages - use the 32-bit Instant Client if you are running 32-bit PHP).

Unless you have OCI8 PHP 2.2.2 and are using Oracle client libraries 18c or later, then oci_set_call_timeout() won't be available.

If I read your question correctly, you have a problem on Linux?  In that case make sure that LD_LIBRARY_PATH is set correctly for your version of the webserver, e.g you might need to set it in /etc/sysconfig/httpd (I don't know your Linux flavor, so this may differ).  Often it is much easier to use ldconfig as shown in the Instant Client installation instructions


问:
How can I search a python script for use of a class method before running?
I would like to be able to scan a python script for uses of a class method before running the script itself. For example, given the following script, get all uses of the "foo" method for class "A" and the arguments passed to the method

```<code>class A():
    def foo(self, val):
        return val + 1

class B():
    def foo(self, val):
        return val - 1

a = A()
b = B()

a_val = a.foo(1)
b_val = b.foo(1)
</code>```

This is an overly simple example, but the goal here is to use something more than regex to search for a foo() pattern so that items like b.foo(1) are not returned. I've looked at the ast and symtable modules, but they don't seem to have the functionality I'm after. I realize this may be a difficult/impossible problem due to python being an interpreted language, but it seems like someone else had to have had this problem before

答:
This cannot be done with static code analysis because owner of the method is determined in runtime. For example I could add on to your example:

```<code>b = a
b.foo(0)
</code>```

Here b.foo(0) is in fact an invocation of the class A's foo method. And static code analysis can't know this, because this depends on runtime.

Which means that what you're asking for reduces to the halting problem. There is no way to do what you're asking for with a guaranteed (or even probabilistically more accurate than chance) correct answer.

Body:
I would like to be able to scan a python script for uses of a class method before running the script itself. For example, given the following script, get all uses of the "foo" method for class "A" and the arguments passed to the method

class A():
    def foo(self, val):
        return val + 1

class B():
    def foo(self, val):
        return val - 1

a = A()
b = B()

a_val = a.foo(1)
b_val = b.foo(1)

This is an overly simple example, but the goal here is to use something more than regex to search for a foo() pattern so that items like b.foo(1) are not returned. I've looked at the ast and symtable modules, but they don't seem to have the functionality I'm after. I realize this may be a difficult/impossible problem due to python being an interpreted language, but it seems like someone else had to have had this problem before

Body:
This cannot be done with static code analysis because owner of the method is determined in runtime. For example I could add on to your example:

b = a
b.foo(0)

Here b.foo(0) is in fact an invocation of the class A's foo method. And static code analysis can't know this, because this depends on runtime.

Which means that what you're asking for reduces to the halting problem. There is no way to do what you're asking for with a guaranteed (or even probabilistically more accurate than chance) correct answer.


问:
I can't put double to Parameters.AddWithValue
I'm trying add decimal to numbers. Example: 1.45, 46.12 but I got an exception.

```<code>cn.Open();
string sqlquery = ("INSERT INTO table(ID, Name, Price, HowMuch, Localization, Description) VALUES(@ID, @Name, @Price, @HowMuch, @Localization, @Description)");
SqlCeCommand cm = new SqlCeCommand(sqlquery, cn);
cm.Parameters.AddWithValue("@ID", textBox1.Text);
cm.Parameters.AddWithValue("@Name", textBox2.Text);
cm.Parameters.AddWithValue("@Price", textBox3.Text);
cm.Parameters.AddWithValue("@HowMuch", textBox4.Text);
cm.Parameters.AddWithValue("@Localization", textBox5.Text);
cm.Parameters.AddWithValue("@Description", textBox6.Text);
</code>```

Exception Message: "Invalid format of the input string.".
I'm using the System.Data.SqlServerCe

答:
I think its a good idea to make sure that textBox3.Text is a valid decimal first...before you get to the insert routine.

```<code>decimal price = Convert.ToDecimal(textBox3.Text);
</code>```

Then you can add the parameter and value with:

```<code>using System.Data;
cm.Parameters.Add("@Price", SqlDbType.Decimal).Value = price;
</code>```

SqlDbType is part of System.Data.

Body:
I'm trying add decimal to numbers. Example: 1.45, 46.12 but I got an exception.

cn.Open();
string sqlquery = ("INSERT INTO table(ID, Name, Price, HowMuch, Localization, Description) VALUES(@ID, @Name, @Price, @HowMuch, @Localization, @Description)");
SqlCeCommand cm = new SqlCeCommand(sqlquery, cn);
cm.Parameters.AddWithValue("@ID", textBox1.Text);
cm.Parameters.AddWithValue("@Name", textBox2.Text);
cm.Parameters.AddWithValue("@Price", textBox3.Text);
cm.Parameters.AddWithValue("@HowMuch", textBox4.Text);
cm.Parameters.AddWithValue("@Localization", textBox5.Text);
cm.Parameters.AddWithValue("@Description", textBox6.Text);

Exception Message: "Invalid format of the input string.".
I'm using the System.Data.SqlServerCe

Body:
I think its a good idea to make sure that textBox3.Text is a valid decimal first...before you get to the insert routine.

decimal price = Convert.ToDecimal(textBox3.Text);

Then you can add the parameter and value with:

using System.Data;
cm.Parameters.Add("@Price", SqlDbType.Decimal).Value = price;

SqlDbType is part of System.Data.


问:
Return a map with file sizes using a lambda expression and a regular expression java
How to return a map with the size of files in the specified directory whose names match the specified mask. A DOS mask can contain special characters ' * ' and '?'.

My code:

```<code>public Map<Path, Long> fileSizes(Path dir, String mask, boolean recursive) throws IOException {
    return Files.walk(dir)
            .filter(Files::isRegularFile)
            .filter( x -> x.toFile().getName().equals(mask))
            How to make a filter by mask and regular expression correctly? Where to insert "regex"?
            .collect(Collectors.toMap(Path::getFileName, (x) -> x.toFile().length()));
}
}
</code>```

And if you know, tell me the correct regular expression. I made this expression: "(?:(?:*)?(?:\w+))|(?:(?:\?)(?:\w))"

答:
With this implementation, there may be problems?</p>

```<code>public Map<Path, Long> fileSizes(Path dir, String mask, boolean recursive) throws IOException {
    final PathMatcher pathMatcher = dir.getFileSystem().getPathMatcher("glob:**/*" + mask + "*");

    try (final Stream<Path> stream = Files.walk(dir, recursive ? Integer.MAX_VALUE : 1)) {
        return stream.filter(pathMatcher::matches)
                .collect(Collectors.toMap(Path::getFileName, (x) -> x.toFile().length()));
    }
}
</code>```

Body:
How to return a map with the size of files in the specified directory whose names match the specified mask. A DOS mask can contain special characters ' * ' and '?'.

My code:

public Map<Path, Long> fileSizes(Path dir, String mask, boolean recursive) throws IOException {
    return Files.walk(dir)
            .filter(Files::isRegularFile)
            .filter( x -> x.toFile().getName().equals(mask))
            How to make a filter by mask and regular expression correctly? Where to insert "regex"?
            .collect(Collectors.toMap(Path::getFileName, (x) -> x.toFile().length()));
}
}

And if you know, tell me the correct regular expression. I made this expression: "(?:(?:*)?(?:\w+))|(?:(?:\?)(?:\w))"

Body:
With this implementation, there may be problems?

public Map<Path, Long> fileSizes(Path dir, String mask, boolean recursive) throws IOException {
    final PathMatcher pathMatcher = dir.getFileSystem().getPathMatcher("glob:**/*" + mask + "*");

    try (final Stream<Path> stream = Files.walk(dir, recursive ? Integer.MAX_VALUE : 1)) {
        return stream.filter(pathMatcher::matches)
                .collect(Collectors.toMap(Path::getFileName, (x) -> x.toFile().length()));
    }
}


问:
Hyperion Essbase Script Means
I have script essbase calc from hyperion
like this

"ACTUAL" = ("ACTUAL" +
  ("ACTUAL"->"Labor_Hours"->"NA_CE"->"NA_CC"->"NA_ENTITY" *
  "ACTUAL"->"NA_PRODUCT"));

i have no idea what that code means,

because my cube result alwasy zero 0

答:
To answer that, you have to identify the values for each of the following:

"ACTUAL"->"Labor_Hours"->"NA_CE"->"NA_CC"->"NA_ENTITY"for each product

Multiplying for "ACTUAL"->"NA_PRODUCT" where we can assume in the FIX section you have the members CE_1, CC_1, ENTITY_1 then look for the following
"ACTUAL"->"NA_PRODUCT"->CE_1->CC_1->ENTITY_1

The product of 1*2 will be added to "Actual" where we can assume
"ACTUAL"->CE_1->CC_1->ENTITY_1 for each product

In this case, for sure, what can make you get a ZERO is that for 1 or 2 there's a ZERO or #Missing in you data.

Title: Hyperion Essbase Script Means


问:
Concatenation of 2 values from same column using oracle SQL
I'm trying to concatenate the values of a column.

For EX:

```<code>select case when month=1 then month_name1
when month =12 then month_name2 END
from Calendar
where month in (1,12)
</code>```

results:

```<code>Jan
Dec
</code>```

Target results:

```<code>Jan - Dec
</code>```

tried different ways but couldn't get it. looks very simple but hard luck.
Thanks in advance.

答:
I feel you would need a hack here, below query must do the magic !!

select c1.month_name1 || ' - ' || c2.month_name2
from Calendar c1, calendar c2
where c1.month = 1 and c2.month = 12 ;

Body:
I'm trying to concatenate the values of a column.

For EX:

select case when month=1 then month_name1
when month =12 then month_name2 END
from Calendar
where month in (1,12)

results:

Jan
Dec

Target results:

Jan - Dec

tried different ways but couldn't get it. looks very simple but hard luck.
Thanks in advance.


问:
Combining Hex string
I am working on a C program where I have been given 91 bits of an AES Key and need to iterate through the other possible 37 to get a full key. In hex, the key looks like this where the F's is the unknown part of the key.

FF FF FF FF FC 00 00 00 00 00 00 00 00 00 00 03

When iterating through the unknown portion, I will obviously need to combine the unknown portion to the known portion. Being I have an odd number of 9 bytes that need to be found, how will I combine that last byte to the "C" to ensure I get the correct length key?

答:
There are a number of ways that you could do it, but I would do it this way:

Initialize four 128-bit values, min, max, inc, and base. Set min to zero. Set max to FF FF FF FF F0 00 00 00 00 00 00 00 00 00 00 00. Set base to the given key with zeroes in all the spots that are unknown. Set inc to 00 00 00 00 10 00 00 00 00 00 00 00 00 00 00 00.

Loop from min to max adding inc each time. For each entry, OR the current loop index with base. That's the value you test.

Title: Combining Hex string


问:
How to parse moment into specific timezone from moment.unix()
I have an initial value for a timestamp (created in User-1's timezone) I'm retrieving from firebase's firestore. the format this is in, is seconds in UTC from the Unix Epoch.

My goal is to take the initial timestamp value, and convert it to the timezone of the current user. if I use

moment.unix(initial_In_Seconds).format("H:mma") I get the correct initial time. Using .unix() is the only way I've been able to get the correct initial time. Now I need to convert it to a specific timezone. lets say "America/Denver" (the initial timezone is GMT -05:00)

I haven't been successful using moment.tz() in any of my amalgamations thus far.

I've tried:

```<code>moment.tz(moment.unix(initial_In_Seconds).format("H:mma"), "America/Denver")

let unix = moment.unix(initial_In_Seconds).format("H:mma");
let parsed = moment.tz(unix, "America/Denver");
</code>```

How can this be parsed? Moment.js confuses me

答:
further playing has yielded better results:

```<code>moment
 .tz(moment.unix(props.navigation.state.params.time.start.seconds),'America/Denver')
 .format('H:mma')
</code>```

unfortunately for hours that are PM, it gives military time...and im interested in 12hr format...

EDIT: changes -> .format('h:mma') yields 12hr format

Body:
I have an initial value for a timestamp (created in User-1's timezone) I'm retrieving from firebase's firestore. the format this is in, is seconds in UTC from the Unix Epoch.

My goal is to take the initial timestamp value, and convert it to the timezone of the current user. if I use

moment.unix(initial_In_Seconds).format("H:mma") I get the correct initial time. Using .unix() is the only way I've been able to get the correct initial time. Now I need to convert it to a specific timezone. lets say "America/Denver" (the initial timezone is GMT -05:00)

I haven't been successful using moment.tz() in any of my amalgamations thus far.

I've tried:

moment.tz(moment.unix(initial_In_Seconds).format("H:mma"), "America/Denver")

let unix = moment.unix(initial_In_Seconds).format("H:mma");
let parsed = moment.tz(unix, "America/Denver");

How can this be parsed? Moment.js confuses me

Body:
further playing has yielded better results:

moment
 .tz(moment.unix(props.navigation.state.params.time.start.seconds),'America/Denver')
 .format('H:mma')

unfortunately for hours that are PM, it gives military time...and im interested in 12hr format...

EDIT: changes -> .format('h:mma') yields 12hr format


问:
API calls fail with Rate limit exceeded in OneLogin
I am trying to make a API call to Onelogin (which is a third-party identity platform), it fails with "Rate limit exceeded", after 5000 request. How can I increase the request or reset the counter?</p>

答:
Free/Developer accounts are limited to 5000 API calls per hour.

If you're a paying customer, you can contact OneLogin support to get your rate limit increased.