问:
Create an array of object properties for each item that has the same key
I'm merging two objects together to create a filter object. However I want to group the merged objects property values where the keys are the same.

So...

```<code>[{category: 'furniture'}, {category: 'mirrors'}, {availability: 'in_stock'}]
</code>```

becomes

```<code>[{category: ['furniture', 'mirrors']}, {availability: 'in_stock'}]
</code>```

any ideas?

答:
With lodash you merge the entire array to a new object by spreading into _.mergeWith(). The customizer should use empty arrays as default values for the current values, and concat the values. Use _.map() to convert back to an array.

const data = [{category: 'furniture'}, {category: 'mirrors'}, {availability: 'in_stock'}];

const result = _.map(
  _.mergeWith({}, ...data, (a = [], b = [], key) => a.concat(b)),
  (val, key) => ({ [key]: val })
)

console.log(result)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script></code>```

Using vanilla JS, reduce the array to a Map using the objects' keys as the keys of the Map, with an empty array as the value, and push the objects' values into the arrays. Use Array.from() to convert the Map to an array.

const data = [{category: 'furniture'}, {category: 'mirrors'}, {availability: 'in_stock'}];

const result = Array.from(
  data.reduce((acc, obj) => {
    Object.entries(obj)
      .forEach(([key, val]) => {
        if(!acc.has(key)) acc.set(key, [])

        acc.get(key).push(val)
      })

    return acc
  }, new Map()),
  ([key, val]) => ({ [key]: val })
)

console.log(result)```

Body:
I'm merging two objects together to create a filter object. However I want to group the merged objects property values where the keys are the same.

So...

[{category: 'furniture'}, {category: 'mirrors'}, {availability: 'in_stock'}]

becomes

[{category: ['furniture', 'mirrors']}, {availability: 'in_stock'}]

any ideas?

Body:
With lodash you merge the entire array to a new object by spreading into _.mergeWith(). The customizer should use empty arrays as default values for the current values, and concat the values. Use _.map() to convert back to an array.

const data = [{category: 'furniture'}, {category: 'mirrors'}, {availability: 'in_stock'}];

const result = _.map(
  _.mergeWith({}, ...data, (a = [], b = [], key) => a.concat(b)),
  (val, key) => ({ [key]: val })
)

console.log(result)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Using vanilla JS, reduce the array to a Map using the objects' keys as the keys of the Map, with an empty array as the value, and push the objects' values into the arrays. Use Array.from() to convert the Map to an array.

const data = [{category: 'furniture'}, {category: 'mirrors'}, {availability: 'in_stock'}];

const result = Array.from(
  data.reduce((acc, obj) => {
    Object.entries(obj)
      .forEach(([key, val]) => {
        if(!acc.has(key)) acc.set(key, [])

        acc.get(key).push(val)
      })

    return acc
  }, new Map()),
  ([key, val]) => ({ [key]: val })
)

console.log(result)


来源: stackexchange

问:
PHP access to iTunes tags in an RSS feed
I need to get access to the iTunes tags in an RSS feed using PHP. I've used simplepie before for podcast feeds, but I'm not sure how to get the iTunes tags using it. Is there a way to use simplepie to do it or is there a better way?

Okay I tried Simple XML.

All this (the code below) seems to work

```<code>$feed = simplexml_load_file('http://sbhosting.com/feed/');
$channel = $feed->channel;
$channel_itunes = $channel->children('http://www.itunes.com/dtds/podcast-1.0.dtd');
$summary = $channel_itunes->summary;
$subtitle = $channel_itunes->subtitle;
$category = $channel_itunes->category;
$owner = $channel_itunes->owner->name;
</code>```

Now I need to get the itunes categories. The seem to be represented in several ways.
In this case I get the follow XML:

```<code><itunes:category text="Technology"/>
<itunes:category text="Technology">
  <itunes:category text="Software How-To"/>
</itunes:category>
</code>```

I would expect to be able to get the category with something like this:

```<code>$category_text = $channel_itunes->category['text'];
</code>```

But that does not seem to work.

I've seen other ways to represent the category that I really don't know who to get.

For example:

Technology
  Business
  Education

Is this a media thing or a itunes thing or both?

Thanks For Your Help.
G

答:
```<code><?php echo $feed_item->children('itunes', true)->image->attributes()->href;?>
</code>```

OwnerDisplayName: hap

ContentLicense: CC BY-SA 2.5

Body:
I need to get access to the iTunes tags in an RSS feed using PHP. I've used simplepie before for podcast feeds, but I'm not sure how to get the iTunes tags using it. Is there a way to use simplepie to do it or is there a better way?

Okay I tried Simple XML.

All this (the code below) seems to work

$feed = simplexml_load_file('http://sbhosting.com/feed/');
$channel = $feed->channel;
$channel_itunes = $channel->children('http://www.itunes.com/dtds/podcast-1.0.dtd');
$summary = $channel_itunes->summary;
$subtitle = $channel_itunes->subtitle;
$category = $channel_itunes->category;
$owner = $channel_itunes->owner->name;

Now I need to get the itunes categories. The seem to be represented in several ways.
In this case I get the follow XML:

<itunes:category text="Technology"/>
<itunes:category text="Technology">
  <itunes:category text="Software How-To"/>
</itunes:category>

I would expect to be able to get the category with something like this:

$category_text = $channel_itunes->category['text'];

But that does not seem to work.

I've seen other ways to represent the category that I really don't know who to get.

For example:

Technology
  Business
  Education

Is this a media thing or a itunes thing or both?

Thanks For Your Help.
G

LastEditorDisplayName: hap

ContentLicense: CC BY-SA 4.0


问:
Will events be emitted / captured while awaiting for a promise?
I'm kinda new to nodejs and I'm familiarizing myself with the event loop, queue, etc.

I was wondering what happens while I'm awaiting for a promise to resolve, regarding events. Will events be emitted while awaiting? (I'm subscribed to a message broker, getting a message triggers an event). Will the callbacks that are called on event be queued in the event queue?

I know that the callback won't be executed until the promise resolves but will the events be triggered?

Thanks ^^

答: When events are registered, their emission is simply controlled by whatever makes them emitted. However, the callback registered to handle the event would go first into the event queue, and their queue position is not determined by what other promises are awaiting resolution, rather the position is determined by whatever promises have been resolved or rejected and whatever events have been emitted ahead of the presently emitted event, and they will all wait for the call stack to be cleared before they are invoked in turn. The event loop is the process of doing that, that is, it executes tasks from the event queue only when the call stack is empty i.e. there is no ongoing task.</p>


问:
How to automatically update R to the latest patched version?
Is there any way to automatically update R on Mac OS X to the latest patched version (R-Patched) on a daily basis or some predetermined intervals?</p>

答:
My impression is that compiling from source is the most (only?) reliable way to get the most recent patched version, but I could be wrong about this. A simple shell script to download the latest patched version and recompile would be:

```<code>curl -o /tmp/R-patched.tar.gz ftp://ftp.stat.math.ethz.ch/Software/R/R-patched.tar.gz
tar xzvf /tmp/R-patched.tar.gz
cd /tmp/R-patched
./configure
make
cp bin/R <old_R_binary_location>
</code>```

You could then use crontab to run this at regular intervals. I don't find the crontab man page to be very helpful, so I always end up referring back to guides such as this one.

ContentLicense: CC BY-SA 3.0

Body:
My impression is that compiling from source is the most (only?) reliable way to get the most recent patched version, but I could be wrong about this. A simple shell script to download the latest patched version and recompile would be:

curl -o /tmp/R-patched.tar.gz ftp://ftp.stat.math.ethz.ch/Software/R/R-patched.tar.gz
tar xzvf /tmp/R-patched.tar.gz
cd /tmp/R-patched
./configure
make
cp bin/R <old_R_binary_location>

You could then use crontab to run this at regular intervals. I don't find the crontab man page to be very helpful, so I always end up referring back to guides such as this one.

OwnerDisplayName: bnaul


问:
Mongoose saves empty object
After a post request, moongoose does save the document but it is empty.

I do have the model for it and the collection exists.

index.js

```<code>const BlogPost = require("./models/BlogPost.js");
</code>```

BlogPost.js:

```<code>const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const BlogPostSchema = new Schema({
    title: String,
    body: String,
});

const BlogPost = mongoose.model("BlogPost", BlogPostSchema);
module.exports = BlogPost;
</code>```

create method:

```<code>app.post("/posts/store", (req, res) => {
    BlogPost.create(req.body, (error, blogpost) => {
        console.log(req.body);
        res.redirect("/");
    });
});
</code>```

req.body console.log result

```<code>{ '”title”': 'aaaa', '”body”': 'bbbbbbbbbb' }
</code>```

So, when I console.log req.body I do get the expected data, however blogpost is empty and is being saved as such. What am I missing?

答:
You can create async await function for sending data to mongoDb
Like this:

```<code>app.post("/posts/store", async (req, res) => {
const { title, body } = req.body;
const blog = await BlogPost.create({
    title,
    body,
});

res.status(201).json({
      status: 'success',
      data: {
          blog,
      }
   })
});
</code>```

after than if everything ok add delete res.status(201).json and add res.redirect("/");

If you don't use Postman you can test with curl

```<code>curl -X POST -H "Content-Type: application/json" \-d '{"title":
   "titles", "body": "bodys"}' \https://localhost:<YOUR_PORT>
</code>```

Title: Mongoose saves empty object

Body:
After a post request, moongoose does save the document but it is empty.

I do have the model for it and the collection exists.

index.js

const BlogPost = require("./models/BlogPost.js");

BlogPost.js:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const BlogPostSchema = new Schema({
    title: String,
    body: String,
});

const BlogPost = mongoose.model("BlogPost", BlogPostSchema);
module.exports = BlogPost;

create method:

app.post("/posts/store", (req, res) => {
    BlogPost.create(req.body, (error, blogpost) => {
        console.log(req.body);
        res.redirect("/");
    });
});

req.body console.log result

{ '”title”': 'aaaa', '”body”': 'bbbbbbbbbb' }

So, when I console.log req.body I do get the expected data, however blogpost is empty and is being saved as such. What am I missing?

Body:
You can create async await function for sending data to mongoDb
Like this:

app.post("/posts/store", async (req, res) => {
const { title, body } = req.body;
const blog = await BlogPost.create({
    title,
    body,
});

res.status(201).json({
      status: 'success',
      data: {
          blog,
      }
   })
});

after than if everything ok add delete res.status(201).json and add res.redirect("/");

If you don't use Postman you can test with curl

curl -X POST -H "Content-Type: application/json" \-d '{"title":
   "titles", "body": "bodys"}' \https://localhost:<YOUR_PORT>


问:
python regex text extraction
the text input is something like this
West Team 4, Eastern 3\n

-------Update--------

the input is a txt file containing team name and scores like a football game
the whole text file will be something like this, two names and scores:

```<code>West Team 4, Eastern 5
Nott Team 2, Eastern 3
West wood 1, Eathan 2
West Team 4, Eas 5
</code>```

I am using with open to read file line by line therefore there will be \n at the end of the line.

I would like to extract this line of text in to something like:

```<code>['West Team', 'Eastern']
</code>```

What I currently have in mind is to use regex

```<code>result = re.sub("[\n^\s$\d]", "", text).split(",")
</code>```

this code results in this:

```<code>['WestTeam','Eastern']
</code>```

I'm sure that my regex is not correct. I want to remove '\n' and any number including the space in front of the number but not the space in the middle of the name.

