问:
How to test if a valid Method exists when params are involved
I have the following method:

```<code>    public MethodInfo FancyGetMethodInfo
         (object obj, string methodName, Type[] methodSignature)
    {
        return obj.GetType().GetMethod(methodName, methodSignature);
    }
</code>```

and for the sake of an example I have in my object I am passing the two methods

```<code>    public int Subtract(int a, int b) { return a - b; }

    public int Add(params int[] a) { return a.Sum(); }
</code>```

And when I execute the following lines I get these results:

```<code>        var SubMethod = FancyGetMethodInfo(obj, "Subtract",
                         new Type[] { typeof(int), typeof(int) });
        //I get a MethodInfo
        var AddMethod = FancyGetMethodInfo(obj, "Add",
                         new Type[] { typeof(int), typeof(int) });
        //I get a Null reference
</code>```

I'm sure this is because of the params in Add. Is there a clean way to get reference to my MethodInfo for my Add method given an arbitrary sized Type[] containing ints and only having access to the provided variables in my FancyGetMethodInfo method?

Edit:
More eloquently put by Jon Skeet, I want to perform the same binding as the C# compiler does in my method. it needs to work properly with subclasses, implicit casting, arbitrary length params, etc...

Also as requested, a relevant link here is: Determining if a parameter uses "params" using reflection in C#? which will get me as far as knowing that the method has a params.

答:
Did you give this one a try:

From the MSDN: Type.GetMethod

```<code>public void MethodA(int[] i) { }

// Get MethodA(int[] i)
mInfo = typeof(Program).GetMethod("MethodA",
    BindingFlags.Public | BindingFlags.Instance,
    null,
    new Type[] { typeof(int[]) },
    null);
Console.WriteLine("Found method: {0}", mInfo);
</code>```

How to check for the "params" keyword: this has been answered here

Body:
I have the following method:

    public MethodInfo FancyGetMethodInfo
         (object obj, string methodName, Type[] methodSignature)
    {
        return obj.GetType().GetMethod(methodName, methodSignature);
    }

and for the sake of an example I have in my object I am passing the two methods

    public int Subtract(int a, int b) { return a - b; }

    public int Add(params int[] a) { return a.Sum(); }

And when I execute the following lines I get these results:

        var SubMethod = FancyGetMethodInfo(obj, "Subtract",
                         new Type[] { typeof(int), typeof(int) });
        //I get a MethodInfo
        var AddMethod = FancyGetMethodInfo(obj, "Add",
                         new Type[] { typeof(int), typeof(int) });
        //I get a Null reference

I'm sure this is because of the params in Add. Is there a clean way to get reference to my MethodInfo for my Add method given an arbitrary sized Type[] containing ints and only having access to the provided variables in my FancyGetMethodInfo method?

Edit:
More eloquently put by Jon Skeet, I want to perform the same binding as the C# compiler does in my method. it needs to work properly with subclasses, implicit casting, arbitrary length params, etc...

Also as requested, a relevant link here is: Determining if a parameter uses "params" using reflection in C#? which will get me as far as knowing that the method has a params.

Body:
Did you give this one a try:

From the MSDN: Type.GetMethod

public void MethodA(int[] i) { }

// Get MethodA(int[] i)
mInfo = typeof(Program).GetMethod("MethodA",
    BindingFlags.Public | BindingFlags.Instance,
    null,
    new Type[] { typeof(int[]) },
    null);
Console.WriteLine("Found method: {0}", mInfo);

How to check for the "params" keyword: this has been answered here


来源: stackexchange

问:
Powershell: Unable to parse json returned from Invoke-RestMethod
I try to parse a json string returned from an API call.

```<code>$Response = Invoke-RestMethod -Uri $URIValue -Method Post -Headers $Headers -Body $requestBody -ContentType 'application/json; charset=utf-8'

$Response #Returns: {"results":[{"tables":[{"rows":[{"[Quantity]":200}]}]}]}
</code>```

Now that I try to parse it Response | ConvertFrom-Json I get the following error: ConvertFrom-Json: Conversion from JSON failed with error: Unexpected character encountered while parsing value: . Path '', line 0, position 0.

What am I doing wrong?

答:
The actual solution:

$Response.Substring(1) | ConvertFrom-Json

ContentLicense: CC BY-SA 4.0

Body:
I try to parse a json string returned from an API call.

$Response = Invoke-RestMethod -Uri $URIValue -Method Post -Headers $Headers -Body $requestBody -ContentType 'application/json; charset=utf-8'

$Response #Returns: {"results":[{"tables":[{"rows":[{"[Quantity]":200}]}]}]}

Now that I try to parse it Response | ConvertFrom-Json I get the following error: ConvertFrom-Json: Conversion from JSON failed with error: Unexpected character encountered while parsing value: . Path '', line 0, position 0.

What am I doing wrong?


问:
React/node => image display not allowed to load local ressource
I'm on a react/node website project. Pretty simple website with a crud.
My crud worked but my pictures doesn't appears (they are upload on a folder public/uploads/news/ and their path is save in mongoDb) For my news I can see the title, message, date but the picture is broken and I've only the alt.
When I go to the console and go on the element, the patch is OK "c:/users/......... /public/uploads/news/nameofmypicture.jpg".
I just got an error message "not allowed to load local resources"

import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { dateParser, isEmpty } from "../../../general/utils/Utils";
import { updateNews } from "../../../../store/actions/news.actions";
import DeleteCard from "./DeleteCard";
import Loader from "../../../general/utils/Loading";

const Card = ({ news }) => {
    const [isLoading, setIsLoading] = useState(true);
    const [isUpdated, setIsUpdated] = useState(false);
    const [textUpdate, setTextUpdate] = useState(null);
    const newsData = useSelector((state) => state.newsReducer);
    const dispatch = useDispatch();

    const updateItem = () => {
        if (textUpdate) {
            dispatch(updateNews(news._id, textUpdate));
        }
        setIsUpdated(false);
    };

    useEffect(() => {
        !isEmpty(newsData[0]) && setIsLoading(false);
    }, [newsData]);

    return (

            {isLoading ? (
                <Loader />
            ) : (
                <>

                        {isUpdated === false &&
{news.title}
}
                        {isUpdated && (

                                <textarea
                                    defaultValue={news.title}
                                    onChange={(e) => setTextUpdate(e.target.value)}
                                />

                        )}
                            {dateParser(news.createdAt)}

                        {isUpdated === false &&
{news.message}
}
                        {isUpdated && (

                                <textarea
                                    defaultValue={news.message}
                                    onChange={(e) => setTextUpdate(e.target.value)}
                                />

                                    <button className="btn btn-success" onClick={updateItem}>
                                        Valider modification
                                    </button>

                        )}
                        {news.picture && (

                        )}
                        {news.video && (

                        )}

                            <button className="btn btn-primary" onClick={() => setIsUpdated(!isUpdated)}>Edit</button>
                            <DeleteCard id={news._id} />

                </>
            )}

    );
};

export default Card;```

If someone wants the full code
https://github.com/macath/AJC-modelism
If you have more questions, ask me. I'm on this problem since 4 days, I really don't understand why it's don't work.
I specify that this project will be put online so I need a valid solution on a server and not only local

Ps : sorry for my English I'm French

答:
Thanks @Rolland Costomarob & @Siddharth Seth
I think the problem is that, i use multer to upload my pictures and i think i don't use it correctly.

const router = require('express').Router();
const newsController = require('../controllers/news.controller');

const multer = require('multer');
const imageStorage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, './client/public/uploads/')
    },
    filename: (req, file, cb) => {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
        cb(null, 'file-' + uniqueSuffix + '.jpg')
    }
});
const upload = multer({
    limits: {
        fileSize: 10000000
    },
    fileFilter: (req, file, cb) => {
        if (file.mimetype === 'image/png' || file.mimetype === 'image/jpg' || file.mimetype === 'image/jpeg') {
          cb(null, true);
        }
        else {
          cb(new multer.MulterError('mauvais format de document'));
        }
      },
    storage: imageStorage
});

router.get('/', newsController.readNews);
router.post('/', upload.single('file'), newsController.createNews);
router.put('/:id', newsController.updateNews);
router.delete('/:id', newsController.deleteNews);

module.exports = router;```

If you have the solution, you just save my life

Body:
I'm on a react/node website project. Pretty simple website with a crud.
My crud worked but my pictures doesn't appears (they are upload on a folder public/uploads/news/ and their path is save in mongoDb) For my news I can see the title, message, date but the picture is broken and I've only the alt.
When I go to the console and go on the element, the patch is OK "c:/users/......... /public/uploads/news/nameofmypicture.jpg".
I just got an error message "not allowed to load local resources"

import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { dateParser, isEmpty } from "../../../general/utils/Utils";
import { updateNews } from "../../../../store/actions/news.actions";
import DeleteCard from "./DeleteCard";
import Loader from "../../../general/utils/Loading";

const Card = ({ news }) => {
    const [isLoading, setIsLoading] = useState(true);
    const [isUpdated, setIsUpdated] = useState(false);
    const [textUpdate, setTextUpdate] = useState(null);
    const newsData = useSelector((state) => state.newsReducer);
    const dispatch = useDispatch();

    const updateItem = () => {
        if (textUpdate) {
            dispatch(updateNews(news._id, textUpdate));
        }
        setIsUpdated(false);
    };

    useEffect(() => {
        !isEmpty(newsData[0]) && setIsLoading(false);
    }, [newsData]);

    return (

            {isLoading ? (
                <Loader />
            ) : (
                <>

                        {isUpdated === false &&
{news.title}
}
                        {isUpdated && (

                                <textarea
                                    defaultValue={news.title}
                                    onChange={(e) => setTextUpdate(e.target.value)}
                                />

                        )}
                            {dateParser(news.createdAt)}

                        {isUpdated === false &&
{news.message}
}
                        {isUpdated && (

                                <textarea
                                    defaultValue={news.message}
                                    onChange={(e) => setTextUpdate(e.target.value)}
                                />

                                    <button className="btn btn-success" onClick={updateItem}>
                                        Valider modification
                                    </button>

                        )}
                        {news.picture && (

                        )}
                        {news.video && (

                        )}

                            <button className="btn btn-primary" onClick={() => setIsUpdated(!isUpdated)}>Edit</button>
                            <DeleteCard id={news._id} />

                </>
            )}

    );
};

export default Card;

If someone wants the full code
https://github.com/macath/AJC-modelism
If you have more questions, ask me. I'm on this problem since 4 days, I really don't understand why it's don't work.
I specify that this project will be put online so I need a valid solution on a server and not only local