Open to any suggestion that to achieve this result, doesn't necessarily use regex.

答:
Actually re.findall might work well here:

inp = "West Team 4, Eastern 3\n"
matches = re.findall(r'(\w+(?: \w+)*) \d+', inp)
print(matches)  # ['West Team', 'Eastern']
```
<p>The split version, using <code>re.split</code>:</p>
<pre class="lang-py prettyprint-override"><code>inp = "West Team 4, Eastern 3\n"
matches = [x for x in re.split(r'\s+\d+\s*,?\s*', inp) if x != '']
print(matches)  # ['West Team', 'Eastern']
</code>```

Title: python regex text extraction

Body:
the text input is something like this
West Team 4, Eastern 3\n

-------Update--------

the input is a txt file containing team name and scores like a football game
the whole text file will be something like this, two names and scores:

West Team 4, Eastern 5
Nott Team 2, Eastern 3
West wood 1, Eathan 2
West Team 4, Eas 5

I am using with open to read file line by line therefore there will be \n at the end of the line.

I would like to extract this line of text in to something like:

['West Team', 'Eastern']

What I currently have in mind is to use regex

result = re.sub("[\n^\s$\d]", "", text).split(",")

this code results in this:

['WestTeam','Eastern']

I'm sure that my regex is not correct. I want to remove '\n' and any number including the space in front of the number but not the space in the middle of the name.

Open to any suggestion that to achieve this result, doesn't necessarily use regex.

Body:
Actually re.findall might work well here:

inp = "West Team 4, Eastern 3\n"
matches = re.findall(r'(\w+(?: \w+)*) \d+', inp)
print(matches)  # ['West Team', 'Eastern']

The split version, using re.split:

inp = "West Team 4, Eastern 3\n"
matches = [x for x in re.split(r'\s+\d+\s*,?\s*', inp) if x != '']
print(matches)  # ['West Team', 'Eastern']


问:
Target of URI doesn't exist: 'firebase_options.dart'. Try creating the file referenced by the URI, or Try using a URI for a file that does exist
please how can i solve this problem
Target of URI doesn't exist: 'firebase_options.dart'.
Try creating the file referenced by the URI, or Try using a URI for a file that does exist

I try this flutter clean

flutter pub get

restart

答:
Usually, the firebase_options.dart file is generated through flutterfire configure command.

Double check that you generate the file properly with the Flutterfire CLI and that you import it with the right path in your main.dart (or the file that require it)


问:
Need to add similar customer into array after performing groupBy but with a limit per customer
I had asked a similar question yesterday and got a correct answer, but today I faced more issues.
So here is the new problem statement.
I am fetching customer contacts from salesforce which are coming as an array of objects as shown below.

Input Payload:

```<code>[
    {
        "customerID": 1,
        "customerName": "Jonhn1"
    },
    {
        "customerID": 1,
        "customerName": "Jonhn2"
    },
    {
        "customerID": 1,
        "customerName": "Jonhn3"
    },
    {
        "customerID": 1,
        "customerName": "Jonhn4"
    },
    {
        "customerID": 1,
        "customerName": "Jonhn5"
    },
    {
        "customerID": 2,
        "customerName": "Jonhn6"
    },
    {
        "customerID": 2,
        "customerName": "Jonhn7"
    },
    {
        "customerID": 2,
        "customerName": "Jonhn8"
    },
    {
        "customerID": 3,
        "customerName": "Jonhn9"
    },
    {
        "customerID": 3,
        "customerName": "Jonhn10"
    },
    {
        "customerID": 3,
        "customerName": "Jonhn11"
    },
    {
        "customerID": 4,
        "customerName": "Jonhn12"
    },
    {
        "customerID": 4,
        "customerName": "Jonhn13"
    },
    {
        "customerID": 5,
        "customerName": "Jonhn14"
    },
    {
        "customerID": 5,
        "customerName": "Jonhn15"
    },
    {
        "customerID": 5,
        "customerName": "Jonhn16"
    },
    {
        "customerID": 6,
        "customerName": "Jonhn17"
    },
    {
        "customerID": 7,
        "customerName": "Jonhn17"
    }
]
</code>```

I need the output to be an array of arrays, each sub-array should have all the customer details of at most three different customers.
I got the solution till the above statement as show below

```<code>%dw 2.0
output application/json
import * from dw::core::Arrays
---
payload groupBy $.customerID pluck $ divideBy 3 map((flatten($)))
</code>```

Now the main problem,
We have to put a limit on the number of customers in an array. For example in the given input payload customer with id "1" came more than 4 (four) times, then this customer should be in a different array ( means a separate array of customer "1" e.g an array for five records) this can happen to any other customer as well.

So we have to check if a customer is repeating more than 4 times then make a separate array for that type of customer else combine it with other customers as required earlier

Expected output:

```<code>[
    [
        {
            "customerID": 1,
            "customerName": "Jonhn1"
        },
        {
            "customerID": 1,
            "customerName": "Jonhn2"
        },
        {
            "customerID": 1,
            "customerName": "Jonhn3"
        },
        {
            "customerID": 1,
            "customerName": "Jonhn4"
        },
        {
            "customerID": 1,
            "customerName": "Jonhn5"
        }
    ],
    [
        {
            "customerID": 2,
            "customerName": "Jonhn6"
        },
        {
            "customerID": 2,
            "customerName": "Jonhn7"
        },
        {
            "customerID": 2,
            "customerName": "Jonhn8"
        },
        {
            "customerID": 3,
            "customerName": "Jonhn9"
        },
        {
            "customerID": 3,
            "customerName": "Jonhn10"
        },
        {
            "customerID": 3,
            "customerName": "Jonhn11"
        },
        {
            "customerID": 4,
            "customerName": "Jonhn12"
        },
        {
            "customerID": 4,
            "customerName": "Jonhn13"
        }
    ],
    [
        {
            "customerID": 5,
            "customerName": "Jonhn14"
        },
        {
            "customerID": 5,
            "customerName": "Jonhn15"
        },
        {
            "customerID": 5,
            "customerName": "Jonhn16"
        },
        {
            "customerID": 6,
            "customerName": "Jonhn17"
        },
        {
            "customerID": 7,
            "customerName": "Jonhn18"
        }
    ]
]
</code>```

答:
Please verify all the scenarios and correct me if anything I missed. I just seggregated based on the size of individual array.

If size[array] > 4 then divideBy 5 else divideBy 3.

distinctBy to maintain a single payload as I have used payload in if and else condition

Note -> Order will not be maintained as you mentioned for rainy scenarios.

```<code>%dw 2.0
output application/json
import * from dw::core::Arrays
var a = payload groupBy $.customerID pluck $
---
flatten(a map
    (if (sizeOf($)>4)
            $ divideBy sizeOf($) map(flatten($))
            else
    (a filter (sizeOf ($)< 5) divideBy 3 map (flatten ($)))
    ) distinctBy $)
</code>```

Output

```<code>[
  [
    {
      "customerID": 1,
      "customerName": "Jonhn1"
    },
    {
      "customerID": 1,
      "customerName": "Jonhn2"
    },
    {
      "customerID": 1,
      "customerName": "Jonhn3"
    },
    {
      "customerID": 1,
      "customerName": "Jonhn4"
    },
    {
      "customerID": 1,
      "customerName": "Jonhn5"
    }
  ],
  [
    {
      "customerID": 2,
      "customerName": "Jonhn6"
    },
    {
      "customerID": 2,
      "customerName": "Jonhn7"
    },
    {
      "customerID": 2,
      "customerName": "Jonhn8"
    },
    {
      "customerID": 2,
      "customerName": "Jonhn9"
    },
    {
      "customerID": 3,
      "customerName": "Jonhn10"
    },
    {
      "customerID": 3,
      "customerName": "Jonhn11"
    },
    {
      "customerID": 4,
      "customerName": "Jonhn12"
    },
    {
      "customerID": 4,
      "customerName": "Jonhn13"
    }
  ],
  [
    {
      "customerID": 5,
      "customerName": "Jonhn14"
    },
    {
      "customerID": 5,
      "customerName": "Jonhn15"
    },
    {
      "customerID": 5,
      "customerName": "Jonhn16"
    },
    {
      "customerID": 6,
      "customerName": "Jonhn17"
    },
    {
      "customerID": 7,
      "customerName": "Jonhn17"
    }
  ]
]
</code>```

Body:
I had asked a similar question yesterday and got a correct answer, but today I faced more issues.
So here is the new problem statement.
I am fetching customer contacts from salesforce which are coming as an array of objects as shown below.

Input Payload:

[
    {
        "customerID": 1,
        "customerName": "Jonhn1"
    },
    {
        "customerID": 1,
        "customerName": "Jonhn2"
    },
    {
        "customerID": 1,
        "customerName": "Jonhn3"
    },
    {
        "customerID": 1,
        "customerName": "Jonhn4"
    },
    {
        "customerID": 1,
        "customerName": "Jonhn5"
    },
    {
        "customerID": 2,
        "customerName": "Jonhn6"
    },
    {
        "customerID": 2,
        "customerName": "Jonhn7"
    },
    {
        "customerID": 2,
        "customerName": "Jonhn8"
    },
    {
        "customerID": 3,
        "customerName": "Jonhn9"
    },
    {
        "customerID": 3,
        "customerName": "Jonhn10"
    },
    {
        "customerID": 3,
        "customerName": "Jonhn11"
    },
    {
        "customerID": 4,
        "customerName": "Jonhn12"
    },
    {
        "customerID": 4,
        "customerName": "Jonhn13"
    },
    {
        "customerID": 5,
        "customerName": "Jonhn14"
    },
    {
        "customerID": 5,
        "customerName": "Jonhn15"
    },
    {
        "customerID": 5,
        "customerName": "Jonhn16"
    },
    {
        "customerID": 6,
        "customerName": "Jonhn17"
    },
    {
        "customerID": 7,
        "customerName": "Jonhn17"
    }
]

I need the output to be an array of arrays, each sub-array should have all the customer details of at most three different customers.
I got the solution till the above statement as show below

%dw 2.0
output application/json
import * from dw::core::Arrays
---
payload groupBy $.customerID pluck $ divideBy 3 map((flatten($)))

Now the main problem,
We have to put a limit on the number of customers in an array. For example in the given input payload customer with id "1" came more than 4 (four) times, then this customer should be in a different array ( means a separate array of customer "1" e.g an array for five records) this can happen to any other customer as well.

So we have to check if a customer is repeating more than 4 times then make a separate array for that type of customer else combine it with other customers as required earlier

Expected output:

[
    [
        {
            "customerID": 1,
            "customerName": "Jonhn1"
        },
        {
            "customerID": 1,
            "customerName": "Jonhn2"
        },
        {
            "customerID": 1,
            "customerName": "Jonhn3"
        },
        {
            "customerID": 1,
            "customerName": "Jonhn4"
        },
        {
            "customerID": 1,
            "customerName": "Jonhn5"
        }
    ],
    [
        {
            "customerID": 2,
            "customerName": "Jonhn6"
        },
        {
            "customerID": 2,
            "customerName": "Jonhn7"
        },
        {
            "customerID": 2,
            "customerName": "Jonhn8"
        },
        {
            "customerID": 3,
            "customerName": "Jonhn9"
        },
        {
            "customerID": 3,
            "customerName": "Jonhn10"
        },
        {
            "customerID": 3,
            "customerName": "Jonhn11"
        },
        {
            "customerID": 4,
            "customerName": "Jonhn12"
        },
        {
            "customerID": 4,
            "customerName": "Jonhn13"
        }
    ],
    [
        {
            "customerID": 5,
            "customerName": "Jonhn14"
        },
        {
            "customerID": 5,
            "customerName": "Jonhn15"
        },
        {
            "customerID": 5,
            "customerName": "Jonhn16"
        },
        {
            "customerID": 6,
            "customerName": "Jonhn17"
        },
        {
            "customerID": 7,
            "customerName": "Jonhn18"
        }
    ]
]