Ps : sorry for my English I'm French

Body:
Thanks @Rolland Costomarob & @Siddharth Seth
I think the problem is that, i use multer to upload my pictures and i think i don't use it correctly.

const router = require('express').Router();
const newsController = require('../controllers/news.controller');

const multer = require('multer');
const imageStorage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, './client/public/uploads/')
    },
    filename: (req, file, cb) => {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
        cb(null, 'file-' + uniqueSuffix + '.jpg')
    }
});
const upload = multer({
    limits: {
        fileSize: 10000000
    },
    fileFilter: (req, file, cb) => {
        if (file.mimetype === 'image/png' || file.mimetype === 'image/jpg' || file.mimetype === 'image/jpeg') {
          cb(null, true);
        }
        else {
          cb(new multer.MulterError('mauvais format de document'));
        }
      },
    storage: imageStorage
});

router.get('/', newsController.readNews);
router.post('/', upload.single('file'), newsController.createNews);
router.put('/:id', newsController.updateNews);
router.delete('/:id', newsController.deleteNews);

module.exports = router;

If you have the solution, you just save my life


问:
GNU Radio File Format for the recorded samples
Do you know the format in which GNU Radio ( File Sink in GNU Radio Companion)  stores the samples in the Binary File?

I need to read these samples in Matlab, but the problem is the file is too big to be read in Matlab.

I am writing the program in C++ to read this binary file.

答:
Ben's answer still stands – but it's from a time long past (the module organization points at GNU Radio 3.6, I think). Organizationally, things are different now; data-wise, the File Sink remained the same.

GNU Radio now has relatively much block documentation in their wiki. In particular, the File Sink documentation page has a section on Handling File Sink data; not to overquote that:

// This is C++17
#include <algorithm>
#include <cmath>
#include <complex>
#include <cstddef>
#include <filesystem>
#include <fstream>
#include <string_view>
#include <vector>

#include <fmt/format.h>
#include <fmt/ranges.h>

using sample_t = std::complex<float>;
using power_t = float;
constexpr std::size_t read_block_size = 1 << 16;

int main(int argc, char *argv[]) {
  // expect exactly one argument, a file name
  if (argc != 2) {
    fmt::print(stderr, "Usage: {} FILE_NAME", argv[0]);
    return -1;
  }
  // just for convenience; we could as well just use `argv[1]` throughout the
  // code
  std::string_view filename(argv[1]);

  // check whether file exists
  if (!std::filesystem::exists(filename.data())) {
    fmt::print(stderr, "file '{:s}' not found\n", filename);
    return -2;
  }

  // calculate how many samples to read
  auto file_size = std::filesystem::file_size(std::filesystem::path(filename));
  auto samples_to_read = file_size / sizeof(sample_t);

  // construct and reserve container for resulting powers
  std::vector<power_t> powers;
  powers.reserve(samples_to_read);

  std::ifstream input_file(filename.data(), std::ios_base::binary);
  if (!input_file) {
    fmt::print(stderr, "error opening '{:s}'\n", filename);
    return -3;
  }

  // construct and reserve container for read samples
  // if read_block_size == 0, then read the whole file at once
  std::vector<sample_t> samples;
  if (read_block_size)
    samples.resize(read_block_size);
  else
    samples.resize(samples_to_read);

  fmt::print(stderr, "Reading {:d} samples…\n", samples_to_read);
  while (samples_to_read) {
    auto read_now = std::min(samples_to_read, samples.size());
    input_file.read(reinterpret_cast<char *>(samples.data()),
                    read_now * sizeof(sample_t));
    for (size_t idx = 0; idx < read_now; ++idx) {
      auto magnitude = std::abs(samples[idx]);
      powers.push_back(magnitude * magnitude);
    }
    samples_to_read -= read_now;
  }

  // we're not actually doing anything with the data. Let's print it!
  fmt::print("Power\n{}\n", fmt::join(powers, "\n"));
}
```

ContentLicense: CC BY-SA 3.0


问:
How to interpret dplyr message `summarise()` regrouping output by 'x' (override with `.groups` argument)?
I started getting a new message (see post title) when running group_by and summarise() after updating to dplyr development version 0.8.99.9003.

Here is an example to recreate the output:

```<code>library(tidyverse)
library(hablar)
df <- read_csv("year, week, rat_house_females, rat_house_males, mouse_wild_females, mouse_wild_males
               2018,10,1,1,1,1
               2018,10,1,1,1,1
               2018,11,2,2,2,2
               2018,11,2,2,2,2
               2019,10,3,3,3,3
               2019,10,3,3,3,3
               2019,11,4,4,4,4
               2019,11,4,4,4,4") %>%
  convert(chr(year,week)) %>%
  mutate(total_rodents = rowSums(select_if(., is.numeric))) %>%
  convert(num(year,week)) %>%
  group_by(year,week) %>% summarise(average = mean(total_rodents))
</code>```

The output tibble is correct, but this message appears:

summarise() regrouping output by 'year' (override with .groups argument)

How should this be interpreted? Why does it report regrouping only by 'year' when I grouped by both year and week? Also, what does it mean to override and why would I want to do that?

I don't think the message indicates a problem because it appears throughout the dplyr vignette:
https://cran.r-project.org/web/packages/dplyr/vignettes/programming.html

I believe it is a new message because it has only appeared on very recent SO questions such as How to melt pairwise.wilcox.test output using dplyr? and R Aggregate over multiple columns (neither of which addresses the regrouping/override message).

Thank you!

答:
This can be as a result of summarise_all() vs summarise(across(everything()... when you have 2 or more grouping columns

```<code>> tibble(gr1=c(1,1,2), gr2=c(1,1,2), val=1:3) %>%
    group_by(gr1, gr2) %>%
    summarise(across(everything(), mean))

#`summarise()` has grouped output by 'gr1'.
# You can override using the #`.groups` argument.

# A tibble: 2 x 3
# Groups:   gr1 [2]
    gr1   gr2   val
  <dbl> <dbl> <dbl>
1     1     1   1.5
2     2     2   3

> tibble(gr1=c(1,1,2), gr2=c(1,1,2), val=1:3) %>%
+     group_by(gr1, gr2) %>%
+     summarise_all(mean)
# No warnings here

# A tibble: 2 x 3
# Groups:   gr1 [2]
    gr1   gr2   val
  <dbl> <dbl> <dbl>
1     1     1   1.5
2     2     2   3
</code>```

So, the warning meaning: despite everything(), some of the columns will be skipped (grouping ones) in summarise()

Body:
I started getting a new message (see post title) when running group_by and summarise() after updating to dplyr development version 0.8.99.9003.

Here is an example to recreate the output:

library(tidyverse)
library(hablar)
df <- read_csv("year, week, rat_house_females, rat_house_males, mouse_wild_females, mouse_wild_males
               2018,10,1,1,1,1
               2018,10,1,1,1,1
               2018,11,2,2,2,2
               2018,11,2,2,2,2
               2019,10,3,3,3,3
               2019,10,3,3,3,3
               2019,11,4,4,4,4
               2019,11,4,4,4,4") %>%
  convert(chr(year,week)) %>%
  mutate(total_rodents = rowSums(select_if(., is.numeric))) %>%
  convert(num(year,week)) %>%
  group_by(year,week) %>% summarise(average = mean(total_rodents))

The output tibble is correct, but this message appears:

summarise() regrouping output by 'year' (override with .groups argument)

How should this be interpreted? Why does it report regrouping only by 'year' when I grouped by both year and week? Also, what does it mean to override and why would I want to do that?

I don't think the message indicates a problem because it appears throughout the dplyr vignette:
https://cran.r-project.org/web/packages/dplyr/vignettes/programming.html

I believe it is a new message because it has only appeared on very recent SO questions such as How to melt pairwise.wilcox.test output using dplyr? and R Aggregate over multiple columns (neither of which addresses the regrouping/override message).

Thank you!

Body:
This can be as a result of summarise_all() vs summarise(across(everything()... when you have 2 or more grouping columns

> tibble(gr1=c(1,1,2), gr2=c(1,1,2), val=1:3) %>%
    group_by(gr1, gr2) %>%
    summarise(across(everything(), mean))

#`summarise()` has grouped output by 'gr1'.
# You can override using the #`.groups` argument.

# A tibble: 2 x 3
# Groups:   gr1 [2]
    gr1   gr2   val
  <dbl> <dbl> <dbl>
1     1     1   1.5
2     2     2   3

> tibble(gr1=c(1,1,2), gr2=c(1,1,2), val=1:3) %>%
+     group_by(gr1, gr2) %>%
+     summarise_all(mean)
# No warnings here

# A tibble: 2 x 3
# Groups:   gr1 [2]
    gr1   gr2   val
  <dbl> <dbl> <dbl>
1     1     1   1.5
2     2     2   3

So, the warning meaning: despite everything(), some of the columns will be skipped (grouping ones) in summarise()


问:
How to populate mongoose with obejectId which is defined as Number?
I'm trying to populate my user requests.profileId but it returns only nulls.

I have the following schemas:

First Schema:

```<code>const profileSchema = new mongoose.Schema({
  _id: { type: Number }, //<- _id is defined as a number which represents mobile number (easier for me to handle)
  first: { type: String },
  second: { type: String },
});

module.exports = mongoose.model('Profile', profileSchema, 'profiles');
</code>```

Second Schema:

```<code>const userSchema = new mongoose.Schema({
  firstName: { type: String },
  lastName: { type: String },
  requests: [
    {
      profileId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Profile',
      },
      requestTime: { type: Date, default: Date.now },
    },
  ],
});