Body:
Please verify all the scenarios and correct me if anything I missed. I just seggregated based on the size of individual array.

If size[array] > 4 then divideBy 5 else divideBy 3.

distinctBy to maintain a single payload as I have used payload in if and else condition

Note -> Order will not be maintained as you mentioned for rainy scenarios.

%dw 2.0
output application/json
import * from dw::core::Arrays
var a = payload groupBy $.customerID pluck $
---
flatten(a map
    (if (sizeOf($)>4)
            $ divideBy sizeOf($) map(flatten($))
            else
    (a filter (sizeOf ($)< 5) divideBy 3 map (flatten ($)))
    ) distinctBy $)

Output

[
  [
    {
      "customerID": 1,
      "customerName": "Jonhn1"
    },
    {
      "customerID": 1,
      "customerName": "Jonhn2"
    },
    {
      "customerID": 1,
      "customerName": "Jonhn3"
    },
    {
      "customerID": 1,
      "customerName": "Jonhn4"
    },
    {
      "customerID": 1,
      "customerName": "Jonhn5"
    }
  ],
  [
    {
      "customerID": 2,
      "customerName": "Jonhn6"
    },
    {
      "customerID": 2,
      "customerName": "Jonhn7"
    },
    {
      "customerID": 2,
      "customerName": "Jonhn8"
    },
    {
      "customerID": 2,
      "customerName": "Jonhn9"
    },
    {
      "customerID": 3,
      "customerName": "Jonhn10"
    },
    {
      "customerID": 3,
      "customerName": "Jonhn11"
    },
    {
      "customerID": 4,
      "customerName": "Jonhn12"
    },
    {
      "customerID": 4,
      "customerName": "Jonhn13"
    }
  ],
  [
    {
      "customerID": 5,
      "customerName": "Jonhn14"
    },
    {
      "customerID": 5,
      "customerName": "Jonhn15"
    },
    {
      "customerID": 5,
      "customerName": "Jonhn16"
    },
    {
      "customerID": 6,
      "customerName": "Jonhn17"
    },
    {
      "customerID": 7,
      "customerName": "Jonhn17"
    }
  ]
]


问:
to get a list of bools, .contain()
how do i do a list for bools in javascript. im doing a validation so i can have a list of bools and at the end i want to check that list if it contains any errors. im not sure how to add to the varable validations_errors (like a list). Plus i dont know how i can check if that list contains any true values.

what i got so far is this

```<code>var validation_errors;

            if (!validateForm($(this))) {
                validation_errors = false; //here i want to add the it to a list
                var $input_container = $(this).parents('.input');
                $input_container.removeClass('success').addClass('error');
            }

    //this is something what i want to do like (this code is c# based)
    if (validation_errors.contains(true)){
    // do some actions
    }
</code>```

EDIT

list of bools = list of true & false

答:
```<code>var validation_errors = [];
.
.
.

    if (error) validation_errors.push(true)

if (validation_errors.length > 0) ...
</code>```

If you want to store true or false so you can use indexOf to find which test failed:

```<code>if (validateForm($(this))) validation_errors.push(false);
else {
  validation_errors.push(true);
  var $input_container = $(this).parents('.input');
  $input_container.removeClass('success').addClass('error');
}

var notvalid = validation_errors.indexOf(true);
if (notValid !=-1) alert("The form #"+(notvalid+1)+" failed")
</code>```

Title: to get a list of bools, .contain()

Body:
how do i do a list for bools in javascript. im doing a validation so i can have a list of bools and at the end i want to check that list if it contains any errors. im not sure how to add to the varable validations_errors (like a list). Plus i dont know how i can check if that list contains any true values.

what i got so far is this

var validation_errors;

            if (!validateForm($(this))) {
                validation_errors = false; //here i want to add the it to a list
                var $input_container = $(this).parents('.input');
                $input_container.removeClass('success').addClass('error');
            }

    //this is something what i want to do like (this code is c# based)
    if (validation_errors.contains(true)){
    // do some actions
    }

EDIT

list of bools = list of true & false

Body:
var validation_errors = [];
.
.
.

    if (error) validation_errors.push(true)

if (validation_errors.length > 0) ...

If you want to store true or false so you can use indexOf to find which test failed:

if (validateForm($(this))) validation_errors.push(false);
else {
  validation_errors.push(true);
  var $input_container = $(this).parents('.input');
  $input_container.removeClass('success').addClass('error');
}

var notvalid = validation_errors.indexOf(true);
if (notValid !=-1) alert("The form #"+(notvalid+1)+" failed")


问:
How do I programmatically set the background color gradient on a Custom Title Bar?
There are many tutorials out there and questions on SO that implement custom title bars.  However, in my custom title bar I have a custom gradient for the background and I would like to know how to set it dynamically in my code.

Here is where my custom title bar gets called:

```<code>requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.foo_layout);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title_bar);
</code>```

And this is my custom_title_bar:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@layout/custom_title_bar_background_colors">
<ImageView
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:src="@drawable/title_bar_logo"
              android:gravity="center_horizontal"
              android:paddingTop="0dip"/>

</LinearLayout>
</code>```

As you can see, the background on the linear layout is defined by this guy:

```<code><shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
    android:startColor="#616261"
    android:endColor="#131313"
    android:angle="270"
 />
<corners android:radius="0dp" />
</shape>
</code>```

What I would like to do is set those gradient colors dynamically in my code.  I do not want to hard code them in my XML file like they currently are.

I am open to all ideas if you have a better way of setting a background gradient.

Thank you in advance!!

答:
Answer with gradient generation is correct, but it will not work if you just set background to MaterialButton. For MaterialButton you have to nullable default backgroundTint:

```<code>app:backgroundTint="@null"
</code>```

After that solution will work. (link to source: https://github.com/material-components/material-components-android/issues/889#issuecomment-621194246)

Body:
There are many tutorials out there and questions on SO that implement custom title bars.  However, in my custom title bar I have a custom gradient for the background and I would like to know how to set it dynamically in my code.

Here is where my custom title bar gets called:

requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.foo_layout);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title_bar);

And this is my custom_title_bar:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@layout/custom_title_bar_background_colors">
<ImageView
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:src="@drawable/title_bar_logo"
              android:gravity="center_horizontal"
              android:paddingTop="0dip"/>

</LinearLayout>

As you can see, the background on the linear layout is defined by this guy:

<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
    android:startColor="#616261"
    android:endColor="#131313"
    android:angle="270"
 />
<corners android:radius="0dp" />
</shape>

What I would like to do is set those gradient colors dynamically in my code.  I do not want to hard code them in my XML file like they currently are.

I am open to all ideas if you have a better way of setting a background gradient.

Thank you in advance!!

Body:
Answer with gradient generation is correct, but it will not work if you just set background to MaterialButton. For MaterialButton you have to nullable default backgroundTint:

app:backgroundTint="@null"

After that solution will work. (link to source: https://github.com/material-components/material-components-android/issues/889#issuecomment-621194246)


问:
how to verify checkbox is checked in react/typescript
i want to verify that my custom component checkbox is checked when i trigger a click.
Actually, i tried many differents stuffs and still not working.
Here is my custom component

```<code>interface IProps {
  checked: boolean;
  type?: 'filledDotPrimary' | 'checkmark' | 'checkmarkValid';
  disabled?: boolean;
  hasError?: boolean;
  hasLabel?: boolean;
  isActuallyCheckbox?: boolean;
  labelStyle?: 'default' | 'outlined';
  name: string;
  onCheck?: (event: ChangeEvent<HTMLInputElement>) => void;
  overrideContainer?: string;
  id?: string;
  testId?: string;
}
/**
 * Custom radio input built using regular and solid css svgs.
 *
 * @param checked boolean. Defines the style when checked.
 * @param disabled boolean (optional). Defines the style when disabled: no box shadow and slightly grey background.
 * @param hasError boolean (optional). Defines the style red borders of the circle if error happens.
 * @param color 'primary' | 'valid'. By default 'primary' (blue), use 'valid' for green background.
 * @param type 'filledDot' | 'checkmark'. By default 'filledDot' (circle with circle), use 'checkmark' for different style.
 * @param name string. Mandatory for identifying the label with its input.
 * @param onCheck MouseEvent<HTMLElement>(optional). Define action when checked
 * @param overrideContainer string(optional). Modify container css
 *
 * @returns div + input type radio + label
 */

const RadioButton: FC<IProps> = ({
  checked,
  disabled = false,
  hasError = false,
  isActuallyCheckbox = false,
  labelStyle = 'default',
  type = 'filledDotPrimary',
  name,
  onCheck = () => {},
  overrideContainer = '',
  id = '',
  testId = '',
}): ReactElement<any, any> => {
  return (
    <span
      className={classnames(
        styles[`${type}`],
        hasError ? styles.error : false,
        labelStyle === 'outlined' ? styles.outlinedAlign : false,
        overrideContainer
      )}
      onClick={(event: MouseEvent<HTMLInputElement>): void => event.stopPropagation()}
    >
      {isActuallyCheckbox ? (
        <input type="checkbox" name={name} id={id} disabled={disabled} checked={checked}  onChange={onCheck} />
      ) : (
        <input type="radio" name={name} id={id} disabled={disabled} checked={checked} onChange={onCheck} />
      )}
      <label htmlFor={id}>
        {labelStyle === 'outlined' ? (
          <span className={checked ? styles.outlinedSelected : hasError ? styles.outlinedError : styles.outlined}>
            {name}
          </span>
        ) : (
          name
        )}
      </label>
    </span>
  );
};

export default RadioButton;
</code>```

and here is where i use this RadioButton component

```<code>  <RadioButton type="checkmark" name=""  onCheck={onCheck} isActuallyCheckbox={true}  checked={doubleApproval} />
</code>```

the oncheck method which is supposed to trigger the event, but it seems not working even when i console.log()

```<code>// state declaration
   const [doubleApproval, setDoubleApproval] = useState<boolean>(false);

// functions
  function onCheck(): void {
    console.log("clicked")
    setDoubleApproval(!doubleApproval);
  }
</code>```

can someone tell me why it doesn't working and how could fix it please ?

答:
I found the issue
Actually, I had to provide the id attribute to my input which is related to my component so that react can detect it.
In my case, I didn't provide an id attribute, so react doesn't actually know which element is in action. So I have this finally:</p>
```<code><RadioButton
  type="checkmark"
  name=''
  id='radio1'
  onCheck={onCheck}
  isActuallyCheckbox={true}
  checked={doubleApproval}
 />