module.exports = mongoose.model('User', userSchema, 'users');
</code>```

Here is my code:

```<code>const user = await User.findById(req.user).populate('requests.profileId');
console.log(user.requests);
</code>```

Here is the output:

```<code>[
  {
    _id: 6201633869648e2b74c00a10,
    profileId: null,
    requestTime: 2022-02-07T18:21:44.722Z
  },
  {
    _id: 6201633b69648e2b74c00a11,
    profileId: null,
    requestTime: 2022-02-07T18:21:47.238Z
  },
  {
    _id: 620238f9d2b5dd3dee6c41a2,
    profileId: null,
    requestTime: 2022-02-08T09:33:45.176Z
  },
  {
    _id: 620239253220343dfd7cfdd9,
    profileId: null,
    requestTime: 2022-02-08T09:34:29.780Z
  }
]
</code>```

Here is the output without populate:

```<code>[
  {
    _id: 6201633869648e2b74c00a10,
    profileId: 393732353235303134343330, //<- typeof profileId is obeject
    requestTime: 2022-02-07T18:21:44.722Z
  },
  {
    _id: 6201633b69648e2b74c00a11,
    profileId: 393732353435353333313131,
    requestTime: 2022-02-07T18:21:47.238Z
  },
  {
    _id: 620238f9d2b5dd3dee6c41a2,
    profileId: 393732353435353333313131,
    requestTime: 2022-02-08T09:33:45.176Z
  },
  {
    _id: 620239253220343dfd7cfdd9,
    profileId: 393732353435353333313131,
    requestTime: 2022-02-08T09:34:29.780Z
  }
]
</code>```

Currently Profile.findById(mobileNumber) works fine.

Any ideas what went wrong?

Will greatly appreciate your assistance.

Thanks in advance :)

答:
For future readers having the same issue!

I've found a solution for this issue.

I had to change the profileId type to Number in my userSchema:

```<code>const userSchema = new mongoose.Schema({
  firstName: { type: String },
  lastName: { type: String },
  requests: [
    {
      profileId: {
        type: Number // and NOT use type: mongoose.Schema.Types.ObjectId,
        ref: 'Profile',
      },
      requestTime: { type: Date, default: Date.now },
    },
  ],
});

module.exports = mongoose.model('User', userSchema, 'users');
</code>```

Now it works!

Body:
I'm trying to populate my user requests.profileId but it returns only nulls.

I have the following schemas:

First Schema:

const profileSchema = new mongoose.Schema({
  _id: { type: Number }, //<- _id is defined as a number which represents mobile number (easier for me to handle)
  first: { type: String },
  second: { type: String },
});

module.exports = mongoose.model('Profile', profileSchema, 'profiles');

Second Schema:

const userSchema = new mongoose.Schema({
  firstName: { type: String },
  lastName: { type: String },
  requests: [
    {
      profileId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Profile',
      },
      requestTime: { type: Date, default: Date.now },
    },
  ],
});

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

Here is my code:

const user = await User.findById(req.user).populate('requests.profileId');
console.log(user.requests);

Here is the output:

[
  {
    _id: 6201633869648e2b74c00a10,
    profileId: null,
    requestTime: 2022-02-07T18:21:44.722Z
  },
  {
    _id: 6201633b69648e2b74c00a11,
    profileId: null,
    requestTime: 2022-02-07T18:21:47.238Z
  },
  {
    _id: 620238f9d2b5dd3dee6c41a2,
    profileId: null,
    requestTime: 2022-02-08T09:33:45.176Z
  },
  {
    _id: 620239253220343dfd7cfdd9,
    profileId: null,
    requestTime: 2022-02-08T09:34:29.780Z
  }
]

Here is the output without populate:

[
  {
    _id: 6201633869648e2b74c00a10,
    profileId: 393732353235303134343330, //<- typeof profileId is obeject
    requestTime: 2022-02-07T18:21:44.722Z
  },
  {
    _id: 6201633b69648e2b74c00a11,
    profileId: 393732353435353333313131,
    requestTime: 2022-02-07T18:21:47.238Z
  },
  {
    _id: 620238f9d2b5dd3dee6c41a2,
    profileId: 393732353435353333313131,
    requestTime: 2022-02-08T09:33:45.176Z
  },
  {
    _id: 620239253220343dfd7cfdd9,
    profileId: 393732353435353333313131,
    requestTime: 2022-02-08T09:34:29.780Z
  }
]

Currently Profile.findById(mobileNumber) works fine.

Any ideas what went wrong?

Will greatly appreciate your assistance.

Thanks in advance :)

Body:
For future readers having the same issue!

I've found a solution for this issue.

I had to change the profileId type to Number in my userSchema:

const userSchema = new mongoose.Schema({
  firstName: { type: String },
  lastName: { type: String },
  requests: [
    {
      profileId: {
        type: Number // and NOT use type: mongoose.Schema.Types.ObjectId,
        ref: 'Profile',
      },
      requestTime: { type: Date, default: Date.now },
    },
  ],
});

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

Now it works!


问:
Why can't I use `using` in a multiple inheritance c++?
I tried to implement some interfaces and their children. This is my idea:

```<code>         Interface
         /       \
  Interface2    InterfaceDefination
        |        /
  Interface2Defination
</code>```

And this is my code:

#include <iostream>

class Interface {
public:
  virtual void method1() = 0;
  virtual void print() = 0;
};

class Interface2 : public Interface {
public:
  virtual void method2() = 0;
};

class InterfaceDefination : public Interface {
public:
  virtual void method1() override {
    std::cout << "method1 from InterfaceDefination\n";
  }
};

class Interface2Defination : public Interface2, public InterfaceDefination {
public:
  using InterfaceDefination::method1;
  virtual void print() override {
    std::cout << "print from Interface2Defination\n";
  }
  virtual void method2() override {
    std::cout << "method2 from Interface2Defination\n";
  }
};

int main() {
  Interface2Defination c;
  c.method1();
  c.method2();
  c.print();
}
```
<p>My expected output is:</p>
```method1 from InterfaceDefination
method2 from Interface2Defination
print from Interface2Defination
```
<p>But accidentally i received these errors:</p>
```main.cpp:33:24: error: variable type 'Interface2Defination' is an abstract class
  Interface2Defination c;
                       ^
main.cpp:5:16: note: unimplemented pure virtual method 'method1' in 'Interface2Defination'
  virtual void method1() = 0;
               ^
1 error generated.
make: *** [<builtin>: main.o] Error 1
exit status 2
```

https://godbolt.org/z/9ncoGfn4P

In this case, the error means using keyword is not making method method1 usable in class Interface2Defination. What should i do with it?

答:
A using declaration is a declaration. It is not a definition. It does not define anything "new". What it does is declare: ok, I have a symbol X, but it really refers to X in my parent class (for this version of a using declaration).

You might ask what's the point, aren't you inheriting X from your parent class in the normal fashion. Yes, that's true, but it's not the same thing, but the technical differences are mostly immaterial here.

What's also important here is that the shown diagram is misleading. It is a popular way to portray (non-virtual) diamond inheritance, but every time it's shown, it is 100% wrong. This is because Interface2Defination does not inherit one instance of Interface, but two. This is a more accurate inheritance diagram:

```<code>  Interface          Interface
       |                |
  Interface2    InterfaceDefination
        |        /
  Interface2Defination
</code>```

For each one of the two instances of Interface parent classes, only one of its abstract methods gets defined and overridden, hence the shown code is ill-formed.

The using declaration does not define the imported method in the child class, and formally override it. A using declaration does not "count" for the purpose of overriding an abstract method. Only formally defining an inherited abstract method does that, not declaring one.

Body:
I tried to implement some interfaces and their children. This is my idea:

         Interface
         /       \
  Interface2    InterfaceDefination
        |        /
  Interface2Defination

And this is my code:

#include <iostream>

class Interface {
public:
  virtual void method1() = 0;
  virtual void print() = 0;
};

class Interface2 : public Interface {
public:
  virtual void method2() = 0;
};

class InterfaceDefination : public Interface {
public:
  virtual void method1() override {
    std::cout << "method1 from InterfaceDefination\n";
  }
};

class Interface2Defination : public Interface2, public InterfaceDefination {
public:
  using InterfaceDefination::method1;
  virtual void print() override {
    std::cout << "print from Interface2Defination\n";
  }
  virtual void method2() override {
    std::cout << "method2 from Interface2Defination\n";
  }
};

int main() {
  Interface2Defination c;
  c.method1();
  c.method2();
  c.print();
}

My expected output is:

method1 from InterfaceDefination
method2 from Interface2Defination
print from Interface2Defination

But accidentally i received these errors:

main.cpp:33:24: error: variable type 'Interface2Defination' is an abstract class
  Interface2Defination c;
                       ^
main.cpp:5:16: note: unimplemented pure virtual method 'method1' in 'Interface2Defination'
  virtual void method1() = 0;
               ^
1 error generated.
make: *** [<builtin>: main.o] Error 1
exit status 2

https://godbolt.org/z/9ncoGfn4P

In this case, the error means using keyword is not making method method1 usable in class Interface2Defination. What should i do with it?

Body:
A using declaration is a declaration. It is not a definition. It does not define anything "new". What it does is declare: ok, I have a symbol X, but it really refers to X in my parent class (for this version of a using declaration).

You might ask what's the point, aren't you inheriting X from your parent class in the normal fashion. Yes, that's true, but it's not the same thing, but the technical differences are mostly immaterial here.

What's also important here is that the shown diagram is misleading. It is a popular way to portray (non-virtual) diamond inheritance, but every time it's shown, it is 100% wrong. This is because Interface2Defination does not inherit one instance of Interface, but two. This is a more accurate inheritance diagram:

  Interface          Interface
       |                |
  Interface2    InterfaceDefination
        |        /
  Interface2Defination

For each one of the two instances of Interface parent classes, only one of its abstract methods gets defined and overridden, hence the shown code is ill-formed.

The using declaration does not define the imported method in the child class, and formally override it. A using declaration does not "count" for the purpose of overriding an abstract method. Only formally defining an inherited abstract method does that, not declaring one.


问:
ExtentReports - screenshot not in the report - broken image
I'm trying to add a screenshot to my ExtentReport HTML file, but for some reason, the image is not there even though it DOES exist and the console shows that it's looking at the correct place (href is correct).

This is the latest trial code:

```<code>Screenshot screenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000)).takeScreenshot(driver);
String destination = getScreenshotPath();
ImageIO.write(screenshot.getImage(), "IMG", new File(destination));
test.fail("Details: " + test.addScreenCaptureFromPath(destination));
</code>```

The screenshot gets saved in the destination.
When I try the debugging mode, or look at the report, it's printed as:

Details: com.aventstack.extentreports.ExtentTest@62041567
and there's a broken image under it:

答:
I tried the following code, and it resulted in a screenshot being recorded in the report.

File file = new File("./Screenshots/" + result.getName() + ".png");

String absolutePath = file.getAbsolutePath();
logger.fail("details", MediaEntityBuilder.createScreenCaptureFromPath(absolutePath).build());
```

Body:
I'm trying to add a screenshot to my ExtentReport HTML file, but for some reason, the image is not there even though it DOES exist and the console shows that it's looking at the correct place (href is correct).

This is the latest trial code:

Screenshot screenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000)).takeScreenshot(driver);
String destination = getScreenshotPath();
ImageIO.write(screenshot.getImage(), "IMG", new File(destination));
test.fail("Details: " + test.addScreenCaptureFromPath(destination));

The screenshot gets saved in the destination.
When I try the debugging mode, or look at the report, it's printed as:

Details: com.aventstack.extentreports.ExtentTest@62041567
and there's a broken image under it:


答:
Well, you could:

Find all the methods with the right name

For each method:

Check whether the last parameter in the method is a "params" array (as per this question; thanks yas4891)

Check whether the parameter types you've been given up to but not including the last parameter match the ones on the method

Check whether the remaining parameter types all match the array element type of the final parameter

Note that once you'd found a match (and not found a match that didn't require this params expansion) you'd then need to remember that so that you could deal with the arguments appropriately later (assuming you want to actually call the method).

It's a bit of a faff, to be honest... the way I see it you have three options:

Change the caller to pass in typeof(int[]) and your existing code will work

Change FancyGetMethodInfo to handle parameter arrays as described above

Change Sum to accept two integers (or possibly have various overloads)

It's up to you which route you choose...

Title: How to test if a valid Method exists when params are involved


问:
Optimize network range function
I found a blog post by Richard Paquin Morel on computing a network range function in R (Burt 1981; Reagans and McEvily 2003). The function assigns a value to each network node based on the number of its contacts and the interconnectedness of these nodes. The network range can be computed accross subgroups of nodes (e.g. female and male nodes). These are stored as attributes of the vertices.

The author's example is very illustrative, but it is based on a relatively small network (about 100 nodes). I have a network with about 200,000 nodes, which means the performance of the function is not suited for my analyses.

I present you an example where the size of a random graph according to the Erdos-Renyi model can be manipulated to time the performance of the functions.

I am unfamiliar with optimizing R code, but I think the adjacency matrix needs to be stored more efficiently (e.g., a sparse matrix). My attempts so far did not succeed in producing a working function.

```<code>rm(list=ls())

library(igraph)
library(statnet)
library(intergraph)
library(tictoc)

set.seed(42)

## Source: https://ramorel.github.io/network-range/
## Function to find network range for each node in a network
## Arguments:
##  net = adjacency matrix, igraph graph, or network object
##  attr = Vector of attributes associated with each node in net
##  directed = boolean indicated if the network is directed or not

netrange <- function(net, attr, directed = TRUE){
  require(reshape2)
  if (class(net) == "igraph") {
    net <- as_adjacency_matrix(net, sparse = F)
  }
  else {
    if(class(net) == "network") {
      net <- as.matrix.network(net)
    }
    else {
      net <- as.matrix(net)
    }
  }
  if(nrow(net) != length(attr)) {
    stop("Number of nodes must match length of attributes vector")
  }
  else {
    if (directed == TRUE){
      ns <- colnames(net)
      el <- melt(net, varnames=c("ego", "alter"), value.name = "weight")
      df <- cbind(rownames(net), attr)
      el$ego_grp <- df[match(el[,1], df[,1]), 2]
      el$alter_grp <- df[match(el[,2], df[,1]), 2]

      #FINDING p_k, the strength of ties within each group
      # z_iq = sum of strength of ties from nodes in group _k_ to all other alters
      # z_ij = sum of strength of ties from nodes in group _k_ to alters in group _k_

      z_iq <- sapply(unique(attr), function(x) {
        sum(el[which(el$ego_grp==x), "weight"])
      })
      z_ij <- sapply(unique(attr), function(x) {
        sum(el[which(el$ego_grp==x & el$alter_grp==x), "weight"])
      })
      p_k <- z_ij / z_iq
      p_k[is.na(p_k)] <- 0

      #FINDING p_ik, the strength of connection from person i to group k
      # x_iq = sum of strength of ties for _i_ to alters in group _k_
      # x_ij = sum of strength of ties for _i_ to all alters

      x_ij <- sapply(colnames(net), function(x) {
        sum(el[which(el$ego==x), "weight"])
      }
      )
      x_iq <- list(NULL)
      for(i in colnames(net)) {
        x_iq[[i]] <- sapply(unique(attr), function(x) {
          sum(el[which(el$ego==i & el$alter_grp==x), "weight"])
        }
        )
      }
      x_iq <- x_iq[-c(1)] #x_iq is now a list where each elements is a vector of node _i_ summed strength of tie to group _k_

      p_ik <- lapply(1:length(x_iq),
                     function(x) x_iq[[x]] / x_ij[x])

      # FINDING nd_i, the network diversity score for node _i_

      nd_i <- sapply(1:length(p_ik),
                     function(x) 1 - sum(p_k*p_ik[[x]]^2, na.rm = F)
      )
    }
    else {
      ns <- colnames(net)
      el <- melt(net, varnames=c("ego", "alter"), value.name = "weight")
      dup <- data.frame(t(apply(el[,1:2],1,sort)))

      el <- el[!duplicated(dup),]
      df <- cbind(rownames(net), attr)
      el$ego_grp <- df[match(el[,1], df[,1]), 2]
      el$alter_grp <- df[match(el[,2], df[,1]), 2]

      #FINDING p_k, the strength of ties within each group
      # z_iq = sum of strength of ties from nodes in group _k_ to all other alters
      # z_ij = sum of strength of ties from nodes in group _k_ to alters in group _k_

      z_iq <- sapply(unique(attr), function(x) {
        sum(el[which(el$ego_grp==x | el$alter_grp==x), "weight"])
      })
      z_ij <- sapply(unique(attr), function(x) {
        sum(el[which(el$ego_grp==x & el$alter_grp==x), "weight"])
      })
      p_k <- z_ij / z_iq
      p_k[is.na(p_k)] <- 0

      #FINDING p_ik, the strength of connection from person i to group k
      # x_iq = sum of strength of ties for _i_ to alters in group _k_
      # x_ij = sum of strength of ties for _i_ to all alters

      x_ij <- sapply(colnames(net), function(x) {
        sum(el[which(el$ego==x | el$alter==x), "weight"])
      }
      )
      x_iq <- list(NULL)
      for(i in colnames(net)) {
        x_iq[[i]] <- sapply(unique(attr), function(x) {
          sum(el[which(el$ego==i & el$alter_grp==x), "weight"],
              el[which(el$alter==i & el$ego_grp==x), "weight"])
        }
        )
      }
      x_iq <- x_iq[-c(1)] #x_iq is now a list where each elements is a vector of node _i_ summed strength of tie to group _k_

      p_ik <- lapply(1:length(x_iq),
                     function(x) x_iq[[x]] / x_ij[x])

      # FINDING nd_i, the network diversity score for node _i_

      nd_i <- sapply(1:length(p_ik),
                     function(x) 1 - sum(p_k*p_ik[[x]]^2, na.rm = F)
      )
    }
    return(nd_i)
  }
}

# Generate exemplary network

g <- igraph::erdos.renyi.game(1000, 150, type = "gnm")

## Add categorical (binary) vertex feature: female

V(g)$female <- sample(c(0,1), replace=TRUE, size=length(V(g)))
V(g)$female

## transform igraph to statnet

net <- intergraph::asNetwork(g)

## Apply network function

tic()
range_female <- netrange(net,
                         net %v% "female",
                         directed = T)
seq_time <- toc()
</code>```

答:
Best thing to optimize is to use profiling using  profvis which shows where your bottle necks are. I took part of your function though.

There we saw x_ij <- sapply(colnames(net), function(x) { sum(el[which(el$ego==x | el$alter==x), "weight"]) }) taking terribly long.

I prefer data.table myself so just provide the code here to speed up that part which takes a few seconds only. Try the same then for creating x_iq.

```<code>xx_ij <- el[, .(xxij = lapply(.SD, sum)), by = c("ego"), .SDcols = c("weight")]
xx_ij2 <- xx_ij$xxij
names(xx_ij2) <- xx_ij$ego

identical(x_ij, unlist(xx_ij2))
# TRUE
</code>```

**profiling

```<code>library(profvis)
p <- profvis({
  ## code here
})