</code>```

Body:
i want to verify that my custom component checkbox is checked when i trigger a click.
Actually, i tried many differents stuffs and still not working.
Here is my custom component

interface IProps {
  checked: boolean;
  type?: 'filledDotPrimary' | 'checkmark' | 'checkmarkValid';
  disabled?: boolean;
  hasError?: boolean;
  hasLabel?: boolean;
  isActuallyCheckbox?: boolean;
  labelStyle?: 'default' | 'outlined';
  name: string;
  onCheck?: (event: ChangeEvent<HTMLInputElement>) => void;
  overrideContainer?: string;
  id?: string;
  testId?: string;
}
/**
 * Custom radio input built using regular and solid css svgs.
 *
 * @param checked boolean. Defines the style when checked.
 * @param disabled boolean (optional). Defines the style when disabled: no box shadow and slightly grey background.
 * @param hasError boolean (optional). Defines the style red borders of the circle if error happens.
 * @param color 'primary' | 'valid'. By default 'primary' (blue), use 'valid' for green background.
 * @param type 'filledDot' | 'checkmark'. By default 'filledDot' (circle with circle), use 'checkmark' for different style.
 * @param name string. Mandatory for identifying the label with its input.
 * @param onCheck MouseEvent<HTMLElement>(optional). Define action when checked
 * @param overrideContainer string(optional). Modify container css
 *
 * @returns div + input type radio + label
 */

const RadioButton: FC<IProps> = ({
  checked,
  disabled = false,
  hasError = false,
  isActuallyCheckbox = false,
  labelStyle = 'default',
  type = 'filledDotPrimary',
  name,
  onCheck = () => {},
  overrideContainer = '',
  id = '',
  testId = '',
}): ReactElement<any, any> => {
  return (
    <span
      className={classnames(
        styles[`${type}`],
        hasError ? styles.error : false,
        labelStyle === 'outlined' ? styles.outlinedAlign : false,
        overrideContainer
      )}
      onClick={(event: MouseEvent<HTMLInputElement>): void => event.stopPropagation()}
    >
      {isActuallyCheckbox ? (
        <input type="checkbox" name={name} id={id} disabled={disabled} checked={checked}  onChange={onCheck} />
      ) : (
        <input type="radio" name={name} id={id} disabled={disabled} checked={checked} onChange={onCheck} />
      )}

        {labelStyle === 'outlined' ? (

            {name}

        ) : (
          name
        )}

  );
};

export default RadioButton;

and here is where i use this RadioButton component

  <RadioButton type="checkmark" name=""  onCheck={onCheck} isActuallyCheckbox={true}  checked={doubleApproval} />

the oncheck method which is supposed to trigger the event, but it seems not working even when i console.log()

// state declaration
   const [doubleApproval, setDoubleApproval] = useState<boolean>(false);

// functions
  function onCheck(): void {
    console.log("clicked")
    setDoubleApproval(!doubleApproval);
  }

can someone tell me why it doesn't working and how could fix it please ?

Body:
I found the issue
Actually, I had to provide the id attribute to my input which is related to my component so that react can detect it.
In my case, I didn't provide an id attribute, so react doesn't actually know which element is in action. So I have this finally:

<RadioButton
  type="checkmark"
  name=''
  id='radio1'
  onCheck={onCheck}
  isActuallyCheckbox={true}
  checked={doubleApproval}
 />


答:
You want to:

remove '\n' and

any number including the space in front of the number

but not the space in the middle of the name.

Functions to use:

for constant parts you could just replace using str.replace().

for all dynamic matches we need a regex  to substitute with empty-string using re.sub().

for surroundings we can even use str.strip() to remove leading and trailing whitespaces like \n.

Code

import re

input = "West Team 4, Eastern 3\n"

cleaned = re.sub(r'\s+\d', '', input)  # remove numbers with leading spaces
cleaned = cleaned.strip()  # remove surrounding whitespace like \n
print(cleaned)

output = cleaned.split(",")
print(output)
```
<p>Prints:</p>
```West Team, Eastern
['West Team', 'Eastern']
```

Title: python regex text extraction

Body:
You want to:

remove '\n' and

any number including the space in front of the number

but not the space in the middle of the name.

Functions to use:

for constant parts you could just replace using str.replace().

for all dynamic matches we need a regex  to substitute with empty-string using re.sub().

for surroundings we can even use str.strip() to remove leading and trailing whitespaces like \n.

Code

import re

input = "West Team 4, Eastern 3\n"

cleaned = re.sub(r'\s+\d', '', input)  # remove numbers with leading spaces
cleaned = cleaned.strip()  # remove surrounding whitespace like \n
print(cleaned)

output = cleaned.split(",")
print(output)

Prints:

West Team, Eastern
['West Team', 'Eastern']


问:
New Line not being written on file (Qt)
i am keeping a log of activities in my software using qtextedit. later when i want to save it as a text using toPlainText(), the resulting text file is a single line without any line breaks.
I start logging by plainText() and add subsequent additions using append().

```<code>void rocketscience::saveLog(){
QFile logFile;
QTextStream logOut;
QString logfName;

QSettings prevSet("us","fr");

    if (defaultDir.exists(prevSet.value("settings/logPath").toString()))
        logfName= QFileDialog::getSaveFileName(this,"Save File",fName,"Text (*.txt");

    if (logfName!=NULL){

    logFile.setFileName(logfName);
    logFile.open(QIODevice::WriteOnly);
    logOut.setDevice(&logFile);
    logOut<<ui.statusReport->toPlainText();
    logFile.close();
}
</code>```

}

答:
Probably the file is written using UNIX line endings? You should open the file in text, to get the local (Windows) line-endings:</p>

```<code>  logFile.open(QIODevice::WriteOnly|QIODevice::Text);
</code>```

Title: New Line not being written on file (Qt)

Body:
i am keeping a log of activities in my software using qtextedit. later when i want to save it as a text using toPlainText(), the resulting text file is a single line without any line breaks.
I start logging by plainText() and add subsequent additions using append().

void rocketscience::saveLog(){
QFile logFile;
QTextStream logOut;
QString logfName;

QSettings prevSet("us","fr");

    if (defaultDir.exists(prevSet.value("settings/logPath").toString()))
        logfName= QFileDialog::getSaveFileName(this,"Save File",fName,"Text (*.txt");

    if (logfName!=NULL){

    logFile.setFileName(logfName);
    logFile.open(QIODevice::WriteOnly);
    logOut.setDevice(&logFile);
    logOut<<ui.statusReport->toPlainText();
    logFile.close();
}

}

Body:
Probably the file is written using UNIX line endings? You should open the file in text, to get the local (Windows) line-endings:

  logFile.open(QIODevice::WriteOnly|QIODevice::Text);


问:
Trying to access design metadata without viewer, but have a problem of getting sqllite file
I am trying to use the api service as in the below link, and trying to get metadata by using derivative urn.

https://forge.autodesk.com/en/docs/model-derivative/v2/reference/http/urn-manifest-derivativeurn-GET/

However, the data returning from the service is broken as in below. What can be the problem?

答:
As described in this post, there is multiple ways to get metadata : Accessing Design Metadata Without Viewer

The easiest way is to request the metadata endpoint as @varunpatil already answered.
But if you want to get a Sqlite file, you can download this file using the method described in Petr's post.
If you get a 200 status code in your response, you should have the entire file, 206 means you only get chunked partial content.


问:
How can I create pojo class of json array
How can I create pojo class of this type of JsonArray
Below links response
https://fakestoreapi.com/products/categories</p>
```<code>[
"electronics",
"jewelery",
"men's clothing",
"women's clothing"
]
</code>```

答:
Just Use ArrayList Of String</p>
```<code>public class ClassName{
  @JsonProperty("MyArray")
  public ArrayList<String> myArray;
}
</code>```

Body:
How can I create pojo class of this type of JsonArray
Below links response
https://fakestoreapi.com/products/categories

[
"electronics",
"jewelery",
"men's clothing",
"women's clothing"
]

Body:
Just Use ArrayList Of String

public class ClassName{
  @JsonProperty("MyArray")
  public ArrayList<String> myArray;
}


问:
Elasticsearch, Failed to obtain node lock, is the following location writable
Elasticsearch won't start using ./bin/elasticsearch.
It raises the following exception:

```<code>- ElasticsearchIllegalStateException[Failed to obtain node lock, is the following location writable?: [/home/user1/elasticsearch-1.4.4/data/elasticsearch]
</code>```

I checked the permissions on the same location and the location has 777 permissions on it and is owned by user1.

```<code>ls -al /home/user1/elasticsearch-1.4.4/data/elasticsearch
</code>```

```<code>drwxrwxrwx  3 user1 wheel 4096 Mar  8 13:24 .
drwxrwxrwx  3 user1 wheel 4096 Mar  8 13:00 ..
drwxrwxrwx 52 user1 wheel 4096 Mar  8 13:51 nodes
</code>```

What is the problem?

Trying to run elasticsearch 1.4.4 on linux without root access.

答: Mostly this error occurs when you kill the process abruptly. When you kill the process, node.lock file may not be cleared. you can manually remove the node.lock file and start the process again, it should work</p>

Body:
Elasticsearch won't start using ./bin/elasticsearch.
It raises the following exception:

- ElasticsearchIllegalStateException[Failed to obtain node lock, is the following location writable?: [/home/user1/elasticsearch-1.4.4/data/elasticsearch]

I checked the permissions on the same location and the location has 777 permissions on it and is owned by user1.

ls -al /home/user1/elasticsearch-1.4.4/data/elasticsearch

drwxrwxrwx  3 user1 wheel 4096 Mar  8 13:24 .
drwxrwxrwx  3 user1 wheel 4096 Mar  8 13:00 ..
drwxrwxrwx 52 user1 wheel 4096 Mar  8 13:51 nodes

What is the problem?

Trying to run elasticsearch 1.4.4 on linux without root access.


问:
Passing function through Switch Route component
I want to build an app, which collects input information from sub-components and lift this information up to my main App component. I am using Switch with multiple Route to navigate through my questionnaire. I am able to pass variables and functions through my app until the <Switch> statement.

My problem: how do I pass a function or variable into my <Route> component.

```<code>class App extends Component {
    state = {
      date: new Date(),
      machineid: null,
    };

  handleChangeMachine(event) {
    const machineid_temp = event.target.value;
    this.setState({machineid: machineid_temp})
    console.log(machineid_temp)
  }

  render(){
    return (
    <div className="page">
      <Router>
        <Header testvalue="this is working"/>
        <Switch testvalues="this is working">
          <Route testvalues="this is not working" path="/" exact component={Landingpage}/>
          <Route path="/survey" component={Survey}/>
          <Route path="/kontakt" component={Kontakt}/>
          <Route path="/question_one" handleChangeMachine={this.handleChangeMachine}  component={question_one}/> {/* This is not working */}
          <Route path="/question_two" component={question_two}/>
        </Switch>
      </Router>
    </div>
  );
}
}

export default App;
</code>```

In this case the function handleChangeMachine isn't properly passed to the component question_one. Has anyone an idea about how I can solve it? I've tried every thing I understood as a React-beginner.

答:
If you are using React-router@v5, you can write your route as follow:

```<code><Route path="/question_one">
  <QuestionOne handleChangeMachine={this.handleChangeMachine.bind(this)}
</Route>
</code>```

Note that question_one isn't a correct component name.

Or even :

```<code><Route
  path="/question_one"
  render={({ match }) => {
    // Do whatever you want with the match...
    return <QuestionOne handleChangeMachine={this.handleChangeMachine.bind(this)} />;
  }}
/>
</code>```

You can check the documentation for more information.

Here is a repro on Stackblitz.

Body:
I want to build an app, which collects input information from sub-components and lift this information up to my main App component. I am using Switch with multiple Route to navigate through my questionnaire. I am able to pass variables and functions through my app until the <Switch> statement.

My problem: how do I pass a function or variable into my <Route> component.

class App extends Component {
    state = {
      date: new Date(),
      machineid: null,
    };

  handleChangeMachine(event) {
    const machineid_temp = event.target.value;
    this.setState({machineid: machineid_temp})
    console.log(machineid_temp)
  }

  render(){
    return (

      <Router>

        <Switch testvalues="this is working">
          <Route testvalues="this is not working" path="/" exact component={Landingpage}/>
          <Route path="/survey" component={Survey}/>
          <Route path="/kontakt" component={Kontakt}/>
          <Route path="/question_one" handleChangeMachine={this.handleChangeMachine}  component={question_one}/> {/* This is not working */}
          <Route path="/question_two" component={question_two}/>
        </Switch>
      </Router>

  );
}
}

export default App;

In this case the function handleChangeMachine isn't properly passed to the component question_one. Has anyone an idea about how I can solve it? I've tried every thing I understood as a React-beginner.

Body:
If you are using React-router@v5, you can write your route as follow:

<Route path="/question_one">
  <QuestionOne handleChangeMachine={this.handleChangeMachine.bind(this)}
</Route>

Note that question_one isn't a correct component name.

Or even :

<Route
  path="/question_one"
  render={({ match }) => {
    // Do whatever you want with the match...
    return <QuestionOne handleChangeMachine={this.handleChangeMachine.bind(this)} />;
  }}
/>

You can check the documentation for more information.

Here is a repro on Stackblitz.


答:
You can use a non-regex approach to keep any letters/spaces after splitting with a comma:

text = "West Team 4, Eastern 3\n"
print( ["".join(c for c in x if c.isalpha() or c.isspace()).strip() for x in text.split(',')]  )
# => ['West Team', 'Eastern']
```
<p>Or a regex approach to remove any chars other than ASCII letters and spaces matched with the <code>[^a-zA-Z\s]+</code> pattern:</p>
<pre class="lang-py prettyprint-override"><code>import re
rx = re.compile(r'[^a-zA-Z\s]+')
print( [rx.sub("", x).strip() for x in text.split(',')]  )
# => ['West Team', 'Eastern']
</code>```

Another similar solution can be used to extract one or more non-digit char chunks after an optional comma + whitespaces:

print(re.findall(r',?\s*(\D*[^\d\s])', text))
```
<p>See the Python demo.</p>
<p>In case there are consecutive non-letter chunks you can use</p>
<pre class="lang-py prettyprint-override"><code>import re
text = "West Team 4, Eastern 3\n, test 23 99 test"
rx = re.compile(r'[^\W\d_]+')
print( [" ".join(rx.findall(x)) for x in text.split(',')]  )
</code>```

See the Python demo yielding ['West Team', 'Eastern', 'test test']. The [^\W\d_]+ pattern matches any one or more Unicode letters.

Title: python regex text extraction

Body:
the text input is something like this
West Team 4, Eastern 3\n

-------Update--------

the input is a txt file containing team name and scores like a football game
the whole text file will be something like this, two names and scores:

West Team 4, Eastern 5
Nott Team 2, Eastern 3
West wood 1, Eathan 2
West Team 4, Eas 5

I am using with open to read file line by line therefore there will be \n at the end of the line.

I would like to extract this line of text in to something like:

['West Team', 'Eastern']

What I currently have in mind is to use regex

result = re.sub("[\n^\s$\d]", "", text).split(",")

this code results in this:

['WestTeam','Eastern']

I'm sure that my regex is not correct. I want to remove '\n' and any number including the space in front of the number but not the space in the middle of the name.

Open to any suggestion that to achieve this result, doesn't necessarily use regex.

Body:
You can use a non-regex approach to keep any letters/spaces after splitting with a comma:

text = "West Team 4, Eastern 3\n"
print( ["".join(c for c in x if c.isalpha() or c.isspace()).strip() for x in text.split(',')]  )
# => ['West Team', 'Eastern']

Or a regex approach to remove any chars other than ASCII letters and spaces matched with the [^a-zA-Z\s]+ pattern:

import re
rx = re.compile(r'[^a-zA-Z\s]+')
print( [rx.sub("", x).strip() for x in text.split(',')]  )
# => ['West Team', 'Eastern']

Another similar solution can be used to extract one or more non-digit char chunks after an optional comma + whitespaces:

print(re.findall(r',?\s*(\D*[^\d\s])', text))

See the Python demo.

In case there are consecutive non-letter chunks you can use

import re
text = "West Team 4, Eastern 3\n, test 23 99 test"
rx = re.compile(r'[^\W\d_]+')
print( [" ".join(rx.findall(x)) for x in text.split(',')]  )

See the Python demo yielding ['West Team', 'Eastern', 'test test']. The [^\W\d_]+ pattern matches any one or more Unicode letters.


问:
Only few mails getting delivered using sp_send_dbmail in SQL Server 2008
I am extracting the recipient list from a column in a table and I am running the stored procedure sp_send_dbmail to send the emails to these recipients.

There are a total of around 200 recipients.

Ironically only few of the mails are delivered even though the message that I am getting is Mail queued. The database mail is correctly configured and I am using the Public database profile.

When I check the msdb.dbo.sysmail_mailitems table, as expected value in sent_status column is 1 for the recipients for whom the mail is delivered and for rest of them the value is either 0 or 2.

I am completely sure that the recipient list is 100% correct. Do we have any workaround to resolve this issue?

Below is the code that I am running:

```<code>CREATE procedure [dbo].[sp_dataRefreshNotification]
AS
BEGIN
DECLARE @ToMail VARCHAR(20)
DECLARE @Body1 VARCHAR(MAX) =
'Dear User,
Data has been refreshed.
Regards,
IT Support Team

Note: This is an auto generated e-mail, please do not reply this mail. '

SELECT DISTINCT RecipientAddress FROM dbo.RecipientAddressList
OPEN notification_cursor
FETCH NEXT FROM notification_cursor
INTO @ToMail

WHILE @@FETCH_STATUS = 0
BEGIN
EXEC msdb.dbo.sp_send_dbmail
@profile_name  ='aaaa',
@Recipients = @Tomail,
@Subject = 'Required Data',
@Body = @Body1
FETCH NEXT FROM notification_cursor
INTO @ToMail
END
CLOSE notification_cursor
DEALLOCATE notification_cursor
END
</code>```

答: If you really need to send a separate email to each individual, then your method is good using the loop and a WAITFOR DELAY '00:00:10' in the loop. But if you could send one email to all individuals, then you could concatenate these emails. Only there is a maximum of 255 characters of concatenated emails that can be in the recipient box. So you'd have to break the resulted string into pieces or 255 characters of less.</p>

Body:
I am extracting the recipient list from a column in a table and I am running the stored procedure sp_send_dbmail to send the emails to these recipients.

There are a total of around 200 recipients.

Ironically only few of the mails are delivered even though the message that I am getting is Mail queued. The database mail is correctly configured and I am using the Public database profile.

When I check the msdb.dbo.sysmail_mailitems table, as expected value in sent_status column is 1 for the recipients for whom the mail is delivered and for rest of them the value is either 0 or 2.

I am completely sure that the recipient list is 100% correct. Do we have any workaround to resolve this issue?

Below is the code that I am running:

CREATE procedure [dbo].[sp_dataRefreshNotification]
AS
BEGIN
DECLARE @ToMail VARCHAR(20)
DECLARE @Body1 VARCHAR(MAX) =
'Dear User,
Data has been refreshed.
Regards,
IT Support Team

Note: This is an auto generated e-mail, please do not reply this mail. '

SELECT DISTINCT RecipientAddress FROM dbo.RecipientAddressList
OPEN notification_cursor
FETCH NEXT FROM notification_cursor
INTO @ToMail

WHILE @@FETCH_STATUS = 0
BEGIN
EXEC msdb.dbo.sp_send_dbmail
@profile_name  ='aaaa',
@Recipients = @Tomail,
@Subject = 'Required Data',
@Body = @Body1
FETCH NEXT FROM notification_cursor
INTO @ToMail
END
CLOSE notification_cursor
DEALLOCATE notification_cursor
END


问:
NextJS static pages never get refreshed in browser although revalidated on server
I have a NextJS project with many sites that use getStaticProps() in combination with revalidate. As expected, the pages are generated at build time and are rebuilt in the specified interval (verified using a REST client). However, the users never get to see the refreshed version of the page because the browser seems to cache the generated html. In production, the NextJS server generates caching headers as follows: Cache-Control: s-maxage=60, stale-while-revalidate. No matter how long I wait or journey through the page, the browser never requests the updated page. I only get to see the new data when I manually refresh the page - which I cannot ask my users to do on a daily basis. I also tried overwriting the Cache-Control headers to max-age=60, s-maxage=60, stale-while-revalidate=120 using the nginx that sits in front of the NextJS server, but no chance. For links on the page I use import Link from "next/link". Any ideas on this?

答:
Okay, got it, thanks for the hint. ISR is not meant to work like that. I got it to work in combination with SWR:
https://swr.vercel.app/docs/with-nextjs

So I pre-render the pages with SSG to have a good performance and SEO. In addition, the client requests fresh data while the old data is shown, using SWR.


问:
mediaelement.js - How to hide Audio controls?
I am trying to implement Mediaelement.js into a site for both video and audio, the video is all working great however what I need to do is hide the audio element so it does not show on the page at all and that the MEJS audio control bar isnt visible. Playback for the audio will be handled through a function to play/pause the audio as needed.

Ive tried altering the CSS and also changing the audio code to include "hidden=true" currently the audio blocks look like this:

```<code>    <audio id="Audio101" hidden="true">
    <source src="audio/audio1.mp3" />
    <source src="audio/audio1.ogg" />
    <embed src="audio/audio1.mp3" hidden=true autostart=false loop=false>
    </audio>
</code>```

Does anyone know how to hide only the Audio (not Video) MEJS controls?

Cheers.

答:
it's a bit dirty, but this seems to work:</p>

```<code>$('#Audio101').mediaelementplayer({
     success: function(){
          $('.mejs-container').css('display', 'none');
     }
})
</code>```

Body:
I am trying to implement Mediaelement.js into a site for both video and audio, the video is all working great however what I need to do is hide the audio element so it does not show on the page at all and that the MEJS audio control bar isnt visible. Playback for the audio will be handled through a function to play/pause the audio as needed.

Ive tried altering the CSS and also changing the audio code to include "hidden=true" currently the audio blocks look like this:

    <audio id="Audio101" hidden="true">
    <source src="audio/audio1.mp3" />
    <source src="audio/audio1.ogg" />
    <embed src="audio/audio1.mp3" hidden=true autostart=false loop=false>
    </audio>

Does anyone know how to hide only the Audio (not Video) MEJS controls?

Cheers.

Body:
it's a bit dirty, but this seems to work:

$('#Audio101').mediaelementplayer({
     success: function(){
          $('.mejs-container').css('display', 'none');
     }
})


问:
How to access microphone(camera) in robot framework?
I am working on robot framework where in i am not able to allow chrome camera allow popup from the browser. Please help on this or code will help a lot.

答:
*** Settings ***

Library          SeleniumLibrary
Library          BuiltIn

#Test Setup       Test Case Setup

*** Test Cases ***
Test Site Login

```<code>  ${chrome_options}=Evaluate sys.modules['selenium.webdriver'].ChromeOptions()   sys

Call Method      ${chrome_options}   add_argument    --use-fake-ui-for-media-stream

Call Method         ${chrome_options}   add_argument    --use-fake-device-for-media-stream

Create Webdriver    Chrome  alias=tab1  chrome_options=${chrome_options}

Open Browser     https://www.google.com/  Chrome     alias=tab1

Click Element    xpath://div[@aria-label='Search by voice']//*[name()='svg']
</code>```

This is the code which we can use for the purpose of enabling the mic in www.google.com

Body:
*** Settings ***

Library          SeleniumLibrary
Library          BuiltIn

#Test Setup       Test Case Setup

*** Test Cases ***
Test Site Login

  ${chrome_options}=Evaluate sys.modules['selenium.webdriver'].ChromeOptions()   sys

Call Method      ${chrome_options}   add_argument    --use-fake-ui-for-media-stream

Call Method         ${chrome_options}   add_argument    --use-fake-device-for-media-stream

Create Webdriver    Chrome  alias=tab1  chrome_options=${chrome_options}

Open Browser     https://www.google.com/  Chrome     alias=tab1

Click Element    xpath://div[@aria-label='Search by voice']//*[name()='svg']

This is the code which we can use for the purpose of enabling the mic in www.google.com


问:
aws cdk for Elasticache Redis Cluster
I have gone through the https://docs.aws.amazon.com/cdk/api/latest/python/aws_cdk.aws_elasticache.html.

How to create an Elasticache Redis template using AWS-CDK. It would be more helpful if you share the sample code.

答:
I just struggled for hours creating a Redis cluster mode enabled with just one shard but two nodes. If you create a CfnReplicationGroup with num_cache_clusters=2, it will create a primary & replica node.

The trick is to create a CfnReplicationGroup with num_cache_clusters=2 and set the cache_parameter_group_name="default.redis6.x.cluster.on"

Then it will create a redis cache with cluster mode enable, one shard but two nodes

Title: aws cdk for Elasticache Redis Cluster


答:
```<code>import re

text = 'West Team 4, Eastern 3\n'

result = re.sub("[\n^$\d]", "", text).split(",")

# REMOVE THE LEADING AND TRAILING SPACES:
result = [x.strip() for x in result]
print(result)
# result: ['West Team', 'Eastern']
</code>```

Title: python regex text extraction


问:
notify user when wifi, or 3g 4g network get lost jquery or javascript
we have web site which is optimized for mobile phone. we do qute frequent ajax requestes and some time an event get rigered from a back end.

now the problem is how to properly manage when network connection get lost.

can we create a custom event where it will be triggered when a connection get lost using jquery?

答:
use following code.</p>

```<code>$(document).ready(function () {
   if (!Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack()) {
                Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
   }
});

    function endRequestHandler(sender, args) {
        if (args.get_error() != undefined) {
            var errorMessage;
            if (args.get_response().get_statusCode() == '200') {
                errorMessage = args.get_error().message;
            }
            else {
                // Error occurred somewhere other than the server page.
                errorMessage = "Error Message";
            }
            args.set_errorHandled(true);
            $get('ErrorMessage').innerHTML = errorMessage;
        } else {
            // no error occur
        }
    }
</code>```

Body:
use following code.

$(document).ready(function () {
   if (!Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack()) {
                Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
   }
});

    function endRequestHandler(sender, args) {
        if (args.get_error() != undefined) {
            var errorMessage;
            if (args.get_response().get_statusCode() == '200') {
                errorMessage = args.get_error().message;
            }
            else {
                // Error occurred somewhere other than the server page.
                errorMessage = "Error Message";
            }
            args.set_errorHandled(true);
            $get('ErrorMessage').innerHTML = errorMessage;
        } else {
            // no error occur
        }
    }


问:
Explain These Services.xml File Terms In Shopware 6
What does argument and argument type mean,
What does tag and tag name mean,
in Shopware 6 plugin services.xml file?

```<code><?xml version="1.0" ?>
</code>```

```<code><services>
    <service id="Winner\Service\ExampleService" />

    <service id="Winner\Service\ExampleServiceDecorator" decorates="Winner\Service\ExampleService">
        <tag name="kernel.event_listener" event="product.loaded" />
        <argument type="service" id="Winner\Service\ExampleServiceDecorator.inner" />
    </service>
</services>
</code>```

答:
The services.xml file is the configuration file for the symfony dependency injection container.

By default, Symfony allows autowiring of the config, but the Shopware default is to configure the DI container manually. Please refer to the Symfony docs for more information on manually configuring the DI.

And the Symfony docs also have more information on service tags.

So technically this is not a Shopware specific question, but rather a Symfony question. I hope my answer and the provided docs help you.

Body:
What does argument and argument type mean,
What does tag and tag name mean,
in Shopware 6 plugin services.xml file?

<?xml version="1.0" ?>

<services>
    <service id="Winner\Service\ExampleService" />

    <service id="Winner\Service\ExampleServiceDecorator" decorates="Winner\Service\ExampleService">
        <tag name="kernel.event_listener" event="product.loaded" />
        <argument type="service" id="Winner\Service\ExampleServiceDecorator.inner" />
    </service>
</services>


问:
How to insert a single user from a table of all users into a table in MySQL in PHP
I have a table of all registered users from my users table from my database. Now I have an accept button, when clicked I want to add that specific user to a new table called accepted_applicants.

But when I try to do this it adds all the users into the database. How can I only add the specific row that I click?

What am I doing wrong?

Here is my code:

```<code>   //users query
$query = $conn->query("SELECT users.id AS userid, users.status AS status, users.name AS username, users.dob AS dob, users.gender AS g, users.country AS country, users.addedDate AS created_date, users.categoryId AS catID ,
     category.name AS awardname, country.id AS countryID, country.country_name AS countryName FROM users LEFT JOIN category ON users.categoryId = category.id LEFT JOIN country ON country.id = users.country;");

<table class="table table-head-fixed text-nowrap">
                  <thead>
                    <tr>
                      <th>ID</th>
                      <th>Name</th>
                      <th>Gender</th>
                      <th>Date of Birth</th>
                      <th>Country</th>
                      <th>Award Category</th>
                      <th>Date Created</th>
                      <th>Application Status</th>
                      <th>Answers</th>
                      <th>Accept</th>
                      <th>Reject</th>
                    </tr>
                  </thead>
                  <tbody>
                    <?php

                    while ($row = $query->fetch()) {

                      $userid = $row['userid'];
                      $username = $row['username'];
                      $gender = $row['g'];
                      $dob = $row['dob'];
                      $date = $row['created_date'];
                      $status = $row['status'];
                      $countryName = $row['countryName'];
                      $awardCatName = $row['awardname'];

                      if(isset($_POST['accept'])){
                        $insertq = $conn->prepare("INSERT INTO accepted_applicants (user_id,name,gender,dob,country,award_cat,status) VALUES (?,?,?,?,?,?,?)");
                        $insertq->bindValue(1,$userid);
                        $insertq->bindValue(2,$username);
                        $insertq->bindValue(3,$gender);
                        $insertq->bindValue(4,$dob);
                        $insertq->bindValue(5,$countryName);
                        $insertq->bindValue(6,$awardCatName);
                        $insertq->bindValue(7,$status);
                        $insertq->execute();
                      }

                    ?>
                    <tr>
                      <td><?php echo $row['userid'] ?></td>
                      <td><?php echo $row['username'] ?></td>
                      <td><?php echo $row['g'] ?></td>
                      <td><?php echo $row['dob'] ?></td>
                      <td><?php echo $countryName ?></td>
                      <td><?php echo $awardCatName ?></td>
                      <td><?php echo $row['created_date'] ?></td>
                      <td><?php if($row['status'] == 1){
                          echo "Submitted";
                        }else{
                          echo "Not Submitted";
                        } ?></td>
                      <td><button>Answers</button></td>
                      <td><input type="submit" name="accept" value="Accept"/></td>
                      <td><input type="submit" name="reject"/></td>

                    </tr>

                    <?php
                    }
                    ?>

                  </tbody>
                </table>
                  </form>
</code>```

答:
i solved it this way:

I added an extra condition to my if statement to check if the userid is equal to the value of the Accept input field.

```<code><form method="post" action="applicant_approval.php" >
                  <tbody>
                    <?php

                    while ($row = $query->fetch()) {

                     // $userid = $row['userid'];
                      $username = $row['username'];
                      $gender = $row['g'];
                      $dob = $row['dob'];
                      $date = $row['created_date'];
                      $status = $row['status'];
                      $countryName = $row['countryName'];
                      $awardCatName = $row['awardname'];

                      if(isset($_POST['accept']) && $_POST['accept']==$row['userid']){
                        $insertq = $conn->prepare("INSERT INTO accepted_applicants (user_id,name,gender,dob,country,award_cat,status) VALUES (?,?,?,?,?,?,?)" );
                        $insertq->bindValue(1,$row['userid']);
                        $insertq->bindValue(2,$username);
                        $insertq->bindValue(3,$gender);
                        $insertq->bindValue(4,$dob);
                        $insertq->bindValue(5,$countryName);
                        $insertq->bindValue(6,$awardCatName);
                        $insertq->bindValue(7,$status);
                        $insertq->execute();
                      }

                    ?>

                    <tr>
                      <td><?php echo $row['userid'] ?></td>
                      <td><?php echo $row['username'] ?></td>
                      <td><?php echo $row['g'] ?></td>
                      <td><?php echo $row['dob'] ?></td>
                      <td><?php echo $countryName ?></td>
                      <td><?php echo $awardCatName ?></td>
                      <td><?php echo $row['created_date'] ?></td>
                      <td><?php if($row['status'] == 1){
                          echo "Submitted";
                        }else{
                          echo "Not Submitted";
                        } ?></td>
                      <td><button>Answers</button></td>
                      <td><input type="submit" name="accept" value="<?php echo $row['userid']; ?>"/></td>
                      <td><input type="submit" name="reject"/></td>

                    </tr>

                    <?php
                    }
                    ?>

                  </tbody>
                </table>
                  </form>
</code>```

Body:
I have a table of all registered users from my users table from my database. Now I have an accept button, when clicked I want to add that specific user to a new table called accepted_applicants.

But when I try to do this it adds all the users into the database. How can I only add the specific row that I click?

What am I doing wrong?

Here is my code:

   //users query
$query = $conn->query("SELECT users.id AS userid, users.status AS status, users.name AS username, users.dob AS dob, users.gender AS g, users.country AS country, users.addedDate AS created_date, users.categoryId AS catID ,
     category.name AS awardname, country.id AS countryID, country.country_name AS countryName FROM users LEFT JOIN category ON users.categoryId = category.id LEFT JOIN country ON country.id = users.country;");

                      ID
                      Name
                      Gender
                      Date of Birth
                      Country
                      Award Category
                      Date Created
                      Application Status
                      Answers
                      Accept
                      Reject

                    <?php

                    while ($row = $query->fetch()) {

                      $userid = $row['userid'];
                      $username = $row['username'];
                      $gender = $row['g'];
                      $dob = $row['dob'];
                      $date = $row['created_date'];
                      $status = $row['status'];
                      $countryName = $row['countryName'];
                      $awardCatName = $row['awardname'];

                      if(isset($_POST['accept'])){
                        $insertq = $conn->prepare("INSERT INTO accepted_applicants (user_id,name,gender,dob,country,award_cat,status) VALUES (?,?,?,?,?,?,?)");
                        $insertq->bindValue(1,$userid);
                        $insertq->bindValue(2,$username);
                        $insertq->bindValue(3,$gender);
                        $insertq->bindValue(4,$dob);
                        $insertq->bindValue(5,$countryName);
                        $insertq->bindValue(6,$awardCatName);
                        $insertq->bindValue(7,$status);
                        $insertq->execute();
                      }

                    ?>

                      <?php echo $row['userid'] ?>
                      <?php echo $row['username'] ?>
                      <?php echo $row['g'] ?>
                      <?php echo $row['dob'] ?>
                      <?php echo $countryName ?>
                      <?php echo $awardCatName ?>
                      <?php echo $row['created_date'] ?>
                      <?php if($row['status'] == 1){
                          echo "Submitted";
                        }else{
                          echo "Not Submitted";
                        } ?>
                      <button>Answers</button>
                      <input type="submit" name="accept" value="Accept"/>
                      <input type="submit" name="reject"/>

                    <?php
                    }
                    ?>

                  </form>

Body:
i solved it this way:

I added an extra condition to my if statement to check if the userid is equal to the value of the Accept input field.

<form method="post" action="applicant_approval.php" >
                  <tbody>
                    <?php

                    while ($row = $query->fetch()) {

                     // $userid = $row['userid'];
                      $username = $row['username'];
                      $gender = $row['g'];
                      $dob = $row['dob'];
                      $date = $row['created_date'];
                      $status = $row['status'];
                      $countryName = $row['countryName'];
                      $awardCatName = $row['awardname'];

                      if(isset($_POST['accept']) && $_POST['accept']==$row['userid']){
                        $insertq = $conn->prepare("INSERT INTO accepted_applicants (user_id,name,gender,dob,country,award_cat,status) VALUES (?,?,?,?,?,?,?)" );
                        $insertq->bindValue(1,$row['userid']);
                        $insertq->bindValue(2,$username);
                        $insertq->bindValue(3,$gender);
                        $insertq->bindValue(4,$dob);
                        $insertq->bindValue(5,$countryName);
                        $insertq->bindValue(6,$awardCatName);
                        $insertq->bindValue(7,$status);
                        $insertq->execute();
                      }

                    ?>

                    <tr>
                      <td><?php echo $row['userid'] ?></td>
                      <td><?php echo $row['username'] ?></td>
                      <td><?php echo $row['g'] ?></td>
                      <td><?php echo $row['dob'] ?></td>
                      <td><?php echo $countryName ?></td>
                      <td><?php echo $awardCatName ?></td>
                      <td><?php echo $row['created_date'] ?></td>
                      <td><?php if($row['status'] == 1){
                          echo "Submitted";
                        }else{
                          echo "Not Submitted";
                        } ?></td>
                      <td><button>Answers</button></td>
                      <td><input type="submit" name="accept" value="<?php echo $row['userid']; ?>"/></td>
                      <td><input type="submit" name="reject"/></td>

                    </tr>

                    <?php
                    }
                    ?>

                  </tbody>
                </table>
                  </form>


问:
How to get iTunes-specific child nodes of RSS feeds?
I'm trying to process an RSS feed using PHP and there are some tags such as 'itunes:image' which I need to process. The code I'm using is below and for some reason these elements are not returning any value. The output is length is 0.

How can I read these tags and get their attributes?

```<code>$f = $_REQUEST['feed'];
$feed = new DOMDocument();
$feed->load($f);
$items = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('item');

foreach($items as $key => $item)
{
    $title = $item->getElementsByTagName('title')->item(0)->firstChild->nodeValue;
    $pubDate = $item->getElementsByTagName('pubDate')->item(0)->firstChild->nodeValue;
    $description = $item->getElementsByTagName('description')->item(0)->textContent; // textContent

    $arrt = $item->getElementsByTagName('itunes:image');
    print_r($arrt);
}
</code>```

答:
```<code><?php
$rss_feed = simplexml_load_file("url link");
if(!empty($rss_feed)) {
$i=0;
foreach ($rss_feed->channel->item as $feed_item) {
?>

<?php echo $rss_feed->children('itunes', true)->image->attributes()->href;?>

<?php
}
?>
</code>```

Body:
I'm trying to process an RSS feed using PHP and there are some tags such as 'itunes:image' which I need to process. The code I'm using is below and for some reason these elements are not returning any value. The output is length is 0.

How can I read these tags and get their attributes?

$f = $_REQUEST['feed'];
$feed = new DOMDocument();
$feed->load($f);
$items = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('item');

foreach($items as $key => $item)
{
    $title = $item->getElementsByTagName('title')->item(0)->firstChild->nodeValue;
    $pubDate = $item->getElementsByTagName('pubDate')->item(0)->firstChild->nodeValue;
    $description = $item->getElementsByTagName('description')->item(0)->textContent; // textContent

    $arrt = $item->getElementsByTagName('itunes:image');
    print_r($arrt);
}


问:
Is there a way for someone to read my contract?
I made a Contract, "AA" then deployed it. I think, people can execute my Contract's function, but they can't read whole contents in my Contract. Can people know the details of my contract? (e.g. using web3...)</p>

答: There are decompilers (such as this one) that can convert the deployed bytecode to a pseudocode. So while it's not possible to get the exact same Solidity code, anyone can still get a rough idea of what the contract does.</p>


问:
Use array formula with index match
Is it possible to do an array formula with index match:

e.g:

```<code>=arrayformula(if(len(A3:A),INDEX('SheetB'!E:E,MATCH(A3:A,'SheetB'!H:H,0))))
</code>```

If not, is there a solution that doesn't involve google scripts?

答:
In the OP's specific case, one can actually use VLOOKUP for its intended purpose, as a replacement for MATCH:

```<code>=arrayformula(if(len(A3:A),VLOOKUP(A3:A,{SheetB!E:E,SheetB!H:H},2,false)))
</code>```

In the general case of trying to use INDEX to retrieve multiple values, it can be replaced with a kludge of VLOOKUP and SEQUENCE:

```<code>=arrayformula(VLOOKUP(A:A,{SEQUENCE(rows(B:B)),B:B},2,true))
</code>```

does what would have been accomplished by

```<code>=arrayformula(INDEX(B:B,A:A))
</code>```

if the latter worked as OP expected.

Title: Use array formula with index match

Body:
Is it possible to do an array formula with index match:

e.g:

=arrayformula(if(len(A3:A),INDEX('SheetB'!E:E,MATCH(A3:A,'SheetB'!H:H,0))))

If not, is there a solution that doesn't involve google scripts?

Body:
In the OP's specific case, one can actually use VLOOKUP for its intended purpose, as a replacement for MATCH:

=arrayformula(if(len(A3:A),VLOOKUP(A3:A,{SheetB!E:E,SheetB!H:H},2,false)))

In the general case of trying to use INDEX to retrieve multiple values, it can be replaced with a kludge of VLOOKUP and SEQUENCE:

=arrayformula(VLOOKUP(A:A,{SEQUENCE(rows(B:B)),B:B},2,true))

does what would have been accomplished by

=arrayformula(INDEX(B:B,A:A))

if the latter worked as OP expected.


问:
vshost32.exe has stopped working when I call the ShowDialog method of OpenFileDialog
I've a c# application, I'm doing a final test of it.

But now, a function which has worked everytimes until now doesn't work anymore!

I've a Button, when I click on it I want to browse files, I see the "Open file" windows, and an half second after, I got an uncaught visual studio error:

vshost32.exe has stopped working:

I'm sorry but the error is happening on a french localized computer:

```<code>Signature du problème :
  Nom d’événement de problème:  APPCRASH
  Nom de l’application: TOM.vshost.exe
  Version de l’application: 10.0.30319.1
  Horodatage de l’application:  4ba2084b
  Nom du module par défaut: ntdll.dll
  Version du module par défaut: 6.1.7600.16695
  Horodateur du module par défaut:  4cc7ab44
  Code de l’exception:  c0000008
  Décalage de l’exception:  0004631f
  Version du système:   6.1.7600.2.0.0.256.48
  Identificateur de paramètres régionaux:   4108
  Information supplémentaire n° 1:  ffb6
  Information supplémentaire n° 2:  ffb61531feaa1f65f528a2694a510c22
  Information supplémentaire n° 3:  b220
  Information supplémentaire n° 4:  b2205da238309b0a025a25162a3a18f3
</code>```

My code is:

```<code>OpenFileDialog ofd = new OpenFileDialog {Filter = Filters};
if (ofd.ShowDialog() != true) {
    return;
}
</code>```

it crash just when I'm in the ofd.ShowDialog.

Is this a code related issue?

Do you have any idea about how to debug? Or even how to debug this??

When activating the "unmanaged code to be debug", I got this:

```<code>"First-chance exception at 0x77cd631f in TOM.exe: 0xC0000008: An invalid handle was specified."
</code>```

The stack trace if it could help:

```<code>>   ntdll.dll!77cd631f()
    [Frames below may be incorrect and/or missing, no symbols loaded for ntdll.dll]
    ntdll.dll!77d1792d()
    ntdll.dll!77ce343b()
    ntdll.dll!77ce2d80()
    ole32.dll!776b4102()
    ole32.dll!776b411e()
    ole32.dll!7767e505()
    SearchFolder.dll!1046b49d()
    SearchFolder.dll!1046b267()
    shell32.dll!76281cb7()
    shell32.dll!761701b6()
    shell32.dll!761991fd()
    shell32.dll!761d61ee()
    shell32.dll!761d6159()
    System.ni.dll!524c4ed4()
    shlwapi.dll!77b6b6cf()
    ntdll.dll!77cbb428()
    ntdll.dll!77cbe6f9()
    kernel32.dll!77c01114()
    ntdll.dll!77ceb429()
    ntdll.dll!77ceb3fc()
</code>```

Some things I've tried:

An important new point:  It seems that the error doesn't happen when I run it without visual studio(which seems to be logic)

Important point bis: It seems the same code is working in visual studio of another computer(which is exactly the same and issued of the same image of windows

I tried to remove all files and do a GetLatest, but still doesn't work

答:
I remember seeing something akin to this on a computer with German locale, with our French application. I can't remember how we solved it, but the similarity points me towards checking locales...
Invalid handle though usually means the object you call is already destroyed, though I really can't guess which object, as ofd must still be valid at this point.</p>

Body:
I've a c# application, I'm doing a final test of it.

But now, a function which has worked everytimes until now doesn't work anymore!

I've a Button, when I click on it I want to browse files, I see the "Open file" windows, and an half second after, I got an uncaught visual studio error:

vshost32.exe has stopped working:

I'm sorry but the error is happening on a french localized computer:

Signature du problème :
  Nom d’événement de problème:  APPCRASH
  Nom de l’application: TOM.vshost.exe
  Version de l’application: 10.0.30319.1
  Horodatage de l’application:  4ba2084b
  Nom du module par défaut: ntdll.dll
  Version du module par défaut: 6.1.7600.16695
  Horodateur du module par défaut:  4cc7ab44
  Code de l’exception:  c0000008
  Décalage de l’exception:  0004631f
  Version du système:   6.1.7600.2.0.0.256.48
  Identificateur de paramètres régionaux:   4108
  Information supplémentaire n° 1:  ffb6
  Information supplémentaire n° 2:  ffb61531feaa1f65f528a2694a510c22
  Information supplémentaire n° 3:  b220
  Information supplémentaire n° 4:  b2205da238309b0a025a25162a3a18f3

My code is:

OpenFileDialog ofd = new OpenFileDialog {Filter = Filters};
if (ofd.ShowDialog() != true) {
    return;
}

it crash just when I'm in the ofd.ShowDialog.

Is this a code related issue?

Do you have any idea about how to debug? Or even how to debug this??

When activating the "unmanaged code to be debug", I got this:

"First-chance exception at 0x77cd631f in TOM.exe: 0xC0000008: An invalid handle was specified."

The stack trace if it could help:

>   ntdll.dll!77cd631f()
    [Frames below may be incorrect and/or missing, no symbols loaded for ntdll.dll]
    ntdll.dll!77d1792d()
    ntdll.dll!77ce343b()
    ntdll.dll!77ce2d80()
    ole32.dll!776b4102()
    ole32.dll!776b411e()
    ole32.dll!7767e505()
    SearchFolder.dll!1046b49d()
    SearchFolder.dll!1046b267()
    shell32.dll!76281cb7()
    shell32.dll!761701b6()
    shell32.dll!761991fd()
    shell32.dll!761d61ee()
    shell32.dll!761d6159()
    System.ni.dll!524c4ed4()
    shlwapi.dll!77b6b6cf()
    ntdll.dll!77cbb428()
    ntdll.dll!77cbe6f9()
    kernel32.dll!77c01114()
    ntdll.dll!77ceb429()
    ntdll.dll!77ceb3fc()

Some things I've tried:

An important new point:  It seems that the error doesn't happen when I run it without visual studio(which seems to be logic)

Important point bis: It seems the same code is working in visual studio of another computer(which is exactly the same and issued of the same image of windows

I tried to remove all files and do a GetLatest, but still doesn't work


问:
Let's Encrypt kubernetes Ingress Controller issuing Fake Certificate
Not Sure why I'm getting Fake certificate, even the certificate is properly issued by Let's Encrypt using certmanager

The setup is running on the Alibaba Cloud ECS console, where one Kube-master and one cube-minion form a Kubernetes cluster.

Service Details

```<code>root@kube-master:~# kubectl get svc
NAME         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)   AGE
kubernetes   ClusterIP   10.96.0.1        <none>        443/TCP   3h20m
my-nginx     ClusterIP   10.101.150.247   <none>        80/TCP    77m
</code>```

Pod Details

```<code>root@kube-master:~# kubectl get pods --show-labels
NAME                        READY   STATUS    RESTARTS   AGE   LABELS
my-nginx-6cc48cd8db-n6scm   1/1     Running   0          46s   app=my-nginx,pod-template-hash=6cc48cd8db
</code>```

Helm Cert-manager deployed

```<code>root@kube-master:~# helm ls
NAME            REVISION    UPDATED                     STATUS      CHART               APP VERSION NAMESPACE
cert-manager    1           Tue Mar 12 15:29:21 2019    DEPLOYED    cert-manager-v0.5.2 v0.5.2      kube-system
kindred-garfish 1           Tue Mar 12 17:03:41 2019    DEPLOYED    nginx-ingress-1.3.1 0.22.0      kube-system
</code>```

Certificate Issued Properly

```<code>root@kube-master:~# kubectl describe certs
Name:         tls-prod-cert
Namespace:    default
Labels:       <none>
Annotations:  <none>
API Version:  certmanager.k8s.io/v1alpha1
Kind:         Certificate
Metadata:
  Creation Timestamp:  2019-03-12T10:26:58Z
  Generation:          2
  Owner References:
    API Version:           extensions/v1beta1
    Block Owner Deletion:  true
    Controller:            true
    Kind:                  Ingress
    Name:                  nginx-ingress-prod
    UID:                   5ab11929-44b1-11e9-b431-00163e005d19
  Resource Version:        17687
  Self Link:               /apis/certmanager.k8s.io/v1alpha1/namespaces/default/certificates/tls-prod-cert
  UID:                     5dad4740-44b1-11e9-b431-00163e005d19
Spec:
  Acme:
    Config:
      Domains:
        zariga.com
      Http 01:
        Ingress:
        Ingress Class:  nginx
  Dns Names:
    zariga.com
  Issuer Ref:
    Kind:       ClusterIssuer
    Name:       letsencrypt-prod
  Secret Name:  tls-prod-cert
Status:
  Acme:
    Order:
      URL:  https://acme-v02.api.letsencrypt.org/acme/order/53135536/352104603
  Conditions:
    Last Transition Time:  2019-03-12T10:27:00Z
    Message:               Order validated
    Reason:                OrderValidated
    Status:                False
    Type:                  ValidateFailed
    Last Transition Time:  <nil>
    Message:               Certificate issued successfully
    Reason:                CertIssued
    Status:                True
    Type:                  Ready
Events:
  Type    Reason        Age   From          Message
  ----    ------        ----  ----          -------
  Normal  CreateOrder   27s   cert-manager  Created new ACME order, attempting validation...
  Normal  IssueCert     27s   cert-manager  Issuing certificate...
  Normal  CertObtained  25s   cert-manager  Obtained certificate from ACME server
  Normal  CertIssued    25s   cert-manager  Certificate issued successfully
</code>```

Ingress Details

```<code>root@kube-master:~# kubectl describe ingress
Name:             nginx-ingress-prod
Namespace:        default
Address:
Default backend:  my-nginx:80 (192.168.123.202:80)
TLS:
  tls-prod-cert terminates zariga.com
Rules:
  Host  Path  Backends
  ----  ----  --------
  *     *     my-nginx:80 (192.168.123.202:80)
Annotations:
  kubernetes.io/ingress.class:        nginx
  kubernetes.io/tls-acme:             true
  certmanager.k8s.io/cluster-issuer:  letsencrypt-prod
Events:
  Type    Reason             Age    From                      Message
  ----    ------             ----   ----                      -------
  Normal  CREATE             7m13s  nginx-ingress-controller  Ingress default/nginx-ingress-prod
  Normal  CreateCertificate  7m8s   cert-manager              Successfully created Certificate "tls-prod-cert"
  Normal  UPDATE             6m57s  nginx-ingress-controller  Ingress default/nginx-ingress-prod
</code>```

Letsencrypt Nginx Production Definition

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: nginx-ingress-prod
  annotations:
    kubernetes.io/ingress.class: nginx
    certmanager.k8s.io/cluster-issuer: letsencrypt-prod
    kubernetes.io/tls-acme: 'true'
  labels:
    app: 'my-nginx'
spec:
  backend:
    serviceName: my-nginx
    servicePort: 80
  tls:
  - secretName: tls-prod-cert
    hosts:
    - zariga.com
</code>```

答: For me, the issue was that I forgot to kubectl apply the secret (in my case 'tls-secret.yml'). When deploying K8S manually, such an error is rarely made. However, I'm using gitlab CICD to deploy applications, and I forgot to add - kubectl apply -f ./kube/secret to my .gitlab-ci.yml.

Body:
Not Sure why I'm getting Fake certificate, even the certificate is properly issued by Let's Encrypt using certmanager

The setup is running on the Alibaba Cloud ECS console, where one Kube-master and one cube-minion form a Kubernetes cluster.

Service Details

root@kube-master:~# kubectl get svc
NAME         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)   AGE
kubernetes   ClusterIP   10.96.0.1        <none>        443/TCP   3h20m
my-nginx     ClusterIP   10.101.150.247   <none>        80/TCP    77m

Pod Details

root@kube-master:~# kubectl get pods --show-labels
NAME                        READY   STATUS    RESTARTS   AGE   LABELS
my-nginx-6cc48cd8db-n6scm   1/1     Running   0          46s   app=my-nginx,pod-template-hash=6cc48cd8db

Helm Cert-manager deployed

root@kube-master:~# helm ls
NAME            REVISION    UPDATED                     STATUS      CHART               APP VERSION NAMESPACE
cert-manager    1           Tue Mar 12 15:29:21 2019    DEPLOYED    cert-manager-v0.5.2 v0.5.2      kube-system
kindred-garfish 1           Tue Mar 12 17:03:41 2019    DEPLOYED    nginx-ingress-1.3.1 0.22.0      kube-system

Certificate Issued Properly

root@kube-master:~# kubectl describe certs
Name:         tls-prod-cert
Namespace:    default
Labels:       <none>
Annotations:  <none>
API Version:  certmanager.k8s.io/v1alpha1
Kind:         Certificate
Metadata:
  Creation Timestamp:  2019-03-12T10:26:58Z
  Generation:          2
  Owner References:
    API Version:           extensions/v1beta1
    Block Owner Deletion:  true
    Controller:            true
    Kind:                  Ingress
    Name:                  nginx-ingress-prod
    UID:                   5ab11929-44b1-11e9-b431-00163e005d19
  Resource Version:        17687
  Self Link:               /apis/certmanager.k8s.io/v1alpha1/namespaces/default/certificates/tls-prod-cert
  UID:                     5dad4740-44b1-11e9-b431-00163e005d19
Spec:
  Acme:
    Config:
      Domains:
        zariga.com
      Http 01:
        Ingress:
        Ingress Class:  nginx
  Dns Names:
    zariga.com
  Issuer Ref:
    Kind:       ClusterIssuer
    Name:       letsencrypt-prod
  Secret Name:  tls-prod-cert
Status:
  Acme:
    Order:
      URL:  https://acme-v02.api.letsencrypt.org/acme/order/53135536/352104603
  Conditions:
    Last Transition Time:  2019-03-12T10:27:00Z
    Message:               Order validated
    Reason:                OrderValidated
    Status:                False
    Type:                  ValidateFailed
    Last Transition Time:  <nil>
    Message:               Certificate issued successfully
    Reason:                CertIssued
    Status:                True
    Type:                  Ready
Events:
  Type    Reason        Age   From          Message
  ----    ------        ----  ----          -------
  Normal  CreateOrder   27s   cert-manager  Created new ACME order, attempting validation...
  Normal  IssueCert     27s   cert-manager  Issuing certificate...
  Normal  CertObtained  25s   cert-manager  Obtained certificate from ACME server
  Normal  CertIssued    25s   cert-manager  Certificate issued successfully

Ingress Details

root@kube-master:~# kubectl describe ingress
Name:             nginx-ingress-prod
Namespace:        default
Address:
Default backend:  my-nginx:80 (192.168.123.202:80)
TLS:
  tls-prod-cert terminates zariga.com
Rules:
  Host  Path  Backends
  ----  ----  --------
  *     *     my-nginx:80 (192.168.123.202:80)
Annotations:
  kubernetes.io/ingress.class:        nginx
  kubernetes.io/tls-acme:             true
  certmanager.k8s.io/cluster-issuer:  letsencrypt-prod
Events:
  Type    Reason             Age    From                      Message
  ----    ------             ----   ----                      -------
  Normal  CREATE             7m13s  nginx-ingress-controller  Ingress default/nginx-ingress-prod
  Normal  CreateCertificate  7m8s   cert-manager              Successfully created Certificate "tls-prod-cert"
  Normal  UPDATE             6m57s  nginx-ingress-controller  Ingress default/nginx-ingress-prod

Letsencrypt Nginx Production Definition

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: nginx-ingress-prod
  annotations:
    kubernetes.io/ingress.class: nginx
    certmanager.k8s.io/cluster-issuer: letsencrypt-prod
    kubernetes.io/tls-acme: 'true'
  labels:
    app: 'my-nginx'
spec:
  backend:
    serviceName: my-nginx
    servicePort: 80
  tls:
  - secretName: tls-prod-cert
    hosts:
    - zariga.com