f <- paste0("profile_", as.Date(now()), ".html")
htmlwidgets::saveWidget(p, f)
browseURL(f)
</code>```

Title: Optimize network range function

Body:
I found a blog post by Richard Paquin Morel on computing a network range function in R (Burt 1981; Reagans and McEvily 2003). The function assigns a value to each network node based on the number of its contacts and the interconnectedness of these nodes. The network range can be computed accross subgroups of nodes (e.g. female and male nodes). These are stored as attributes of the vertices.

The author's example is very illustrative, but it is based on a relatively small network (about 100 nodes). I have a network with about 200,000 nodes, which means the performance of the function is not suited for my analyses.

I present you an example where the size of a random graph according to the Erdos-Renyi model can be manipulated to time the performance of the functions.

I am unfamiliar with optimizing R code, but I think the adjacency matrix needs to be stored more efficiently (e.g., a sparse matrix). My attempts so far did not succeed in producing a working function.

rm(list=ls())

library(igraph)
library(statnet)
library(intergraph)
library(tictoc)

set.seed(42)

## Source: https://ramorel.github.io/network-range/
## Function to find network range for each node in a network
## Arguments:
##  net = adjacency matrix, igraph graph, or network object
##  attr = Vector of attributes associated with each node in net
##  directed = boolean indicated if the network is directed or not

netrange <- function(net, attr, directed = TRUE){
  require(reshape2)
  if (class(net) == "igraph") {
    net <- as_adjacency_matrix(net, sparse = F)
  }
  else {
    if(class(net) == "network") {
      net <- as.matrix.network(net)
    }
    else {
      net <- as.matrix(net)
    }
  }
  if(nrow(net) != length(attr)) {
    stop("Number of nodes must match length of attributes vector")
  }
  else {
    if (directed == TRUE){
      ns <- colnames(net)
      el <- melt(net, varnames=c("ego", "alter"), value.name = "weight")
      df <- cbind(rownames(net), attr)
      el$ego_grp <- df[match(el[,1], df[,1]), 2]
      el$alter_grp <- df[match(el[,2], df[,1]), 2]

      #FINDING p_k, the strength of ties within each group
      # z_iq = sum of strength of ties from nodes in group _k_ to all other alters
      # z_ij = sum of strength of ties from nodes in group _k_ to alters in group _k_

      z_iq <- sapply(unique(attr), function(x) {
        sum(el[which(el$ego_grp==x), "weight"])
      })
      z_ij <- sapply(unique(attr), function(x) {
        sum(el[which(el$ego_grp==x & el$alter_grp==x), "weight"])
      })
      p_k <- z_ij / z_iq
      p_k[is.na(p_k)] <- 0

      #FINDING p_ik, the strength of connection from person i to group k
      # x_iq = sum of strength of ties for _i_ to alters in group _k_
      # x_ij = sum of strength of ties for _i_ to all alters

      x_ij <- sapply(colnames(net), function(x) {
        sum(el[which(el$ego==x), "weight"])
      }
      )
      x_iq <- list(NULL)
      for(i in colnames(net)) {
        x_iq[[i]] <- sapply(unique(attr), function(x) {
          sum(el[which(el$ego==i & el$alter_grp==x), "weight"])
        }
        )
      }
      x_iq <- x_iq[-c(1)] #x_iq is now a list where each elements is a vector of node _i_ summed strength of tie to group _k_

      p_ik <- lapply(1:length(x_iq),
                     function(x) x_iq[[x]] / x_ij[x])

      # FINDING nd_i, the network diversity score for node _i_

      nd_i <- sapply(1:length(p_ik),
                     function(x) 1 - sum(p_k*p_ik[[x]]^2, na.rm = F)
      )
    }
    else {
      ns <- colnames(net)
      el <- melt(net, varnames=c("ego", "alter"), value.name = "weight")
      dup <- data.frame(t(apply(el[,1:2],1,sort)))

      el <- el[!duplicated(dup),]
      df <- cbind(rownames(net), attr)
      el$ego_grp <- df[match(el[,1], df[,1]), 2]
      el$alter_grp <- df[match(el[,2], df[,1]), 2]

      #FINDING p_k, the strength of ties within each group
      # z_iq = sum of strength of ties from nodes in group _k_ to all other alters
      # z_ij = sum of strength of ties from nodes in group _k_ to alters in group _k_

      z_iq <- sapply(unique(attr), function(x) {
        sum(el[which(el$ego_grp==x | el$alter_grp==x), "weight"])
      })
      z_ij <- sapply(unique(attr), function(x) {
        sum(el[which(el$ego_grp==x & el$alter_grp==x), "weight"])
      })
      p_k <- z_ij / z_iq
      p_k[is.na(p_k)] <- 0

      #FINDING p_ik, the strength of connection from person i to group k
      # x_iq = sum of strength of ties for _i_ to alters in group _k_
      # x_ij = sum of strength of ties for _i_ to all alters

      x_ij <- sapply(colnames(net), function(x) {
        sum(el[which(el$ego==x | el$alter==x), "weight"])
      }
      )
      x_iq <- list(NULL)
      for(i in colnames(net)) {
        x_iq[[i]] <- sapply(unique(attr), function(x) {
          sum(el[which(el$ego==i & el$alter_grp==x), "weight"],
              el[which(el$alter==i & el$ego_grp==x), "weight"])
        }
        )
      }
      x_iq <- x_iq[-c(1)] #x_iq is now a list where each elements is a vector of node _i_ summed strength of tie to group _k_

      p_ik <- lapply(1:length(x_iq),
                     function(x) x_iq[[x]] / x_ij[x])

      # FINDING nd_i, the network diversity score for node _i_

      nd_i <- sapply(1:length(p_ik),
                     function(x) 1 - sum(p_k*p_ik[[x]]^2, na.rm = F)
      )
    }
    return(nd_i)
  }
}

# Generate exemplary network

g <- igraph::erdos.renyi.game(1000, 150, type = "gnm")

## Add categorical (binary) vertex feature: female

V(g)$female <- sample(c(0,1), replace=TRUE, size=length(V(g)))
V(g)$female

## transform igraph to statnet

net <- intergraph::asNetwork(g)

## Apply network function

tic()
range_female <- netrange(net,
                         net %v% "female",
                         directed = T)
seq_time <- toc()

Body:
Best thing to optimize is to use profiling using  profvis which shows where your bottle necks are. I took part of your function though.

There we saw x_ij <- sapply(colnames(net), function(x) { sum(el[which(el$ego==x | el$alter==x), "weight"]) }) taking terribly long.

I prefer data.table myself so just provide the code here to speed up that part which takes a few seconds only. Try the same then for creating x_iq.

xx_ij <- el[, .(xxij = lapply(.SD, sum)), by = c("ego"), .SDcols = c("weight")]
xx_ij2 <- xx_ij$xxij
names(xx_ij2) <- xx_ij$ego

identical(x_ij, unlist(xx_ij2))
# TRUE

**profiling

library(profvis)
p <- profvis({
  ## code here
})

f <- paste0("profile_", as.Date(now()), ".html")
htmlwidgets::saveWidget(p, f)
browseURL(f)


问:
How to click on an element (html tag) in Robot Framework Selenium
I'm trying to find an element on html tags using robot framework. I want to click on first element what ever the element is.

For example

Input text in the text field and then pass key enter

The item will show up and i want to click on first item but i cant

My Robot Code

```<code>Open Browser    http://www.tarad.com    chrome
Wait Until Element Is Visible    id=keyword
Input Text    id=keyword    dog
Press Key    id=keyword    \\13
Wait Until Element Is Visible    id=wrapper_body_all
Element Should Be Visible    id=wrapper_body_all
Click Element    xpath=//div[id='warpper_all']/div[id='wapper_body_all']//ul/il//img[constains(@src,'//img.trd.cm/120/120/sumpow/img-lib/spd_20140314140410_b.jpg')]
</code>```

My HTML Tag

```<code><div id="wrapper_body_all">
<div class="main-wrap">
    <!--start : #rightProduct-->
    <div class="section-col-right">
        <!--start : rec_product -->
        <div class="rec_product">
        <!-- end : rec_product -->
        <div class="rec_product">
            <div class="section-products-box">
                <div class="hitproduct-body">
                    <ul class="hitproduct-list list">
                       <!--start : product-list-->
                        <li>
                            <div class="item-border list">
                                <div class="item-image">
                                        <a href="//www.tarad.com/product/5913180" title="ลำโพงน่ารัก dog">
                                            <img src="//img.trd.cm/120/120/sumpow/img-lib/spd_20140314140410_b.jpg"
                                            alt="ลำโพงน่ารัก dog" data-pagespeed-url-hash="3676782613"
                                            onload="pagespeed.CriticalImages.checkImageForCriticality(this);">
                                        </a>
                                </div>
                                <div class="item-details">
                                    <div class="product-name">
                                        <a href="//www.tarad.com/product/5913180" title="ลำโพงน่ารัก dog">ลำโพงน่ารัก dog</a>
                                    </div>
                                </div>
                            </div>
                        </li>
                        <!--end : product-list-->
                        <!--start : product-list-->
                        <li>
                            <div class="item-border list">
                                <div class="item-image">
                                    <a href="//www.tarad.com/product/6755464" title="Brewdog Magic Stone Dog - 330 ml - 5">
                                        <img src="//www.tarad.com/images/web_main/default150x150.gif"
                                        alt="Brewdog Magic Stone Dog - 330 ml - 5" data-pagespeed-url-hash="2123596038"
                                        onload="pagespeed.CriticalImages.checkImageForCriticality(this);">
                                    </a>
                                </div>
                                <div class="item-details">
                                    <div class="product-name">
                                        <a href="//www.tarad.com/product/6755464" title="Brewdog Magic Stone Dog - 330 ml - 5">
                                            Brewdog Magic Stone Dog - 330 ml - 5</a>
                                    </div>
                                </div>
                            </div>
                        </li>
                        <!--end : product-list-->
                        ....
                        ....
                        ....
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

Error

答:
```<code>Sometimes you can use another element earlier or later that does find it, and then use
</code>```

/preceding::div[1]

or

/ascending::div[1]

```<code>respectively
</code>```

Body:
I'm trying to find an element on html tags using robot framework. I want to click on first element what ever the element is.

For example

Input text in the text field and then pass key enter

The item will show up and i want to click on first item but i cant

My Robot Code

Open Browser    http://www.tarad.com    chrome
Wait Until Element Is Visible    id=keyword
Input Text    id=keyword    dog
Press Key    id=keyword    \\13
Wait Until Element Is Visible    id=wrapper_body_all
Element Should Be Visible    id=wrapper_body_all
Click Element    xpath=//div[id='warpper_all']/div[id='wapper_body_all']//ul/il//img[constains(@src,'//img.trd.cm/120/120/sumpow/img-lib/spd_20140314140410_b.jpg')]

My HTML Tag

                                        ลำโพงน่ารัก dog

                                            Brewdog Magic Stone Dog - 330 ml - 5

                        ....
                        ....
                        ....

Error

Body:
Sometimes you can use another element earlier or later that does find it, and then use

/preceding::div[1]

or

/ascending::div[1]

respectively


问:
Error : cc.fr.300.bin cannot be opened for loading
I am using Azure Machine Learning and Azure Databricks.
In Azure Databricks I have a script.py written by %% command (%%write script.py).

In this script I tried to load cc.fr.300.bin that is saved as a model in Azure Machine Learning.

I did this:

```<code>import fasttext
fr_model_path = os.path.join(os.getenv('AZUREML_MODEL_DIR'), 'cc.fr.300.bin')
fr_model = fasttext.load_model(fr_model_path)
</code>```

But I have the error :

```<code>File "/structure/azureml-app/script.py", line 134, in init
    fr_model = fasttext.load_model(fr_model_path)
  File "/azureml-envs/azureml_d7.../lib/python3.6/site-packages/fasttext/FastText.py", line 441, in load_model
    return _FastText(model_path=path)
  File "/azureml-envs/azureml_d7.../lib/python3.6/site-packages/fasttext/FastText.py", line 98, in __init__
    self.f.loadModel(model_path)
ValueError: /var/azureml-app/azureml-models/test/1/cc.fr.300.bin cannot be opened for loading!
</code>```

What can I do ?

答:
cc.nl.300.bin maybe a old version file. The latest fasttext cannot load it.

You can try it as following:

```<code>pip uninstall fasttext

pip install fasttext==0.6.0
</code>```

Refer - https://pypi.org/project/fasttext/0.6.0/

Body:
I am using Azure Machine Learning and Azure Databricks.
In Azure Databricks I have a script.py written by %% command (%%write script.py).

In this script I tried to load cc.fr.300.bin that is saved as a model in Azure Machine Learning.

I did this:

import fasttext
fr_model_path = os.path.join(os.getenv('AZUREML_MODEL_DIR'), 'cc.fr.300.bin')
fr_model = fasttext.load_model(fr_model_path)

But I have the error :

File "/structure/azureml-app/script.py", line 134, in init
    fr_model = fasttext.load_model(fr_model_path)
  File "/azureml-envs/azureml_d7.../lib/python3.6/site-packages/fasttext/FastText.py", line 441, in load_model
    return _FastText(model_path=path)
  File "/azureml-envs/azureml_d7.../lib/python3.6/site-packages/fasttext/FastText.py", line 98, in __init__
    self.f.loadModel(model_path)
ValueError: /var/azureml-app/azureml-models/test/1/cc.fr.300.bin cannot be opened for loading!

What can I do ?

Body:
cc.nl.300.bin maybe a old version file. The latest fasttext cannot load it.

You can try it as following:

pip uninstall fasttext

pip install fasttext==0.6.0

Refer - https://pypi.org/project/fasttext/0.6.0/


问:
Istio - redirect to https external url
I'm trying to setup a simple redirect (not a proxy pass) in istio:

```<code>apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: test
spec:
  gateways:
  - test
  hosts:
  - test.com
  http:
  - redirect:
      authority: testredirect.com
      redirectCode: 302
---
apiVersion: networking.istio.io/v1beta1
kind: Gateway
metadata:
  name: test
spec:
  selector:
    istio: ingressgateway
  servers:
  - hosts:
    - test.com
    port:
      name: http
      number: 80
      protocol: HTTP2
</code>```

This creates a redirect to http://testredirect.com

How do I get this to redirect to http**s**://?

Notes:

I tried adding a DestinationRule and ServiceEntry, but that did not help

we terminate SSL at the load balancer, so our requests come on port 80 non-encrypted

答:
Below is what worked for me.</p>
```<code>- match:
  - authority:
      exact: test.com
  redirect:
    authority: testredirect.com
</code>```

Title: Istio - redirect to https external url

Body:
I'm trying to setup a simple redirect (not a proxy pass) in istio:

apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: test
spec:
  gateways:
  - test
  hosts:
  - test.com
  http:
  - redirect:
      authority: testredirect.com
      redirectCode: 302
---
apiVersion: networking.istio.io/v1beta1
kind: Gateway
metadata:
  name: test
spec:
  selector:
    istio: ingressgateway
  servers:
  - hosts:
    - test.com
    port:
      name: http
      number: 80
      protocol: HTTP2

This creates a redirect to http://testredirect.com

How do I get this to redirect to http**s**://?

Notes:

I tried adding a DestinationRule and ServiceEntry, but that did not help

we terminate SSL at the load balancer, so our requests come on port 80 non-encrypted

Body:
Below is what worked for me.

- match:
  - authority:
      exact: test.com
  redirect:
    authority: testredirect.com


问:
PHP Deployer failing on line without errors
I have a PHP Deployer task to recursively change file owner of everything in the deploy path:

```<code>task('set_owner', function () {
        run("chown -R someuser:www-data {{deploy_path}}");
    });

after('deploy:failed', 'deploy:unlock'); // Unlock after failed deploy
</code>```

Deployer failed on this task since there are some Operation not permitted errors given by this commond. Fair enough, since those files don't need changing anyway. So I add 2>&1 | grep -v 'Operation not permitted' to prevent the errors from showing:

```<code>task('set_owner', function () {
        run("chown -R deployer:www-data {{deploy_path}} 2>&1 | grep -v 'Operation not permitted'");
    });

after('deploy:failed', 'deploy:unlock'); // Unlock after failed deploy
</code>```

However when I run it Deployer still fails on this task:

```<code>➤ Executing task set_owner
[myapp.com] > chown -R someuser:www-data /var/www/myapp.com 2>&1 | grep -v 'Operation not permitted'
➤ Executing task deploy:failed
• done on [myapp.com]
✔ Ok [1ms]
➤ Executing task deploy:unlock
[myapp.com] > rm -f /var/www/myapp.com/.dep/deploy.lock
• done on [myapp.com]
✔ Ok [1s 364ms]
In Client.php line 103:

  [Deployer\Exception\RuntimeException (1)]
  The command "chown -R someuser:www-data /var/www/myapp.com 2>&
  1 | grep -v 'Operation not permitted'" failed.

  Exit Code: 1 (General error)
</code>```

Is there a way to prevent Deployer from failing in this case?

答:
You can add some directives first to your deployment file :

```<code>set('writable_mode', 'chmod');
set('writable_chmod_mode', '0755');
</code>```

Or make a chown with your webapp user.

Check your vhost in /etc/apache2/sites-available/{your-webapp}.conf.

Check your php-fpm config in php{version}-fpm directory to set the rights to your webapps user or a specific webapp user : /etc/php/{version}/fpm/pool.d/{your-webapp-fpm}.conf.

Body:
I have a PHP Deployer task to recursively change file owner of everything in the deploy path:

task('set_owner', function () {
        run("chown -R someuser:www-data {{deploy_path}}");
    });

after('deploy:failed', 'deploy:unlock'); // Unlock after failed deploy

Deployer failed on this task since there are some Operation not permitted errors given by this commond. Fair enough, since those files don't need changing anyway. So I add 2>&1 | grep -v 'Operation not permitted' to prevent the errors from showing:

task('set_owner', function () {
        run("chown -R deployer:www-data {{deploy_path}} 2>&1 | grep -v 'Operation not permitted'");
    });

after('deploy:failed', 'deploy:unlock'); // Unlock after failed deploy

However when I run it Deployer still fails on this task:

➤ Executing task set_owner
[myapp.com] > chown -R someuser:www-data /var/www/myapp.com 2>&1 | grep -v 'Operation not permitted'
➤ Executing task deploy:failed
• done on [myapp.com]
✔ Ok [1ms]
➤ Executing task deploy:unlock
[myapp.com] > rm -f /var/www/myapp.com/.dep/deploy.lock
• done on [myapp.com]
✔ Ok [1s 364ms]
In Client.php line 103:

  [Deployer\Exception\RuntimeException (1)]
  The command "chown -R someuser:www-data /var/www/myapp.com 2>&
  1 | grep -v 'Operation not permitted'" failed.

  Exit Code: 1 (General error)

Is there a way to prevent Deployer from failing in this case?

Body:
You can add some directives first to your deployment file :

set('writable_mode', 'chmod');
set('writable_chmod_mode', '0755');

Or make a chown with your webapp user.

Check your vhost in /etc/apache2/sites-available/{your-webapp}.conf.

Check your php-fpm config in php{version}-fpm directory to set the rights to your webapps user or a specific webapp user : /etc/php/{version}/fpm/pool.d/{your-webapp-fpm}.conf.


问:
Incorrect Timezone in Google Apps Script
I have a Google Apps Script that is pulling a time from a given row on a spreadsheet and then transcribing it. However, the timezone is getting completely messed up in the process.

Relevant code (functional bits snipped out because I don't think they're relevant):

var timezone = "GMT+" + new Date().getTimezoneOffset()/60;
function dysfunction(row) {
  this.time = new Date (sheet.getRange(row,6).getValue());
  this.time.setFullYear(2020);
  this.timeString = Utilities.formatDate(this.time, timezone, "hh:mm a");
  Logger.log(timezone);
  Logger.log(this.time);
  Logger.log(this.timeString);
}```
</div>
</div>
</p>

<p>Stackdriver Log on executions:</p>

```May 4, 2020, 9:43:52 PM Info    GMT+6
May 4, 2020, 9:43:52 PM Info    Wed Dec 30 14:00:00 GMT-07:00 2020
May 4, 2020, 9:43:52 PM Info    03:00 AM
```

My correct timezone is in fact GMT-07:00, but for some reason, the script is detecting my timezone as GMT+6. I have set the correct timezone in the Project properties and even declared the timeZone as "America/Edmonton" in the manifest.

Where do I go next to figure out why this thing isn't interested in reading the timezone correctly?

答: Actually, the timezone shift can vary, according to the season: +0700 or +0600 are correct shifts at 2 different seazons for the same timezone.</p>

Body:
I have a Google Apps Script that is pulling a time from a given row on a spreadsheet and then transcribing it. However, the timezone is getting completely messed up in the process.

Relevant code (functional bits snipped out because I don't think they're relevant):

var timezone = "GMT+" + new Date().getTimezoneOffset()/60;
function dysfunction(row) {
  this.time = new Date (sheet.getRange(row,6).getValue());
  this.time.setFullYear(2020);
  this.timeString = Utilities.formatDate(this.time, timezone, "hh:mm a");
  Logger.log(timezone);
  Logger.log(this.time);
  Logger.log(this.timeString);
}

Stackdriver Log on executions:

May 4, 2020, 9:43:52 PM Info    GMT+6
May 4, 2020, 9:43:52 PM Info    Wed Dec 30 14:00:00 GMT-07:00 2020
May 4, 2020, 9:43:52 PM Info    03:00 AM

My correct timezone is in fact GMT-07:00, but for some reason, the script is detecting my timezone as GMT+6. I have set the correct timezone in the Project properties and even declared the timeZone as "America/Edmonton" in the manifest.

Where do I go next to figure out why this thing isn't interested in reading the timezone correctly?


问:
When I click on the button, the value of that button needs to add up to sum
I was trying to code a POS like system as a small project to learn with.
So currently I have two buttons "cola" and "fanta". The prices of those drinks are in an object.
As soon as I click on one button the price needs to be added to sum.
Well what the code is currently doing is to add up the prices of the same product.
So if I click three times in a row on "cola", which has a price of 3, I get 9 as sum. So far so good, but as soon as I click fanta, which has a price of 2, I get a sum of 2. But when I continue with the cola button it continues at 12 and so on.

Here is the code:

```<code>  const btnChoose = document.querySelectorAll(".btn");

  const drinks= {
    cola: 4,
    fanta: 3,
  };

  for (let i = 0; i < btnChoose.length; i++) {
    let sum = null;
    btnChoose[i].addEventListener("click", function () {
      let price = drinks[this.id];
      sum += price;
      console.log(typeof sum, sum);
    });
  }
</code>```

and here is the HTML:

```<code><!DOCTYPE html>
<html>
  <head>
    <title>POS</title>
  </head>

  <body>
    <button class="btn" id="cola">Cola</button>
    <button class="btn" id="fanta">Fanta</button>
    <script>
     ....
    </script>
  </body>
</html>
</code>```

答:
Try this:

let sum = 0;
const btnChoose = document.querySelectorAll(".btn");

const drinks = {
  cola: 4,
  fanta: 3,
};

for (let i = 0; i < btnChoose.length; i++) {
  btnChoose[i].addEventListener("click", function() {
    let price = drinks[this.id];
    sum += price;
    console.log(typeof sum, sum);
  });
}
```

Body:
I was trying to code a POS like system as a small project to learn with.
So currently I have two buttons "cola" and "fanta". The prices of those drinks are in an object.
As soon as I click on one button the price needs to be added to sum.
Well what the code is currently doing is to add up the prices of the same product.
So if I click three times in a row on "cola", which has a price of 3, I get 9 as sum. So far so good, but as soon as I click fanta, which has a price of 2, I get a sum of 2. But when I continue with the cola button it continues at 12 and so on.

Here is the code:

  const btnChoose = document.querySelectorAll(".btn");

  const drinks= {
    cola: 4,
    fanta: 3,
  };

  for (let i = 0; i < btnChoose.length; i++) {
    let sum = null;
    btnChoose[i].addEventListener("click", function () {
      let price = drinks[this.id];
      sum += price;
      console.log(typeof sum, sum);
    });
  }

and here is the HTML:

<!DOCTYPE html>

    <title>POS</title>

    <button class="btn" id="cola">Cola</button>
    <button class="btn" id="fanta">Fanta</button>


问:
Add multiple primary keys to a table
I have a table with a primary key available; I want to add another one in primary but can't add it.

SRNO
TRNDATE
RATE
AMT

1
08-02-2022
120
120

2
09-02-2022
170
170

3
10-02-2022
180
180

I want to add column Trndate to the primary key.

When I was try to add in primary following code

```<code>ALTER TABLE dbo.avgEnt
ADD CONSTRAINT PK_avgent PRIMARY KEY NONCLUSTERED (srno, trndate);
</code>```

I get an error:

Msg 1779, Level 16, State 0, Line 1

Table 'avgEnt' already has a primary key defined on it.

Msg 1750, Level 16, State 0, Line 1

Could not create constraint or index. See previous errors.

When I open the design of table and add primary key (SRNO, TRNDATE) then it works fine.

When I was trying to add by using the query, it does not work.

What happened when design windows save that time script i want.

My database version is SQL Server 2014.

答:
You can not alter the primary key. The only way is dropping it and then recreating it.

ALTER TABLE avgEnt DROP PRIMARY KEY, ADD PRIMARY KEY(srno,trndate);
```

https://www.db-fiddle.com/f/BQuEjw2pthMDb1z8NTdHv/0 check aswell

Title: Add multiple primary keys to a table

Body:
I have a table with a primary key available; I want to add another one in primary but can't add it.

SRNO
TRNDATE
RATE
AMT

1
08-02-2022
120
120

2
09-02-2022
170
170

3
10-02-2022
180
180

I want to add column Trndate to the primary key.

When I was try to add in primary following code

ALTER TABLE dbo.avgEnt
ADD CONSTRAINT PK_avgent PRIMARY KEY NONCLUSTERED (srno, trndate);

I get an error:

Msg 1779, Level 16, State 0, Line 1

Table 'avgEnt' already has a primary key defined on it.

Msg 1750, Level 16, State 0, Line 1

Could not create constraint or index. See previous errors.

When I open the design of table and add primary key (SRNO, TRNDATE) then it works fine.

When I was trying to add by using the query, it does not work.

What happened when design windows save that time script i want.

My database version is SQL Server 2014.

Body:
You can not alter the primary key. The only way is dropping it and then recreating it.

ALTER TABLE avgEnt DROP PRIMARY KEY, ADD PRIMARY KEY(srno,trndate);

https://www.db-fiddle.com/f/BQuEjw2pthMDb1z8NTdHv/0 check aswell


问:
Where are the best explanations of memory management for iPhone?
I am looking for good explanations out there. I have a 1000 pages book about objective-c, but unfortunately the part about memory management, retain counting, is described pretty bad and hard to understand.</p>

答:
This is one of the most concise good explanations I've found:

http://www.dikant.de/2007/08/23/cocoa-memory-management-101

OwnerDisplayName: Unknown Individual

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Adam Alexander


问:
Loader lock error with managed c++ dll, statically linked to a native c++ lib
I have a managed c++ dll with few managed classes that in turn call native c++ code in a library that I have statically linked to the dll. However, if I try to run RegAsm.exe on the dll, the tool correctly reports 'no types we registered' but then hangs. I'm very sure this is a loader lock problem and my dll hangs when RegAsm tries to load it. I'm using Visual Studio 2008, express edition.

What puzzles me that everything works fine when placing native code into the dll but not when statically linking it from the library. I'm aware that this post is similar to this question but I do not have DllMain in my dll, there is no risk of me running MSIL code from DllMain. Also, following the advice of setting /clr on individual files did not help.

Compiling the dll with /NOENTRY fixes the lock problem but causes the application to break with Type initializer for <Module> threw exception exception and is apparently only reccommended with .NET 2003.

I'm suspecting that initialization of static members could be a possible culprit but why would that be compiled to MSIL in my static lib is beyond me.

Just to clarify: although I have no need of running RegAsm.exe on the dll, I'm using it as a check for the loader lock problem. In reality I'm consuming the dll in a c# assembly that does implement few COM-visible classes - so I need to do COM registration on that one. At the end C# IDE crashes during registering for COM interop, reporting 'R6033 c++ runtime error: Attempt to use MSIL code from this assembly during native code initialization. This indicates a bug in your application. It is most likely the result of calling an MSIL-compiled (/clr) function from a native constructor or from DllMain.

Solved the issue but few things are unclear and I'm curious:

I noticed that two static variables were added to a header file in the statically-linked lib at the time things stopped to work, that looked like this:

```<code>// The whole header is forced to compile as native
#pragma managed(push, off)
....
static const std::locale commaSeparator(std::locale::classic(),
                                        new DecimalSeparator<char>(','));;
....
#pragma managed(pop)
</code>```

Moving the initialization to a .cpp file (and changing static to extern) fixes the loader lock. Could anyone point to why would the initializer get compiled to MSIL at all?

Before the fix, if I only #included the header file from the managed dll, things worked fine. But if I includeed the header AND also linked to the lib, things didn't work. Since the lib also uses the header internally, did I end up with two instances of the static variable? In any case, why a complaint about running MSIL code?

Although things work now, any insight would be welcome.

答:
Compiiler wraps user-defined DllMain with its own code, which is used to initialize runtime library and global variables (so that user-defined DllMain could run with global objects already created and could use standard library). Even if you don't have DllMain, there will be still compiler-generated one. With /NOENTRY you instruct linker to ignore it.

So, doing something in constructor of a static variable is effectively the same as doing that from DllMain, and it seems that is the case here.

Body:
I have a managed c++ dll with few managed classes that in turn call native c++ code in a library that I have statically linked to the dll. However, if I try to run RegAsm.exe on the dll, the tool correctly reports 'no types we registered' but then hangs. I'm very sure this is a loader lock problem and my dll hangs when RegAsm tries to load it. I'm using Visual Studio 2008, express edition.

What puzzles me that everything works fine when placing native code into the dll but not when statically linking it from the library. I'm aware that this post is similar to this question but I do not have DllMain in my dll, there is no risk of me running MSIL code from DllMain. Also, following the advice of setting /clr on individual files did not help.

Compiling the dll with /NOENTRY fixes the lock problem but causes the application to break with Type initializer for <Module> threw exception exception and is apparently only reccommended with .NET 2003.

I'm suspecting that initialization of static members could be a possible culprit but why would that be compiled to MSIL in my static lib is beyond me.

Just to clarify: although I have no need of running RegAsm.exe on the dll, I'm using it as a check for the loader lock problem. In reality I'm consuming the dll in a c# assembly that does implement few COM-visible classes - so I need to do COM registration on that one. At the end C# IDE crashes during registering for COM interop, reporting 'R6033 c++ runtime error: Attempt to use MSIL code from this assembly during native code initialization. This indicates a bug in your application. It is most likely the result of calling an MSIL-compiled (/clr) function from a native constructor or from DllMain.

Solved the issue but few things are unclear and I'm curious:

I noticed that two static variables were added to a header file in the statically-linked lib at the time things stopped to work, that looked like this:

// The whole header is forced to compile as native
#pragma managed(push, off)
....
static const std::locale commaSeparator(std::locale::classic(),
                                        new DecimalSeparator<char>(','));;
....
#pragma managed(pop)

Moving the initialization to a .cpp file (and changing static to extern) fixes the loader lock. Could anyone point to why would the initializer get compiled to MSIL at all?

Before the fix, if I only #included the header file from the managed dll, things worked fine. But if I includeed the header AND also linked to the lib, things didn't work. Since the lib also uses the header internally, did I end up with two instances of the static variable? In any case, why a complaint about running MSIL code?

Although things work now, any insight would be welcome.


问:
Get the full path of file name which is numbers only `highest number` , on main Folder or Subfolders?
I am using database software and export excel files from it and save on my desktop with name like ********.xls

***** means numbers only , for example   08134471.xls

23222578.xls

Those numbers on file name are random on count and length.

The path is constant D:\Users\Waleed\Desktop\    but, file name will change each time incrementally to higher number.

So, I need to open the workbook with highest number on the cited path.

In advance , gratefully for your help.

```<code>Sub Open_Numeric_File()

    Workbooks.Open "D:\Users\Waleed\Desktop\08134471.xls"

End Sub
</code>```

答:
You could do a list of all of the files in the folder, put them into a sheet / array and then sort them by the file name

There's a really good piece of code below that came from VBATips

```<code>Dim iRow

Sub ListFiles()
    iRow = 11
    Call ListMyFiles(Range("C7"), Range("C8"))
End Sub

Sub ListMyFiles(mySourcePath, IncludeSubfolders)
    Set MyObject = New Scripting.FileSystemObject
    Set mySource = MyObject.GetFolder(mySourcePath)
    On Error Resume Next
    For Each myFile In mySource.Files
        iCol = 2
        Cells(iRow, iCol).Value = myFile.Path
        iCol = iCol + 1
        Cells(iRow, iCol).Value = myFile.Name
        iCol = iCol + 1
        Cells(iRow, iCol).Value = myFile.Size
        iCol = iCol + 1
        Cells(iRow, iCol).Value = myFile.DateLastModified
        iRow = iRow + 1
    Next
    If IncludeSubfolders Then
        For Each mySubFolder In mySource.SubFolders
            Call ListMyFiles(mySubFolder.Path, True)
        Next
    End If
End Sub
</code>```

This will list all of the files in the folder into Excel, you could change the to an array

After this, just sort them on the myFile.DateLastModified

Sorry this isn't a full answer, had a minute free and thought this might help you

Partial Source:
http://excelexperts.com/VBA-Tips-List-Files-In-A-Folder

Body:
I am using database software and export excel files from it and save on my desktop with name like ********.xls

***** means numbers only , for example   08134471.xls

23222578.xls

Those numbers on file name are random on count and length.

The path is constant D:\Users\Waleed\Desktop\    but, file name will change each time incrementally to higher number.

So, I need to open the workbook with highest number on the cited path.

In advance , gratefully for your help.

Sub Open_Numeric_File()

    Workbooks.Open "D:\Users\Waleed\Desktop\08134471.xls"

End Sub

Body:
You could do a list of all of the files in the folder, put them into a sheet / array and then sort them by the file name

There's a really good piece of code below that came from VBATips

Dim iRow

Sub ListFiles()
    iRow = 11
    Call ListMyFiles(Range("C7"), Range("C8"))
End Sub

Sub ListMyFiles(mySourcePath, IncludeSubfolders)
    Set MyObject = New Scripting.FileSystemObject
    Set mySource = MyObject.GetFolder(mySourcePath)
    On Error Resume Next
    For Each myFile In mySource.Files
        iCol = 2
        Cells(iRow, iCol).Value = myFile.Path
        iCol = iCol + 1
        Cells(iRow, iCol).Value = myFile.Name
        iCol = iCol + 1
        Cells(iRow, iCol).Value = myFile.Size
        iCol = iCol + 1
        Cells(iRow, iCol).Value = myFile.DateLastModified
        iRow = iRow + 1
    Next
    If IncludeSubfolders Then
        For Each mySubFolder In mySource.SubFolders
            Call ListMyFiles(mySubFolder.Path, True)
        Next
    End If
End Sub

This will list all of the files in the folder into Excel, you could change the to an array

After this, just sort them on the myFile.DateLastModified

Sorry this isn't a full answer, had a minute free and thought this might help you

Partial Source:
http://excelexperts.com/VBA-Tips-List-Files-In-A-Folder


问:
Use function/parameters stored in columns
I'm not sure this question has already been asked, if so I didn't find it.

For a log project we used table to parametrize our data loading run and get track of their basic configuration.

On the specific side of the pull date we also wanna have the configuration in the table and so we putted three information in it: the base date / the range we use to calculate pull from and pull to timestamps.

My issue here is I wanna call the DATEADD() function using those columns as parameters but I don't know how to unstring those values as 'CURRENT_TIMESTAMP' will not work, just like DATEADD('year',...) will also raise an error cause the parameter should not be a string.

To summ up, from values ['CURRENT_TIMESTAMP', 'year', '-6'] in base I wanna create the call DATEADD(year, -6, CURRENT_TIMESTAMP)

Thanks

Screen of my table

答:
Make a case statement, and just match the two columns to there values. Remember case stop on the first in order match.

```<code>CASE
    WHEN col1 = ‘CURRENT_TOMESTAMP’’ AND col2 = ‘year’
        THEN DATEADD(year, col3, CURRENT_TIMESTAMP)
    WHEN col1 = ‘CURRENT_TOMESTAMP’’ AND col2 = ‘month’
        THEN DATEADD(month, col3, CURRENT_TIMESTAMP)
...
</code>```

Etc etc

Body:
Make a case statement, and just match the two columns to there values. Remember case stop on the first in order match.

CASE
    WHEN col1 = ‘CURRENT_TOMESTAMP’’ AND col2 = ‘year’
        THEN DATEADD(year, col3, CURRENT_TIMESTAMP)
    WHEN col1 = ‘CURRENT_TOMESTAMP’’ AND col2 = ‘month’
        THEN DATEADD(month, col3, CURRENT_TIMESTAMP)
...

Etc etc


问:
Why does redis return boolean for HGET in lua script?
This is my eval command

```<code>eval "local b = redis.call('hget', 'foo', 'baz'); if (type(b) == 'boolean') then return 'boolean' else return 'not a boolean' end" 0 "hello"
</code>```

This returns boolean. But if I return the value of b I get (nil). What is happening here?

答:
From https://gigacrunch.herokuapp.com/commands/hget

the value associated with field, or nil when field is not present in
the hash or key does not exist

There are some conversion rules between Redis an Lua values https://cndoc.github.io/redis-doc-cn/cn/commands/eval.html

Redis nil is converted to Lua false. So b is false. Hence type(b) is boolean so you return a string 'boolean'.

If you return b you return false. Lua false is converted to Redis nil.

Body:
This is my eval command

eval "local b = redis.call('hget', 'foo', 'baz'); if (type(b) == 'boolean') then return 'boolean' else return 'not a boolean' end" 0 "hello"

This returns boolean. But if I return the value of b I get (nil). What is happening here?


问:
BigQuery ARRAY_TO_STRING based on condition in non-array field
I have a table that I query like this...

```<code>select *
from table
where productId = 'abc123'
</code>```

Which returns 2 rows (even though the productId is unique) because one of the columns (orderName) is an Array...

```<code>**productId, productName, created, featureCount, orderName**
abc123, someProductName, 2020-01-01, 12, someOrderName
      ,                ,           ,   , someOtherOrderName
</code>```

I'm not sure whether the missing values in the 2nd row are empty strings or nulls because of the way the orderName array expands my search results but I want to now run a query like this...

```<code>select productName, ARRAY_TO_STRING(orderName,'-')
from table
where productId = 'abc123'
and ifnull(featureCount,0) > 0
</code>```

But this query returns...

```<code>someProductName, someOrderName-someOtherOrderName
</code>```

i.e. both array values came back even though I specified a condition of featureCount>0.

I'm sure I'm missing something very basic about how Arrays function in BigQuery but from Google's ARRAY_TO_STRING documentation I don't see any way to add a condition to the extracting of ARRAY values. Appreciate any thoughts on the best way to go about this.

答:
For what I understand, this is because you are just querying one row of data which have a column as ARRAY<STRING>. As you are using ARRAY_TO_STRINGS it will only accept ARRAY<STRING> values you will see all array values fit into just one cell.

So, when you run your script, your output will fit your criteria and return the columns with arrays with additional rows for visibility.

The visualization on the UI should look like your mention in your question:

Row
productId
productName
created
featureCount
orderName

1
abc123
someProductName
2020-01-01
12
someOrderName

someOtherOrderName

Note: On bigquery this additional row is gray out (   ) and Its part of row 1 but it shows as an additional row for visibility. So this output only have 1 row in the table.

And the visualization on a JSON will be:

```<code>[
  {
    "productId": "abc123",
    "productName": "someProductName",
    "created": "2020-01-01",
    "featureCount": "12",
    "orderName": [
      "someOrderName",
      "someOtherOrderName"
    ]
  }
]
</code>```

I don't think there is specific documentation info about how you visualize arrays on UI but I can share the docs that talks about how to flattening your rows outputs into a single row line, check:

Working with Arrays

Flattening Arrays

I use the following to replicate your issue:

```<code>CREATE OR REPLACE TABLE `project-id.dataset.working_table` (
 productId STRING,
 productName STRING,
 created STRING,
 featureCount STRING,
 orderName ARRAY<STRING>
);

insert into `project-id.dataset.working_table` (productId,productName,created,featureCount,orderName)
values ('abc123','someProductName','2020-01-01','12',['someOrderName','someOtherOrderName']);

insert into `project-id.dataset.working_table` (productId,productName,created,featureCount,orderName)
values ('abc123X','someProductNameX','2020-01-02','15',['someOrderName','someOtherOrderName','someData']);

</code>```

output

Row
productId
productName
created
featureCount
orderName

1
abc123
someProductName
2020-01-01
12
someOrderName

someOtherOrderName

2
abc123X
someProductNameX
2020-01-02
15
someOrderName

someOtherOrderName

someData

Note: Table contains 2 rows.

Body:
I have a table that I query like this...

select *
from table
where productId = 'abc123'

Which returns 2 rows (even though the productId is unique) because one of the columns (orderName) is an Array...

**productId, productName, created, featureCount, orderName**
abc123, someProductName, 2020-01-01, 12, someOrderName
      ,                ,           ,   , someOtherOrderName

I'm not sure whether the missing values in the 2nd row are empty strings or nulls because of the way the orderName array expands my search results but I want to now run a query like this...

select productName, ARRAY_TO_STRING(orderName,'-')
from table
where productId = 'abc123'
and ifnull(featureCount,0) > 0

But this query returns...

someProductName, someOrderName-someOtherOrderName

i.e. both array values came back even though I specified a condition of featureCount>0.

I'm sure I'm missing something very basic about how Arrays function in BigQuery but from Google's ARRAY_TO_STRING documentation I don't see any way to add a condition to the extracting of ARRAY values. Appreciate any thoughts on the best way to go about this.

Body:
For what I understand, this is because you are just querying one row of data which have a column as ARRAY<STRING>. As you are using ARRAY_TO_STRINGS it will only accept ARRAY<STRING> values you will see all array values fit into just one cell.

So, when you run your script, your output will fit your criteria and return the columns with arrays with additional rows for visibility.

The visualization on the UI should look like your mention in your question:

Row
productId
productName
created
featureCount
orderName

1
abc123
someProductName
2020-01-01
12
someOrderName

someOtherOrderName

Note: On bigquery this additional row is gray out (   ) and Its part of row 1 but it shows as an additional row for visibility. So this output only have 1 row in the table.

And the visualization on a JSON will be:

[
  {
    "productId": "abc123",
    "productName": "someProductName",
    "created": "2020-01-01",
    "featureCount": "12",
    "orderName": [
      "someOrderName",
      "someOtherOrderName"
    ]
  }
]

I don't think there is specific documentation info about how you visualize arrays on UI but I can share the docs that talks about how to flattening your rows outputs into a single row line, check:

Working with Arrays

Flattening Arrays

I use the following to replicate your issue:

CREATE OR REPLACE TABLE `project-id.dataset.working_table` (
 productId STRING,
 productName STRING,
 created STRING,
 featureCount STRING,
 orderName ARRAY<STRING>
);

insert into `project-id.dataset.working_table` (productId,productName,created,featureCount,orderName)
values ('abc123','someProductName','2020-01-01','12',['someOrderName','someOtherOrderName']);

insert into `project-id.dataset.working_table` (productId,productName,created,featureCount,orderName)
values ('abc123X','someProductNameX','2020-01-02','15',['someOrderName','someOtherOrderName','someData']);

output

Row
productId
productName
created
featureCount
orderName

1
abc123
someProductName
2020-01-01
12
someOrderName

someOtherOrderName

2
abc123X
someProductNameX
2020-01-02
15
someOrderName

someOtherOrderName

someData

Note: Table contains 2 rows.