问:
How to restrict props.children in react typescript?
```<code>import React from 'react';
import './App.css';
import Message from "./components/Message";

function App() {
    return (
        <div className="App">
            <Message>
                <p>Hello World</p>
            </Message>
            <Message>
                <a>Hello World</a>
            </Message>
            <Message>
                <button>Hello World</button>
            </Message>
        </div>
    );
}

export default App;

</code>```
```<code>import React, {FunctionComponent} from 'react';

interface OwnProps {
    children: React.ReactElement<HTMLParagraphElement>;
}

type Props = OwnProps;

const Message: FunctionComponent<Props> = ({children}) => {

    return (
        <h1>
            {children}
        </h1>
    );
};

export default Message;

</code>```

The above code I can pass any HTMLElementTag as props.

Is there any way to restrict ReactElement to only specific element ?
For example only with p tag or button tag etc.

答:
you can use following for static checking:</p>
```<code>type Props = { children: React.ReactNode } //-- allow any React valid Node
// type Props = { children: never } //-- will not allow children to be passed
</code>```

Body:
import React from 'react';
import './App.css';
import Message from "./components/Message";

function App() {
    return (

            <Message>

Hello World

            </Message>
            <Message>
                Hello World
            </Message>
            <Message>
                <button>Hello World</button>
            </Message>

    );
}

export default App;

import React, {FunctionComponent} from 'react';

interface OwnProps {
    children: React.ReactElement<HTMLParagraphElement>;
}

type Props = OwnProps;

const Message: FunctionComponent<Props> = ({children}) => {

    return (

            {children}

    );
};

export default Message;

The above code I can pass any HTMLElementTag as props.

Is there any way to restrict ReactElement to only specific element ?
For example only with p tag or button tag etc.

Body:
you can use following for static checking:

type Props = { children: React.ReactNode } //-- allow any React valid Node
// type Props = { children: never } //-- will not allow children to be passed


来源: stackexchange

问:
Updating time of postgres indexes
I was wondering about the performance of indexes in PostgreSQL. I was mining in the web articles trying to figure out how to check the updating time of an index. I thought Postgres could have some direct construct. The scenario is: there are 4 semesters of sales periodically inserted into a table which has an index on the pk column; I would take the time for updating that index in each semester.</p>

答:
Indexes are always updated automatically, right when you modify the data. There is nothing extra you have to do, and there is nothing you can do to influence that process (for example, suspend index maintenance and do it later).

To preempt comments that criticize “there is nothing you can do to influence that process”: yes, GIN indexes have a “pending list”, whose existence and size you can configure.

ContentLicense: CC BY-SA 4.0

Title: Updating time of postgres indexes


问:
Try to access data array in foreach
I'm trying to access the "links" data in my array so I can then access the data "link" and "name"

But when I try to access it by any means, this is what it returns

Error: Invalid argument supplied for foreach()

I don't understand why it returns this to me, I'm trying to access an array, it should work

Code :

```<code>@foreach ($menu_categories as $menuCat)
    @foreach ( $menuCat as $item)
      @foreach ( $item as $link )
        {{ $item }}
    @endforeach
@endforeach
</code>```

$menuCat result :

```<code>Array
    (
    [id] => 4
    [name] => Batîment / Site
    [links] => Array
        (
            [0] => Array
                (
                    [link] => http://accessi-website-2021.test/
                    [name] => Centre de formation
                )

            [1] => Array
                (
                    [link] => http://accessi-website-2021.test/
                    [name] => Centre de vaccination
                )

            [2] => Array
                (
                    [link] => http://accessi-website-2021.test/
                    [name] => Centre sportif
                )

            [3] => Array
                (
                    [link] => http://accessi-website-2021.test/
                    [name] => Infrasctructure touristique
                )

            [4] => Array
                (
                    [link] => http://accessi-website-2021.test/
                    [name] => Logement
                )

            [5] => Array
                (
                    [link] => http://accessi-website-2021.test/
                    [name] => Piscine
                )

        )

    )
</code>```

答:
You are attempting to iterate non-iterable entries in the second loop.

The first loop's iteration is correct, but the secodnd iteration is also iterating [id] and [name] entries.

Your loop should look like this:

```<code>@foreach ($menu_categories as $menuCat)
    @foreach ( $menuCat['links'] as $item)
      @foreach ( $item as $link )
        {{ $item }}
      @endforeach
    @endforeach
@endforeach
</code>```

Also, you don't need to use the third foreach loop - you can access those properties via $link['link'] and $link['name'] - if that's what you need.

Title: Try to access data array in foreach

Body:
I'm trying to access the "links" data in my array so I can then access the data "link" and "name"

But when I try to access it by any means, this is what it returns

Error: Invalid argument supplied for foreach()

I don't understand why it returns this to me, I'm trying to access an array, it should work

Code :

@foreach ($menu_categories as $menuCat)
    @foreach ( $menuCat as $item)
      @foreach ( $item as $link )
        {{ $item }}
    @endforeach
@endforeach

$menuCat result :

Array
    (
    [id] => 4
    [name] => Batîment / Site
    [links] => Array
        (
            [0] => Array
                (
                    [link] => http://accessi-website-2021.test/
                    [name] => Centre de formation
                )

            [1] => Array
                (
                    [link] => http://accessi-website-2021.test/
                    [name] => Centre de vaccination
                )

            [2] => Array
                (
                    [link] => http://accessi-website-2021.test/
                    [name] => Centre sportif
                )

            [3] => Array
                (
                    [link] => http://accessi-website-2021.test/
                    [name] => Infrasctructure touristique
                )

            [4] => Array
                (
                    [link] => http://accessi-website-2021.test/
                    [name] => Logement
                )

            [5] => Array
                (
                    [link] => http://accessi-website-2021.test/
                    [name] => Piscine
                )

        )

    )

Body:
You are attempting to iterate non-iterable entries in the second loop.

The first loop's iteration is correct, but the secodnd iteration is also iterating [id] and [name] entries.

Your loop should look like this:

@foreach ($menu_categories as $menuCat)
    @foreach ( $menuCat['links'] as $item)
      @foreach ( $item as $link )
        {{ $item }}
      @endforeach
    @endforeach
@endforeach

Also, you don't need to use the third foreach loop - you can access those properties via $link['link'] and $link['name'] - if that's what you need.


问:
Whitespace and overlapping legends in ggplot2 multi-plot-arrangement
So I have several plots I would like to arrange together with their legends and these legends should be in the bottom row and only once per plot type (check the reprex below, its not so easy to verbalize :-/).

reprex pt1: make plots and get legends

```<code>library(ggplot2)
library(gridExtra)
data(iris)

### make some plots

small.1<-ggplot(iris)+
  geom_point(aes(x=Sepal.Length, y=Sepal.Width, color=Species, size=Petal.Width))+
  theme(legend.position="none")

small.2<-ggplot(iris)+
  geom_point(aes(x=Petal.Length, y=Petal.Width, color=Species, size=Petal.Length))+
  theme(legend.position="none")

big<-ggplot(iris)+
  geom_boxplot(aes(x=Species, y=Sepal.Length*Petal.Length, fill=Species))+
  theme(legend.position="none")

### get the legneds

small.leg<-get_legend(small.1+theme(legend.position="bottom")+guides(color=guide_legend(title.positon="top")))

big.leg<-get_legend(big+theme(legend.position="bottom")+guides(fill=guide_legend(title.positon="top")))

</code>```

Then I arranged them into a matrix with marrangeGrob. I tried various versions with plot_grid but that turns out horribly bc. I have to specify rel_heights/widths and the legends don't really align...

reprex pt2 marrangeGrob

```<code>### make a layout matrix
layout_mat<-rbind(c(1,2,2),
                  c(3,2,2),
                  c(4,NA,5))

### combine plots into list (list order like order in matrix)
iris.list<-list(small.1, big, small.2, small.leg, big.leg)

### arrange
iris.arrange<-marrangeGrob(iris.list, layout_matrix=layout_mat)
</code>```

Q: How do I get rid of the whitespace between plots and legends?

答:
I don't know how to reduce the whitespace with the marrangeGrob() method. However, using the {patchwork} package, the spacing seems sensible. Like the marrangeGrob() method the space is too small to display all legends though.

library(ggplot2)
library(patchwork)

small.1<-ggplot(iris)+
  geom_point(aes(x=Sepal.Length, y=Sepal.Width, color=Species, size=Petal.Width))

small.2<-ggplot(iris)+
  geom_point(aes(x=Petal.Length, y=Petal.Width, color=Species, size=Petal.Length))

big<-ggplot(iris)+
  geom_boxplot(aes(x=Species, y=Sepal.Length*Petal.Length, fill=Species))

((small.1 / small.2) | big) + plot_layout(guides = "collect") &
  theme(legend.position = "bottom")
```

Created on 2022-02-09 by the reprex package (v2.0.1)

Body:
So I have several plots I would like to arrange together with their legends and these legends should be in the bottom row and only once per plot type (check the reprex below, its not so easy to verbalize :-/).

reprex pt1: make plots and get legends

library(ggplot2)
library(gridExtra)
data(iris)

### make some plots

small.1<-ggplot(iris)+
  geom_point(aes(x=Sepal.Length, y=Sepal.Width, color=Species, size=Petal.Width))+
  theme(legend.position="none")

small.2<-ggplot(iris)+
  geom_point(aes(x=Petal.Length, y=Petal.Width, color=Species, size=Petal.Length))+
  theme(legend.position="none")

big<-ggplot(iris)+
  geom_boxplot(aes(x=Species, y=Sepal.Length*Petal.Length, fill=Species))+
  theme(legend.position="none")

### get the legneds

small.leg<-get_legend(small.1+theme(legend.position="bottom")+guides(color=guide_legend(title.positon="top")))

big.leg<-get_legend(big+theme(legend.position="bottom")+guides(fill=guide_legend(title.positon="top")))

Then I arranged them into a matrix with marrangeGrob. I tried various versions with plot_grid but that turns out horribly bc. I have to specify rel_heights/widths and the legends don't really align...

reprex pt2 marrangeGrob

### make a layout matrix
layout_mat<-rbind(c(1,2,2),
                  c(3,2,2),
                  c(4,NA,5))

### combine plots into list (list order like order in matrix)
iris.list<-list(small.1, big, small.2, small.leg, big.leg)

### arrange
iris.arrange<-marrangeGrob(iris.list, layout_matrix=layout_mat)

Q: How do I get rid of the whitespace between plots and legends?

Body:
I don't know how to reduce the whitespace with the marrangeGrob() method. However, using the {patchwork} package, the spacing seems sensible. Like the marrangeGrob() method the space is too small to display all legends though.

library(ggplot2)
library(patchwork)

small.1<-ggplot(iris)+
  geom_point(aes(x=Sepal.Length, y=Sepal.Width, color=Species, size=Petal.Width))

small.2<-ggplot(iris)+
  geom_point(aes(x=Petal.Length, y=Petal.Width, color=Species, size=Petal.Length))

big<-ggplot(iris)+
  geom_boxplot(aes(x=Species, y=Sepal.Length*Petal.Length, fill=Species))

((small.1 / small.2) | big) + plot_layout(guides = "collect") &
  theme(legend.position = "bottom")

Created on 2022-02-09 by the reprex package (v2.0.1)


问:
Load testing kafka with multiple producers and multiple consumers
I am trying to load test my Kafka cluster with multiple producers and multiple consumers. I came across a lot of available tools and article but all of them generates load(Producer) from a single machine and similarly reads(Consumer) from a single machine.

I am looking for a tool which can be deployed across/spawn multiple producers and consumers and load test a given kafka cluster.

As input, we can give the number of producers and consumers.

It can then spawn those number of machines with producers and consumers (On AWS, Azure or GCP). Or we can spawn machines manually and then the tool can initiate producer and consumer on them.

Post that it load test's the target kafka cluster.

At the end, it gives out test results like, write/sec, read/sec etc.

Tools/Articles I checked are:

https://www.blazemeter.com/blog/apache-kafka-how-to-load-test-with-jmeter

https://medium.com/selectstarfromweb/lets-load-test-kafka-f90b71758afb

Load testing with Kafka and Storm

Load test kafka consumer

Load testing a kafka consumer

答:
The very first article neither mentions nor assumes any limitations regarding the number of consumers/producers.

Just put the Samplers for different Kafka instances (or different topics or whatever is your test scenario) under different JMeter Thread Groups and you will be able to concurrently stress multiple endpoints.

If you prefer doing it from different machines - you can run JMeter in distributed mode and point different JMeter slave machines to stress different endpoints using If Controller and __machineName() or __machineIP() functions combination.


问:
Prevent 503 Error when scraping Google Scholar
I have written the following code to scrape data from Google Scholar security page.. However, whenever I run it I receive this error:

```<code> Traceback (most recent call last):
  File "/Users/.../Documents/GS_Tag_Scraper/scrape-modified.py", line 53, in <module>
    getProfileFromTag(each)
  File "/Users/.../Documents/GS_Tag_Scraper/scrape-modified.py", line 32, in getProfileFromTag
    page = urllib.request.urlopen(url)
  File "/Users/.../anaconda/lib/python3.5/urllib/request.py", line 163, in urlopen
    return opener.open(url, data, timeout)
  File "/Users/.../anaconda/lib/python3.5/urllib/request.py", line 472, in open
    response = meth(req, response)
  File "/Users/.../anaconda/lib/python3.5/urllib/request.py", line 582, in http_response
    'http', request, response, code, msg, hdrs)
  File "/Users/.../anaconda/lib/python3.5/urllib/request.py", line 504, in error
    result = self._call_chain(*args)
  File "/Users/.../anaconda/lib/python3.5/urllib/request.py", line 444, in _call_chain
    result = func(*args)
  File "/Users/.../anaconda/lib/python3.5/urllib/request.py", line 696, in http_error_302
    return self.parent.open(new, timeout=req.timeout)
  File "/Users/.../anaconda/lib/python3.5/urllib/request.py", line 472, in open
    response = meth(req, response)
  File "/Users/.../anaconda/lib/python3.5/urllib/request.py", line 582, in http_response
    'http', request, response, code, msg, hdrs)
  File "/Users/.../anaconda/lib/python3.5/urllib/request.py", line 510, in error
    return self._call_chain(*args)
  File "/Users/.../anaconda/lib/python3.5/urllib/request.py", line 444, in _call_chain
    result = func(*args)
  File "/Users/.../anaconda/lib/python3.5/urllib/request.py", line 590, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 503: Service Unavailable
</code>```

I presume this is because GS is blocking my requests. How can I prevent this?

The code is:

```<code># -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
import urllib.request
import string
import csv
import time

#Declares array's to store data
name = []
urlList =[]

#Opens and writer header of CSV file
outputFile = open('sample.csv', 'w', newline='')
outputWriter = csv.writer(outputFile)
outputWriter.writerow(['Name', 'URL', 'Total Citations', 'h-index', 'i10-index'])

def getStat (url):
    #Given an authors URL it retunrs an array of stats.
    url = 'https://scholar.google.pl' + url
    page = urllib.request.urlopen(url)
    soup = BeautifulSoup(page, 'lxml')
    buttons = soup.findAll("td", { "class" : "gsc_rsb_std" })
    list=[]
    return (list)

def getProfileFromTag(tag):
    url = "http://scholar.google.pl/citations?view_op=search_authors&hl=pl&mauthors=label:" + tag
    while True:
        page = urllib.request.urlopen(url)
        soup = BeautifulSoup(page, 'lxml')

        mydivs = BeautifulSoup(urllib.request.urlopen(url), 'lxml').findAll("h3", { "class" : "gsc_1usr_name"})
        for each in mydivs:
            for anchor in each.find_all('a'):
                name.append(anchor.text)
                urlList.append(anchor['href'])
                time.sleep(0.001)
        buttons = soup.findAll("button", {"aria-label": "Następna"})
        if not buttons:
            break
        on_click = buttons[0].get('onclick')
        url = 'http://scholar.google.pl' + on_click[17:-1]
        url = url.encode('utf-8').decode('unicode_escape')
    for each in name:
        list = getStat(urlList[i])
        outputWriter.writerow([each, urlList[i], list[0], list[2], list[4]])

tags = ['security']
for each in tags:
    getProfileFromTag(each)
</code>```

答:
I assume you tried to parse the next page token. However, if not, it's because you didn't provide a next page token ID to the request once it's parsed. Or you hit the IP rate limit or get a CAPTCHA. Request headers unfortunately aren't enough.

The ideal solution besides passing the next page token is to use proxies with CAPTCHA solving service.

Code and example in the online IDE:

from bs4 import BeautifulSoup
import requests, lxml, re

def scrape_all_authors():
    params = {
        "view_op": "search_authors",
        "mauthors": "blizzard",
        "hl": "en",
        "astart": 0
    }

    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3538.102 Safari/537.36 Edge/18.19582",
    }

    authors_is_present = True
    while authors_is_present:

        html = requests.get("https://scholar.google.com/citations", params=params, headers=headers, timeout=30)
        soup = BeautifulSoup(html.text, "lxml")

        for author in soup.select(".gs_ai_chpr"):
            name = author.select_one(".gs_ai_name a").text
            link = f'https://scholar.google.com{author.select_one(".gs_ai_name a")["href"]}'
            affiliations = author.select_one(".gs_ai_aff").text
            email = author.select_one(".gs_ai_eml").text
            try:
                cited_by = re.search(r"\d+", author.select_one(".gs_ai_cby").text).group() # Cited by 17143 -> 17143
            except: cited_by = None

            print(f"extracting authors at page #{params['astart']}.",
                  name,
                  link,
                  affiliations,
                  email,
                  cited_by, sep="\n")

        # if next page token
        if soup.select_one("button.gs_btnPR")["onclick"]:
            params["after_author"] = re.search(r"after_author\\x3d(.*)\\x26", str(soup.select_one("button.gs_btnPR")["onclick"])).group(1)  # -> XB0HAMS9__8J
            params["astart"] += 10
        else:
            authors_is_present = False

scrape_all_authors()

# output:
'''
extracting authors at page #0.
Johnson Thomas
https://scholar.google.com/citations?hl=en&user=eKLr0EgAAAAJ
Professor of Computer Science, Oklahoma State University
Verified email at cs.okstate.edu
159469
...

extracting authors at page #60.
Bulent Sankur
https://scholar.google.com/citations?hl=en&user=z9FUD8QAAAAJ
Professor of Electrical and Electronics Engineering, Bogazici University
Verified email at boun.edu.tr
16953
'''
```
<hr />
<p>Alternatively, you can achieve the same thing using Google Scholar Profiles API from SerpApi. It's a paid API with a free plan.</p>
<p>The difference is that you only need to iterate through the received dictionary and grab the data you want without the need to figure out how to scale the number of requests, how to bypass blocks from search engines.</p>
<p>Example code to integrate:</p>
<pre class="lang-py prettyprint-override"><code>from serpapi import GoogleSearch
import os, json
from urllib.parse import urlsplit, parse_qsl

def serpapi_scrape_all_authors():
    params = {
        "api_key": os.getenv("API_KEY"),      # SerpApi API key
        "engine": "google_scholar_profiles",  # profile results search engine
        "mauthors": "blizzard",               # search query
    }
    search = GoogleSearch(params)

    profile_results_data = []

    profiles_is_present = True
    while profiles_is_present:
        profile_results = search.get_dict()

        for profile in profile_results["profiles"]:

            print(f'Currently extracting {profile["name"]} with {profile["author_id"]} ID.')

            thumbnail = profile["thumbnail"]
            name = profile["name"]
            link = profile["link"]
            author_id = profile["author_id"]
            affiliations = profile["affiliations"]
            email = profile.get("email")
            cited_by = profile.get("cited_by")
            interests = profile.get("interests")

            profile_results_data.append({
                "thumbnail": thumbnail,
                "name": name,
                "link": link,
                "author_id": author_id,
                "email": email,
                "affiliations": affiliations,
                "cited_by": cited_by,
                "interests": interests
            })

            if "next" in profile_results["pagination"]:
                # split URL in parts as a dict() and update search "params" variable to a new page
                search.params_dict.update(dict(parse_qsl(urlsplit(profile_results["pagination"]["next"]).query)))
            else:
                profiles_is_present = False

    return profile_results_data

print(json.dumps(serpapi_scrape_all_authors(), indent=2))

# output:
'''
Currently extracting Adam Lobel with _xwYD2sAAAAJ ID.
...
Currently extracting Vladimir Ivanov with rddjbZcAAAAJ ID.

[
  {
    "thumbnail": "https://scholar.googleusercontent.com/citations?view_op=small_photo&user=_xwYD2sAAAAJ&citpid=3",
    "name": "Adam Lobel",
    "link": "https://scholar.google.com/citations?hl=en&user=_xwYD2sAAAAJ",
    "author_id": "_xwYD2sAAAAJ",
    "email": "Verified email at AdamLobel.com",
    "affiliations": "Blizzard Entertainment",
    "cited_by": 2980,
    "interests": [
      {
        "title": "Gaming",
        "serpapi_link": "https://serpapi.com/search.json?engine=google_scholar_profiles&hl=en&mauthors=label%3Agaming",
        "link": "https://scholar.google.com/citations?hl=en&view_op=search_authors&mauthors=label:gaming"
      },
      {
        "title": "Emotion regulation",
        "serpapi_link": "https://serpapi.com/search.json?engine=google_scholar_profiles&hl=en&mauthors=label%3Aemotion_regulation",
        "link": "https://scholar.google.com/citations?hl=en&view_op=search_authors&mauthors=label:emotion_regulation"
      }
    ]
  } ... other results
  {
    "thumbnail": "https://scholar.google.com/citations/images/avatar_scholar_56.png",
    "name": "Vladimir Ivanov",
    "link": "https://scholar.google.com/citations?hl=en&user=rddjbZcAAAAJ",
    "author_id": "rddjbZcAAAAJ",
    "email": null,
    "affiliations": "Blizzard Entertainment",
    "cited_by": null,
    "interests": [
      {
        "title": "Machine Learning",
        "serpapi_link": "https://serpapi.com/search.json?after_author=V8JcAPb___8J&engine=google_scholar_profiles&hl=en&mauthors=label%3Amachine_learning",
        "link": "https://scholar.google.com/citations?hl=en&view_op=search_authors&mauthors=label:machine_learning"
      },
      {
        "title": "Reinforcement Learning",
        "serpapi_link": "https://serpapi.com/search.json?after_author=V8JcAPb___8J&engine=google_scholar_profiles&hl=en&mauthors=label%3Areinforcement_learning",
        "link": "https://scholar.google.com/citations?hl=en&view_op=search_authors&mauthors=label:reinforcement_learning"
      },
      {
        "title": "Computer Vision",
        "serpapi_link": "https://serpapi.com/search.json?after_author=V8JcAPb___8J&engine=google_scholar_profiles&hl=en&mauthors=label%3Acomputer_vision",
        "link": "https://scholar.google.com/citations?hl=en&view_op=search_authors&mauthors=label:computer_vision"
      },
      {
        "title": "Cinematics",
        "serpapi_link": "https://serpapi.com/search.json?after_author=V8JcAPb___8J&engine=google_scholar_profiles&hl=en&mauthors=label%3Acinematics",
        "link": "https://scholar.google.com/citations?hl=en&view_op=search_authors&mauthors=label:cinematics"
      }
    ]
  }
]
'''
</code>```

If you would like to parse historic organic results from Google Scholar, there is a dedicated blog post Scrape historic Google Scholar results using Python of mine.

Disclaimer, I work for SerpApi.

ContentLicense: CC BY-SA 3.0

Body:
I have written the following code to scrape data from Google Scholar security page.. However, whenever I run it I receive this error:

 Traceback (most recent call last):
  File "/Users/.../Documents/GS_Tag_Scraper/scrape-modified.py", line 53, in <module>
    getProfileFromTag(each)
  File "/Users/.../Documents/GS_Tag_Scraper/scrape-modified.py", line 32, in getProfileFromTag
    page = urllib.request.urlopen(url)
  File "/Users/.../anaconda/lib/python3.5/urllib/request.py", line 163, in urlopen
    return opener.open(url, data, timeout)
  File "/Users/.../anaconda/lib/python3.5/urllib/request.py", line 472, in open
    response = meth(req, response)
  File "/Users/.../anaconda/lib/python3.5/urllib/request.py", line 582, in http_response
    'http', request, response, code, msg, hdrs)
  File "/Users/.../anaconda/lib/python3.5/urllib/request.py", line 504, in error
    result = self._call_chain(*args)
  File "/Users/.../anaconda/lib/python3.5/urllib/request.py", line 444, in _call_chain
    result = func(*args)
  File "/Users/.../anaconda/lib/python3.5/urllib/request.py", line 696, in http_error_302
    return self.parent.open(new, timeout=req.timeout)
  File "/Users/.../anaconda/lib/python3.5/urllib/request.py", line 472, in open
    response = meth(req, response)
  File "/Users/.../anaconda/lib/python3.5/urllib/request.py", line 582, in http_response
    'http', request, response, code, msg, hdrs)
  File "/Users/.../anaconda/lib/python3.5/urllib/request.py", line 510, in error
    return self._call_chain(*args)
  File "/Users/.../anaconda/lib/python3.5/urllib/request.py", line 444, in _call_chain
    result = func(*args)
  File "/Users/.../anaconda/lib/python3.5/urllib/request.py", line 590, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 503: Service Unavailable

I presume this is because GS is blocking my requests. How can I prevent this?

The code is:

# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
import urllib.request
import string
import csv
import time

#Declares array's to store data
name = []
urlList =[]

#Opens and writer header of CSV file
outputFile = open('sample.csv', 'w', newline='')
outputWriter = csv.writer(outputFile)
outputWriter.writerow(['Name', 'URL', 'Total Citations', 'h-index', 'i10-index'])

def getStat (url):
    #Given an authors URL it retunrs an array of stats.
    url = 'https://scholar.google.pl' + url
    page = urllib.request.urlopen(url)
    soup = BeautifulSoup(page, 'lxml')
    buttons = soup.findAll("td", { "class" : "gsc_rsb_std" })
    list=[]
    return (list)

def getProfileFromTag(tag):
    url = "http://scholar.google.pl/citations?view_op=search_authors&hl=pl&mauthors=label:" + tag
    while True:
        page = urllib.request.urlopen(url)
        soup = BeautifulSoup(page, 'lxml')

        mydivs = BeautifulSoup(urllib.request.urlopen(url), 'lxml').findAll("h3", { "class" : "gsc_1usr_name"})
        for each in mydivs:
            for anchor in each.find_all('a'):
                name.append(anchor.text)
                urlList.append(anchor['href'])
                time.sleep(0.001)
        buttons = soup.findAll("button", {"aria-label": "Następna"})
        if not buttons:
            break
        on_click = buttons[0].get('onclick')
        url = 'http://scholar.google.pl' + on_click[17:-1]
        url = url.encode('utf-8').decode('unicode_escape')
    for each in name:
        list = getStat(urlList[i])
        outputWriter.writerow([each, urlList[i], list[0], list[2], list[4]])

tags = ['security']
for each in tags:
    getProfileFromTag(each)

Body:
I assume you tried to parse the next page token. However, if not, it's because you didn't provide a next page token ID to the request once it's parsed. Or you hit the IP rate limit or get a CAPTCHA. Request headers unfortunately aren't enough.

The ideal solution besides passing the next page token is to use proxies with CAPTCHA solving service.

Code and example in the online IDE:

from bs4 import BeautifulSoup
import requests, lxml, re

def scrape_all_authors():
    params = {
        "view_op": "search_authors",
        "mauthors": "blizzard",
        "hl": "en",
        "astart": 0
    }

    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3538.102 Safari/537.36 Edge/18.19582",
    }

    authors_is_present = True
    while authors_is_present:

        html = requests.get("https://scholar.google.com/citations", params=params, headers=headers, timeout=30)
        soup = BeautifulSoup(html.text, "lxml")

        for author in soup.select(".gs_ai_chpr"):
            name = author.select_one(".gs_ai_name a").text
            link = f'https://scholar.google.com{author.select_one(".gs_ai_name a")["href"]}'
            affiliations = author.select_one(".gs_ai_aff").text
            email = author.select_one(".gs_ai_eml").text
            try:
                cited_by = re.search(r"\d+", author.select_one(".gs_ai_cby").text).group() # Cited by 17143 -> 17143
            except: cited_by = None

            print(f"extracting authors at page #{params['astart']}.",
                  name,
                  link,
                  affiliations,
                  email,
                  cited_by, sep="\n")

        # if next page token
        if soup.select_one("button.gs_btnPR")["onclick"]:
            params["after_author"] = re.search(r"after_author\\x3d(.*)\\x26", str(soup.select_one("button.gs_btnPR")["onclick"])).group(1)  # -> XB0HAMS9__8J
            params["astart"] += 10
        else:
            authors_is_present = False

scrape_all_authors()

# output:
'''
extracting authors at page #0.
Johnson Thomas
https://scholar.google.com/citations?hl=en&user=eKLr0EgAAAAJ
Professor of Computer Science, Oklahoma State University
Verified email at cs.okstate.edu
159469
...

extracting authors at page #60.
Bulent Sankur
https://scholar.google.com/citations?hl=en&user=z9FUD8QAAAAJ
Professor of Electrical and Electronics Engineering, Bogazici University
Verified email at boun.edu.tr
16953
'''

Alternatively, you can achieve the same thing using Google Scholar Profiles API from SerpApi. It's a paid API with a free plan.

The difference is that you only need to iterate through the received dictionary and grab the data you want without the need to figure out how to scale the number of requests, how to bypass blocks from search engines.

Example code to integrate:

from serpapi import GoogleSearch
import os, json
from urllib.parse import urlsplit, parse_qsl

def serpapi_scrape_all_authors():
    params = {
        "api_key": os.getenv("API_KEY"),      # SerpApi API key
        "engine": "google_scholar_profiles",  # profile results search engine
        "mauthors": "blizzard",               # search query
    }
    search = GoogleSearch(params)

    profile_results_data = []

    profiles_is_present = True
    while profiles_is_present:
        profile_results = search.get_dict()

        for profile in profile_results["profiles"]:

            print(f'Currently extracting {profile["name"]} with {profile["author_id"]} ID.')

            thumbnail = profile["thumbnail"]
            name = profile["name"]
            link = profile["link"]
            author_id = profile["author_id"]
            affiliations = profile["affiliations"]
            email = profile.get("email")
            cited_by = profile.get("cited_by")
            interests = profile.get("interests")

            profile_results_data.append({
                "thumbnail": thumbnail,
                "name": name,
                "link": link,
                "author_id": author_id,
                "email": email,
                "affiliations": affiliations,
                "cited_by": cited_by,
                "interests": interests
            })

            if "next" in profile_results["pagination"]:
                # split URL in parts as a dict() and update search "params" variable to a new page
                search.params_dict.update(dict(parse_qsl(urlsplit(profile_results["pagination"]["next"]).query)))
            else:
                profiles_is_present = False

    return profile_results_data

print(json.dumps(serpapi_scrape_all_authors(), indent=2))

# output:
'''
Currently extracting Adam Lobel with _xwYD2sAAAAJ ID.
...
Currently extracting Vladimir Ivanov with rddjbZcAAAAJ ID.

[
  {
    "thumbnail": "https://scholar.googleusercontent.com/citations?view_op=small_photo&user=_xwYD2sAAAAJ&citpid=3",
    "name": "Adam Lobel",
    "link": "https://scholar.google.com/citations?hl=en&user=_xwYD2sAAAAJ",
    "author_id": "_xwYD2sAAAAJ",
    "email": "Verified email at AdamLobel.com",
    "affiliations": "Blizzard Entertainment",
    "cited_by": 2980,
    "interests": [
      {
        "title": "Gaming",
        "serpapi_link": "https://serpapi.com/search.json?engine=google_scholar_profiles&hl=en&mauthors=label%3Agaming",
        "link": "https://scholar.google.com/citations?hl=en&view_op=search_authors&mauthors=label:gaming"
      },
      {
        "title": "Emotion regulation",
        "serpapi_link": "https://serpapi.com/search.json?engine=google_scholar_profiles&hl=en&mauthors=label%3Aemotion_regulation",
        "link": "https://scholar.google.com/citations?hl=en&view_op=search_authors&mauthors=label:emotion_regulation"
      }
    ]
  } ... other results
  {
    "thumbnail": "https://scholar.google.com/citations/images/avatar_scholar_56.png",
    "name": "Vladimir Ivanov",
    "link": "https://scholar.google.com/citations?hl=en&user=rddjbZcAAAAJ",
    "author_id": "rddjbZcAAAAJ",
    "email": null,
    "affiliations": "Blizzard Entertainment",
    "cited_by": null,
    "interests": [
      {
        "title": "Machine Learning",
        "serpapi_link": "https://serpapi.com/search.json?after_author=V8JcAPb___8J&engine=google_scholar_profiles&hl=en&mauthors=label%3Amachine_learning",
        "link": "https://scholar.google.com/citations?hl=en&view_op=search_authors&mauthors=label:machine_learning"
      },
      {
        "title": "Reinforcement Learning",
        "serpapi_link": "https://serpapi.com/search.json?after_author=V8JcAPb___8J&engine=google_scholar_profiles&hl=en&mauthors=label%3Areinforcement_learning",
        "link": "https://scholar.google.com/citations?hl=en&view_op=search_authors&mauthors=label:reinforcement_learning"
      },
      {
        "title": "Computer Vision",
        "serpapi_link": "https://serpapi.com/search.json?after_author=V8JcAPb___8J&engine=google_scholar_profiles&hl=en&mauthors=label%3Acomputer_vision",
        "link": "https://scholar.google.com/citations?hl=en&view_op=search_authors&mauthors=label:computer_vision"
      },
      {
        "title": "Cinematics",
        "serpapi_link": "https://serpapi.com/search.json?after_author=V8JcAPb___8J&engine=google_scholar_profiles&hl=en&mauthors=label%3Acinematics",
        "link": "https://scholar.google.com/citations?hl=en&view_op=search_authors&mauthors=label:cinematics"
      }
    ]
  }
]
'''

If you would like to parse historic organic results from Google Scholar, there is a dedicated blog post Scrape historic Google Scholar results using Python of mine.

Disclaimer, I work for SerpApi.


问:
Regex : Find string between brackets after a string
So far my regex is ->

myRegex = /catch *\(.\) */

I want to be able to search the following string -

```<code>try {
print(new Function (astatement)())
} catch (e)  { print(e.stack) }
</code>```

So that if .stack is present after catch(anything) it should return true, so far I have managed to reach the catch(anything), stuck from here.

答:
Matching for {[^}]+}

Matching simple code in the exception handler, provided there are no nested curly braces:

```<code>catch *\((\w+)\) *{[^}]+(\1)(\.stack)[^}]+}
</code>```

The above regular expression matches these examples

(capturing groups for my sake, remove them if not needed):

try {
  print(new Function (astatement)())
} catch (e)  { print(e.stack) }

try {
  print(new Function (bstatement)())
} catch (exception)  { print(exception.stack) }
```
<p>You can try it out here:<br />
https://regex101.com/r/PuytDJ/2</p>
<h3>Some techniques used here</h3>
```\w+
```
<p>Instead of just <code>.</code> I assume you can give the exception instance any name, so maybe more safe to use <code>\w+</code> here.</p>
```{[^}]+
```
<p>This looks for an opening curly brace and catches every non-closing curly brace until the next expression. It works only if you do not have nested curly braces in your exception handler.</p>
```(\1)
```
<p>Here I reference the exception's variable name found in capturing group 1.</p>
```(\.stack)
```
<p>Here is finding <code>.stack</code> literally</p>
```[^}]+}
```

I continue to parse for all non-curly braces characters and finally the closing curly bracket.

Disclaimer

⚠ This being said, regular expressions cannot parse nested elements very well, or only to a certain degree with increasingly more complex expressions.

So code blocks, HTML/XML Tags, JSON objects etc. are better parsed, not text-searched in.

Body:
So far my regex is ->

myRegex = /catch *\(.\) */

I want to be able to search the following string -

try {
print(new Function (astatement)())
} catch (e)  { print(e.stack) }

So that if .stack is present after catch(anything) it should return true, so far I have managed to reach the catch(anything), stuck from here.

Body:
Matching for {[^}]+}

Matching simple code in the exception handler, provided there are no nested curly braces:

catch *\((\w+)\) *{[^}]+(\1)(\.stack)[^}]+}

The above regular expression matches these examples

(capturing groups for my sake, remove them if not needed):

try {
  print(new Function (astatement)())
} catch (e)  { print(e.stack) }

try {
  print(new Function (bstatement)())
} catch (exception)  { print(exception.stack) }

You can try it out here:

https://regex101.com/r/PuytDJ/2

Some techniques used here

\w+

Instead of just . I assume you can give the exception instance any name, so maybe more safe to use \w+ here.

{[^}]+

This looks for an opening curly brace and catches every non-closing curly brace until the next expression. It works only if you do not have nested curly braces in your exception handler.

(\1)

Here I reference the exception's variable name found in capturing group 1.

(\.stack)

Here is finding .stack literally

[^}]+}

I continue to parse for all non-curly braces characters and finally the closing curly bracket.

Disclaimer

⚠ This being said, regular expressions cannot parse nested elements very well, or only to a certain degree with increasingly more complex expressions.

So code blocks, HTML/XML Tags, JSON objects etc. are better parsed, not text-searched in.


问:
Asp.net table display using grid view and deleting one row in the website
I am displaying a table in a grid view in a asp.net webpage. I want the user to select one row in the website and delete it. How can I do that. I have a delete button in the same page, where I will do code behind to drop the row in the database. But my problem is how can user select one row in the table .

```<code> <asp:GridView ID="GridView1" runat="server" CssClass="style29">
     <Columns>
         <asp:TemplateField HeaderText="Send Message to Group">
         <ItemTemplate>
             <asp:LinkButton ID="LinkButton2" runat="server"
             PostBackUrl='<%# Eval("GroupName", "SendMessage.aspx?GroupName={0}") %>'
             Text='Send Message'></asp:LinkButton>
        </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
</code>```

Is it possible to do without a check box? Or can I add a delete image to the table in a separate column and on clicking the button the row will be deleted.

答:
Use ICallbackEventHandler to trigger an action on the server.

But my problem is how can user select one row in the table .

this code adds a Select button:

```<code><asp:CommandField ShowSelectButton="True" />
</code>```

Now your problem is only to get the server to execute some piece of code, do that using ICallbackEventHandler or Ajax.

Body:
I am displaying a table in a grid view in a asp.net webpage. I want the user to select one row in the website and delete it. How can I do that. I have a delete button in the same page, where I will do code behind to drop the row in the database. But my problem is how can user select one row in the table .

 <asp:GridView ID="GridView1" runat="server" CssClass="style29">
     <Columns>
         <asp:TemplateField HeaderText="Send Message to Group">
         <ItemTemplate>
             <asp:LinkButton ID="LinkButton2" runat="server"
             PostBackUrl='<%# Eval("GroupName", "SendMessage.aspx?GroupName={0}") %>'
             Text='Send Message'></asp:LinkButton>
        </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Is it possible to do without a check box? Or can I add a delete image to the table in a separate column and on clicking the button the row will be deleted.

Body:
Use ICallbackEventHandler to trigger an action on the server.

But my problem is how can user select one row in the table .

this code adds a Select button:

<asp:CommandField ShowSelectButton="True" />

Now your problem is only to get the server to execute some piece of code, do that using ICallbackEventHandler or Ajax.


问:
How to declare two or multiple words as a single word although it contain space
I am creating a search for blood donors and everything is working fine and after completing the search I am facing some issues in it. My search is working but it's not showing perfect result. Let me elaborate,

```<code>#My Table Structure

    #Table 1- blood_donor
    +----+------+----------+-------------+
    | id | name | blood_id | location_id | // columns
    +----+------+----------+-------------+
    |  1 | rony |     1    |       1     |
    +----+------+----------+-------------+
    |  2 | jony |     2    |       2     |
    +----+------+----------+-------------+
    |  3 | tony |     3    |       3     |
    +----+------+----------+-------------+ // Data example

    #Table 2- blood_group
    +----+------------+
    | id | group_name | // columns
    +----+------------+
    |  1 | a positive |
    +----+------------+
    |  2 | b positive |
    +----+------------+
    |  3 | o negative |
    +----+------------+ // Data example

    #Table 3- location
    +----+---------------+
    | id | location_name | // columns
    +----+---------------+
    |  1 |     khulna    |
    +----+---------------+
    |  2 |     dhaka     |
    +----+---------------+
    |  3 |     sylhet    |
    +----+---------------+ // Data example
</code>```

My keyword

$keyword = "o negative blood donor in khulna";
```
<p>Now I separated the words</p>
<pre class="lang-php prettyprint-override"><code>$keyword_array = explode(" ",$keyword);
</code>```

Here is my query

$query ="SELECT * FROM
    blood_donor AS bd
LEFT JOIN blood_group AS bg ON bg.id = bd.blood_id
LEFT JOIN location    AS lo ON lo.id = bd.location_id
WHERE
bd.name          LIKE '%$keyword%' OR
bg.group_name    LIKE '%$keyword%' OR
lo.location_name LIKE '%$keyword%' OR";

// this above part giving me a result set for 100% match for the full keyword

// Now I generate another result set for separated keyword below

if (count($keyword_array) > 1) {
    foreach ($keyword_array as $array) {
        $query = $query . "
            bd.name          LIKE '%$array%' OR
            bg.group_name    LIKE '%$array%' OR
            lo.location_name LIKE '%$array%' OR";
    }
}

$query = substr($query,0,-3); // Removed the extra OR from the end

// My order by section
$query = $query . " ORDER BY
    CASE
        // If full match found, then bring them top
        WHEN bd.name LIKE '%$keyword%' THEN 1";

        // If partial match found, then bring them afterwards
        if (count($keyword_array) > 1) {
            $keyword_count = count($keyword_array);
            $query = $query . " WHEN";
            for ($i = 0; $i < $keyword_count; $i++) {
                $query = $query . " bd.name LIKE '%$keyword_array[$i]%' AND";
            }
            $query = substr($query,0,-3); // To remove the last AND
            $query = $query . " THEN 2";
        }
        $query = $query . " ELSE 3
    END
LIMIT $items_to_skip, $items_per_page"; // These two variables are OFFSET and LIMIT
```
<p>The keyword I am searching with, in the full match section it has nothing to do because there are no such sentence available in my database as `o negative blood donor in khulna that is okay but when the keywords getting separated then in the separated result section it's generating result what actually I am not looking for!</p>
<p>My separated keywords generating an array which is</p>
<pre class="lang-php prettyprint-override"><code>Array
(
    [0] => o
    [1] => negative
    [2] => blood
    [3] => donor
    [4] => in
    [5] => khulna
)
</code>```

And my SQL generating the query like this

bd.name          LIKE '%o%'        OR
bg.group_name    LIKE '%o%'        OR
lo.location_name LIKE '%o%'        OR
bd.name          LIKE '%negative%' OR
bg.group_name    LIKE '%negative%' OR
lo.location_name LIKE '%negative%' OR
bd.name          LIKE '%blood%'    OR
bg.group_name    LIKE '%blood%'    OR
lo.location_name LIKE '%blood%'    OR
bd.name          LIKE '%donor%'    OR
bg.group_name    LIKE '%donor%'    OR
lo.location_name LIKE '%donor%'    OR
bd.name          LIKE '%in%'       OR
bg.group_name    LIKE '%in%'       OR
lo.location_name LIKE '%in%'       OR
bd.name          LIKE '%khulna%'   OR
bg.group_name    LIKE '%khulna%'   OR
lo.location_name LIKE '%khulna%'
```
<p>This query giving me all the three rows because all the name contain the letter <code>o</code> but I don't want that! I want <code>o negative</code> as a single word so the result must be two rows. row 1 and 3. But how to achieve that? I really can't figure it out. Also I don't know how to make two different word as a single word.</p>
<p>There are eight blood groups and I want to treat every blood group name as a single word!
Example: A Negative is two word, but I want them as one word and how am I going to do it, is it possible?</p>
<p>I need an array like this. And how to do it?</p>
<pre class="lang-php prettyprint-override"><code>$keyword = "o negative blood donor in khulna";
$keyword_array = explode(" ",$keyword);
print_r($keyword_array);
Array
(
    [0] => o negative
    [1] => blood
    [2] => donor
    [3] => in
    [4] => khulna
)
</code>```

Thanks in advance.

答:
If I understand you correctly, you have an issue with blood group/type, as it is like "O negative" or "AB positive" or "0 +"...and so on, so basically two words in one...Try this (its not optimal, but it does the job)

```<code>  // Define blood groups and types here..You can also include more later
    $bloodGroups = [
        "negative",
        "positive",
        "+",
        "-"
        ];

    $bloodTypes = [
        "a",
        "b",
        "o",
        "0", //Some might go for zero...
        "ab"
        ];

    $keyword = "o negative blood donor in khulna";
    // Also try with...So upper case, signs, number
    // $keyword = "AB - blood donor in khulna";
    // $keyword = "0 + blood donor in khulna";

    $keywordArray = explode(" ",$keyword);

    // Array to push blood group and type
    $bloodGroupType= [];

    foreach($keywordArray as $key => $value) {
        $value = strtolower($value);
        //If found in bloodTypes array, we have a blood type...push it to first position in bloodGroupType array and also unset from main array
        if(in_array($value, $bloodTypes )) {
            // Number to char
             if($value == "0") {
                $value = "o";
            }
            $bloodGroupType[0] = $value;
            unset($keywordArray[$key]);
        }
        //If value is found in groups array, we have a blood group...push it to second position in bloodGroupType array and also unset from main array
        if (in_array($value, $bloodGroups )) {
            //Change signs to words
            if($value == "-") {
                $value = "negative";
            }
             if($value == "+") {
                $value = "positive";
            }
             $bloodGroupType[1] = $value;
             unset($keywordArray[$key]);
        }
    }
    // Create string from bloodGroupType, and push to "main array"
    $searchBloodType = implode(" ", $bloodGroupType);

    array_push($keywordArray,$searchBloodType);
    print_r($keywordArray);
</code>```

So now you can loop over this array. Also..This solution will also work if you mix the string..

BR

Body:
I am creating a search for blood donors and everything is working fine and after completing the search I am facing some issues in it. My search is working but it's not showing perfect result. Let me elaborate,

#My Table Structure

    #Table 1- blood_donor
    +----+------+----------+-------------+
    | id | name | blood_id | location_id | // columns
    +----+------+----------+-------------+
    |  1 | rony |     1    |       1     |
    +----+------+----------+-------------+
    |  2 | jony |     2    |       2     |
    +----+------+----------+-------------+
    |  3 | tony |     3    |       3     |
    +----+------+----------+-------------+ // Data example

    #Table 2- blood_group
    +----+------------+
    | id | group_name | // columns
    +----+------------+
    |  1 | a positive |
    +----+------------+
    |  2 | b positive |
    +----+------------+
    |  3 | o negative |
    +----+------------+ // Data example

    #Table 3- location
    +----+---------------+
    | id | location_name | // columns
    +----+---------------+
    |  1 |     khulna    |
    +----+---------------+
    |  2 |     dhaka     |
    +----+---------------+
    |  3 |     sylhet    |
    +----+---------------+ // Data example

My keyword

$keyword = "o negative blood donor in khulna";

Now I separated the words

$keyword_array = explode(" ",$keyword);

Here is my query

$query ="SELECT * FROM
    blood_donor AS bd
LEFT JOIN blood_group AS bg ON bg.id = bd.blood_id
LEFT JOIN location    AS lo ON lo.id = bd.location_id
WHERE
bd.name          LIKE '%$keyword%' OR
bg.group_name    LIKE '%$keyword%' OR
lo.location_name LIKE '%$keyword%' OR";

// this above part giving me a result set for 100% match for the full keyword

// Now I generate another result set for separated keyword below

if (count($keyword_array) > 1) {
    foreach ($keyword_array as $array) {
        $query = $query . "
            bd.name          LIKE '%$array%' OR
            bg.group_name    LIKE '%$array%' OR
            lo.location_name LIKE '%$array%' OR";
    }
}

$query = substr($query,0,-3); // Removed the extra OR from the end

// My order by section
$query = $query . " ORDER BY
    CASE
        // If full match found, then bring them top
        WHEN bd.name LIKE '%$keyword%' THEN 1";

        // If partial match found, then bring them afterwards
        if (count($keyword_array) > 1) {
            $keyword_count = count($keyword_array);
            $query = $query . " WHEN";
            for ($i = 0; $i < $keyword_count; $i++) {
                $query = $query . " bd.name LIKE '%$keyword_array[$i]%' AND";
            }
            $query = substr($query,0,-3); // To remove the last AND
            $query = $query . " THEN 2";
        }
        $query = $query . " ELSE 3
    END
LIMIT $items_to_skip, $items_per_page"; // These two variables are OFFSET and LIMIT

The keyword I am searching with, in the full match section it has nothing to do because there are no such sentence available in my database as `o negative blood donor in khulna that is okay but when the keywords getting separated then in the separated result section it's generating result what actually I am not looking for!

My separated keywords generating an array which is

Array
(
    [0] => o
    [1] => negative
    [2] => blood
    [3] => donor
    [4] => in
    [5] => khulna
)

And my SQL generating the query like this

bd.name          LIKE '%o%'        OR
bg.group_name    LIKE '%o%'        OR
lo.location_name LIKE '%o%'        OR
bd.name          LIKE '%negative%' OR
bg.group_name    LIKE '%negative%' OR
lo.location_name LIKE '%negative%' OR
bd.name          LIKE '%blood%'    OR
bg.group_name    LIKE '%blood%'    OR
lo.location_name LIKE '%blood%'    OR
bd.name          LIKE '%donor%'    OR
bg.group_name    LIKE '%donor%'    OR
lo.location_name LIKE '%donor%'    OR
bd.name          LIKE '%in%'       OR
bg.group_name    LIKE '%in%'       OR
lo.location_name LIKE '%in%'       OR
bd.name          LIKE '%khulna%'   OR
bg.group_name    LIKE '%khulna%'   OR
lo.location_name LIKE '%khulna%'

This query giving me all the three rows because all the name contain the letter o but I don't want that! I want o negative as a single word so the result must be two rows. row 1 and 3. But how to achieve that? I really can't figure it out. Also I don't know how to make two different word as a single word.

There are eight blood groups and I want to treat every blood group name as a single word!
Example: A Negative is two word, but I want them as one word and how am I going to do it, is it possible?

I need an array like this. And how to do it?

$keyword = "o negative blood donor in khulna";
$keyword_array = explode(" ",$keyword);
print_r($keyword_array);
Array
(
    [0] => o negative
    [1] => blood
    [2] => donor
    [3] => in
    [4] => khulna
)

Thanks in advance.

Body:
If I understand you correctly, you have an issue with blood group/type, as it is like "O negative" or "AB positive" or "0 +"...and so on, so basically two words in one...Try this (its not optimal, but it does the job)

  // Define blood groups and types here..You can also include more later
    $bloodGroups = [
        "negative",
        "positive",
        "+",
        "-"
        ];

    $bloodTypes = [
        "a",
        "b",
        "o",
        "0", //Some might go for zero...
        "ab"
        ];

    $keyword = "o negative blood donor in khulna";
    // Also try with...So upper case, signs, number
    // $keyword = "AB - blood donor in khulna";
    // $keyword = "0 + blood donor in khulna";

    $keywordArray = explode(" ",$keyword);

    // Array to push blood group and type
    $bloodGroupType= [];

    foreach($keywordArray as $key => $value) {
        $value = strtolower($value);
        //If found in bloodTypes array, we have a blood type...push it to first position in bloodGroupType array and also unset from main array
        if(in_array($value, $bloodTypes )) {
            // Number to char
             if($value == "0") {
                $value = "o";
            }
            $bloodGroupType[0] = $value;
            unset($keywordArray[$key]);
        }
        //If value is found in groups array, we have a blood group...push it to second position in bloodGroupType array and also unset from main array
        if (in_array($value, $bloodGroups )) {
            //Change signs to words
            if($value == "-") {
                $value = "negative";
            }
             if($value == "+") {
                $value = "positive";
            }
             $bloodGroupType[1] = $value;
             unset($keywordArray[$key]);
        }
    }
    // Create string from bloodGroupType, and push to "main array"
    $searchBloodType = implode(" ", $bloodGroupType);

    array_push($keywordArray,$searchBloodType);
    print_r($keywordArray);

So now you can loop over this array. Also..This solution will also work if you mix the string..

BR


问:
Readonly configuration variables ini file
I have a program in python that has an ini file with the configuration variables for the program. Some variables are ReadWrite and others ReadOnly.

My config file is something like this:

```<code>[AuthCtrlr]
enable = True
nbrOfMssgs = 10
</code>```

where I want the variable enable to be ReadWrite and nbrOfMssgs  ReadOnly.

In my python code, I can change my variables with:

```<code>parser.set('AuthCtrlr', 'enable', False)
</code>```

with the configparser module.

Is there a way to make a code where if I want to change the variable nbrOfMssgs it prints something like "This variable is ReadOnly" and don't change the value of the variable?

答:
```<code>import configparser

class wrappedParser(configparser.ConfigParser):
    def __init__(self):
        super().__init__()
        self.readOnlySettings = []
    def set(self, category, setting, value):
        if setting in self.readOnlySettings:
            raise PermissionError(f"{setting} setting is read-only")
        else:
            return super().set(category, setting, value)
    def makeReadOnly(self, setting):
        self.readOnlySettings.append(setting)

config = wrappedParser()
config['bitbucket.org'] = {}
config.set('bitbucket.org', 'User', 'hg')
config.makeReadOnly('User')
try:
    config.set('bitbucket.org', 'User', 'pg')
except PermissionError as err:
    print(err)
print(config.get('bitbucket.org', 'User'))
</code>```

Make a child class inheriting from ConfigParser that reimplements set operation in a way that raises an error if the setting you are trying to change is one of the read-only ones.

Still, this does not in any way improve security of your code. It's only good to prevent you from accidentially changing the settings. Which asks the question, why would that happen?

Body:
I have a program in python that has an ini file with the configuration variables for the program. Some variables are ReadWrite and others ReadOnly.

My config file is something like this:

[AuthCtrlr]
enable = True
nbrOfMssgs = 10

where I want the variable enable to be ReadWrite and nbrOfMssgs  ReadOnly.

In my python code, I can change my variables with:

parser.set('AuthCtrlr', 'enable', False)

with the configparser module.

Is there a way to make a code where if I want to change the variable nbrOfMssgs it prints something like "This variable is ReadOnly" and don't change the value of the variable?

Body:
import configparser

class wrappedParser(configparser.ConfigParser):
    def __init__(self):
        super().__init__()
        self.readOnlySettings = []
    def set(self, category, setting, value):
        if setting in self.readOnlySettings:
            raise PermissionError(f"{setting} setting is read-only")
        else:
            return super().set(category, setting, value)
    def makeReadOnly(self, setting):
        self.readOnlySettings.append(setting)

config = wrappedParser()
config['bitbucket.org'] = {}
config.set('bitbucket.org', 'User', 'hg')
config.makeReadOnly('User')
try:
    config.set('bitbucket.org', 'User', 'pg')
except PermissionError as err:
    print(err)
print(config.get('bitbucket.org', 'User'))

Make a child class inheriting from ConfigParser that reimplements set operation in a way that raises an error if the setting you are trying to change is one of the read-only ones.

Still, this does not in any way improve security of your code. It's only good to prevent you from accidentially changing the settings. Which asks the question, why would that happen?


问:
Git rebase returns but nothing happens
I am trying to rebase my feature branch onto develop (git rebase develop after checking out the branch)  but every time I try I just get the message:
 Current branch feature/my-feature-branch is up to date
but checking out develop reveals that nothing has changed from the git log.

Would appreciate any pointers, thanks.

答:
Well assuming that develop might have changes on the remote which you don't yet have in your local develop branch, your observations of a no-op rebase might be expected.  In this case, you could first fetch from the remote, and then rebase on the tracking branch, e.g.

```<code># from your feature branch
git fetch origin
git rebase origin/develop
</code>```

If you really want to do git rebase develop and have it work, then you would have to separately bring develop up to date with the remote via a pull.

Note that if the above doesn't resolve it, then maybe you don't have any changes in develop, contrary to what you expected.

Title: Git rebase returns but nothing happens

Body:
Well assuming that develop might have changes on the remote which you don't yet have in your local develop branch, your observations of a no-op rebase might be expected.  In this case, you could first fetch from the remote, and then rebase on the tracking branch, e.g.

# from your feature branch
git fetch origin
git rebase origin/develop

If you really want to do git rebase develop and have it work, then you would have to separately bring develop up to date with the remote via a pull.

Note that if the above doesn't resolve it, then maybe you don't have any changes in develop, contrary to what you expected.


问:
Can I use the LET formula to define an array in Excel?
I've got a formula that verifies that a list of totals all match. It involves comparing the maximum value and the minimum value, and if they match all values must be the same. I'd like to remove the repeating list of totals within each max and min.

Here's the formula.

```<code>=MIN(SUM(Table1[Count]),SUM(Table2[Count]),SUM(Table3[Count]))=MAX(SUM(Table1[Count]),SUM(Table2[Count]),SUM(Table3[Count]))
</code>```

Can I use LET to define the list of totals as an array?

```<code>=LET(Totals,{SUM(Table1[Count]),SUM(Table2[Count]),SUM(Table3[Count])},MIN(Totals)=MAX(Totals))
</code>```

答:
Let me know if either of the two works:

```<code>=LET(X,CHOOSE({1,2,3},SUM(Table1[Count]),SUM(Table2[Count]),SUM(Table3[Count])),MIN(X)=MAX(X))
</code>```

Or:

```<code>=LET(A,SUM(Table1[Count]),B,SUM(Table2[Count]),C,SUM(Table3[Count]),MIN(A,B,C)=MAX(A,B,C))
</code>```

I wrote both without any sample data, so they are untested.

Body:
I've got a formula that verifies that a list of totals all match. It involves comparing the maximum value and the minimum value, and if they match all values must be the same. I'd like to remove the repeating list of totals within each max and min.

Here's the formula.

=MIN(SUM(Table1[Count]),SUM(Table2[Count]),SUM(Table3[Count]))=MAX(SUM(Table1[Count]),SUM(Table2[Count]),SUM(Table3[Count]))

Can I use LET to define the list of totals as an array?

=LET(Totals,{SUM(Table1[Count]),SUM(Table2[Count]),SUM(Table3[Count])},MIN(Totals)=MAX(Totals))

Body:
Let me know if either of the two works:

=LET(X,CHOOSE({1,2,3},SUM(Table1[Count]),SUM(Table2[Count]),SUM(Table3[Count])),MIN(X)=MAX(X))

Or:

=LET(A,SUM(Table1[Count]),B,SUM(Table2[Count]),C,SUM(Table3[Count]),MIN(A,B,C)=MAX(A,B,C))

I wrote both without any sample data, so they are untested.


问:
material ui (mui) button have incorrect styling
why do my MUI button components look like this instead of like the docs
no external .css file or theme changes besides the ones listed
I have the roboto font installed as well and working on the typography
I want whatever changes I make to be global

```<code>import React from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import CssBaseline from "@mui/material/CssBaseline";
import { createTheme, ThemeProvider } from "@mui/material";
import "@fontsource/roboto/300.css";
import "@fontsource/roboto/400.css";
import "@fontsource/roboto/500.css";
import "@fontsource/roboto/700.css";

import "./index.css";
import Home from "./views/Home";
import Login from "./views/Login";
import Register from "./views/Register";

const theme = createTheme({
  components: {
    Button: {
      defaultProps: {
        fontSize: 1000,
      },
    },
  },
});
const App = () => {
  return (
    <>
      <ThemeProvider theme={theme}>
        <CssBaseline />
        <BrowserRouter>
          <Routes>
            <Route path="/" exact element={<Home />} />
          </Routes>
        </BrowserRouter>
      </ThemeProvider>
    </>
  );
};
export default App;
</code>```
```<code><Button variant="contained" style={{ width: 150, height: 50 }}>
          I'm a Doctor
</Button>
</code>```

thanks for any help

答:
Aren't you missing an import inside the component where the button is?

```<code>import { Button } from '@mui/material';
</code>```

And I think the syntax for themes is wrong, you should be using MuiButton instead of Button inside components entry.

Body:
why do my MUI button components look like this instead of like the docs
no external .css file or theme changes besides the ones listed
I have the roboto font installed as well and working on the typography
I want whatever changes I make to be global

import React from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import CssBaseline from "@mui/material/CssBaseline";
import { createTheme, ThemeProvider } from "@mui/material";
import "@fontsource/roboto/300.css";
import "@fontsource/roboto/400.css";
import "@fontsource/roboto/500.css";
import "@fontsource/roboto/700.css";

import "./index.css";
import Home from "./views/Home";
import Login from "./views/Login";
import Register from "./views/Register";

const theme = createTheme({
  components: {
    Button: {
      defaultProps: {
        fontSize: 1000,
      },
    },
  },
});
const App = () => {
  return (
    <>
      <ThemeProvider theme={theme}>
        <CssBaseline />
        <BrowserRouter>
          <Routes>
            <Route path="/" exact element={<Home />} />
          </Routes>
        </BrowserRouter>
      </ThemeProvider>
    </>
  );
};
export default App;

<Button variant="contained" style={{ width: 150, height: 50 }}>
          I'm a Doctor
</Button>

thanks for any help

Body:
Aren't you missing an import inside the component where the button is?

import { Button } from '@mui/material';

And I think the syntax for themes is wrong, you should be using MuiButton instead of Button inside components entry.


问:
Listen to Physical button press from background on Wear OS
Is it possible to listen for a button press from a background app running on a Wear device?
I would like to create a shortcut for an Android app so that when the user presses a physical button on a watch, the app opens on a paired device.

Thank you,
Donny

答:
add to manifest receiver

```<code>    <receiver
        android:name=".services.utils.SearchLongPressReceiver"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.SOS_LONG_PRESS" />
        </intent-filter>
    </receiver>
</code>```

create BroadcastReceiver

```<code>class SearchLongPressReceiver : BroadcastReceiver() {

   override fun onReceive(context: Context, intent: Intent) {
       context.startActivity(Intent(context, SosActivity::class.java))
   }
}
</code>```

Body:
add to manifest receiver

    <receiver
        android:name=".services.utils.SearchLongPressReceiver"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.SOS_LONG_PRESS" />
        </intent-filter>
    </receiver>

create BroadcastReceiver

class SearchLongPressReceiver : BroadcastReceiver() {

   override fun onReceive(context: Context, intent: Intent) {
       context.startActivity(Intent(context, SosActivity::class.java))
   }
}


问:
Figures overlapping when plotting using Matplotlib
I have a plot with multiple images. There are 20 rows and 3 columns. In each row the 1st column should be the original image, the 2nd column should be the mask and the 3rd column should be segmentation obtained using a neural network.

I tried using the below code. 2 rows can be plotted correctly. From 3rd row images overlap the 1st row.

```<code>f = plt.figure()
for j in range(3):
    pred_y = y_pred[j]
    pred_y = pred_y.reshape(256, 256)
    pred_y = (pred_y > 0.1).astype(np.uint8)
    f.add_subplot(j + 1, 3, 1 )
    plt.imshow(X_test[j, :, :])

    f.add_subplot(j + 1, 3, 2)
    plt.imshow(y_test[j])

    f.add_subplot(j + 1, 3, 3)
    plt.imshow(pred_y)
plt.show()
</code>```

The obtained output is,

答:
The arguments to Figure.add_subplot are num_rows, num_cols, n, not row, num_rows, col. You are therefore making the top row of plots in a 1x3, 2x3, 3x3 arrangement. Make your calls to add_subplot like this:

```<code>f.add_subplot(20, 3, 3 * j + 1)
f.add_subplot(20, 3, 3 * j + 2)
f.add_subplot(20, 3, 3 * j + 1)
</code>```

A better way to generate your axes might be plt.subplots, as suggested in the demo:

```<code>fig, ax = plt.subplots(20, 3, constrained_layout=True)
for i in range(20):
    ax[i, 0].imshow(X_test[i])
    ax[i, 1].imshow(y_test[j])
    ax[i, 2].imshow((pred_y[j].reshape(256, 256) > 0.1).astype(np.uint8))
</code>```

Body:
I have a plot with multiple images. There are 20 rows and 3 columns. In each row the 1st column should be the original image, the 2nd column should be the mask and the 3rd column should be segmentation obtained using a neural network.

I tried using the below code. 2 rows can be plotted correctly. From 3rd row images overlap the 1st row.

f = plt.figure()
for j in range(3):
    pred_y = y_pred[j]
    pred_y = pred_y.reshape(256, 256)
    pred_y = (pred_y > 0.1).astype(np.uint8)
    f.add_subplot(j + 1, 3, 1 )
    plt.imshow(X_test[j, :, :])

    f.add_subplot(j + 1, 3, 2)
    plt.imshow(y_test[j])

    f.add_subplot(j + 1, 3, 3)
    plt.imshow(pred_y)
plt.show()

The obtained output is,

Body:
The arguments to Figure.add_subplot are num_rows, num_cols, n, not row, num_rows, col. You are therefore making the top row of plots in a 1x3, 2x3, 3x3 arrangement. Make your calls to add_subplot like this:

f.add_subplot(20, 3, 3 * j + 1)
f.add_subplot(20, 3, 3 * j + 2)
f.add_subplot(20, 3, 3 * j + 1)

A better way to generate your axes might be plt.subplots, as suggested in the demo:

fig, ax = plt.subplots(20, 3, constrained_layout=True)
for i in range(20):
    ax[i, 0].imshow(X_test[i])
    ax[i, 1].imshow(y_test[j])
    ax[i, 2].imshow((pred_y[j].reshape(256, 256) > 0.1).astype(np.uint8))


问:
Why is react skeleton not rendering?
I have a component Recommended that makes a service call to firebase and renders the returned data. During the loading delay at the database call, I want to render a react skeleton, as follows:

Recommended.js

```<code>import { useState, useEffect } from "react";
import Skeleton from "react-loading-skeleton";
import { getVenues } from "../services/firebase";
import VenueCard from "./VenueCard";

const Reccomended = () => {
  const [venues, setVenues] = useState([]);

  useEffect(() => {
    async function getAllVenues() {
      const response = await getVenues();
      await setVenues(response);
    }
    getAllVenues();
  }, []);

  venues[0] ? console.log(true) : console.log(false)

  return (
    <div>
      {!venues[0] ? (
        <>
          <Skeleton />
        </>
      ) : (
        <>
          <p className="recommended">Recommended for Josh</p>
          <VenueCard venues={venues} />
        </>
      )}
    </div>
  );
};

export default Reccomended;
</code>```

However, the skeleton is not rending during loading. The returning data is saved to the state variable venues, and I'm using the 'truthiness' as a conditional for the render. I tested this by logging the following:

  venues[0] ? console.log(true) : console.log(false)

In the browser it initially logged false, followed quickly by true
So given this, I don't understand why the skeleton isn't loading - any suggestions?

I've also passed parameters into <Skeleton/> which didn't change anything.

答:
You must include the CSS styles, or you won't see anything. Just add

```<code>import "react-loading-skeleton/dist/skeleton.css";
</code>```

with the rest of the imports.

This is documented in the package readme in the react-loading-skeleton basic Usage section

Title: Why is react skeleton not rendering?

Body:
I have a component Recommended that makes a service call to firebase and renders the returned data. During the loading delay at the database call, I want to render a react skeleton, as follows:

Recommended.js

import { useState, useEffect } from "react";
import Skeleton from "react-loading-skeleton";
import { getVenues } from "../services/firebase";
import VenueCard from "./VenueCard";

const Reccomended = () => {
  const [venues, setVenues] = useState([]);

  useEffect(() => {
    async function getAllVenues() {
      const response = await getVenues();
      await setVenues(response);
    }
    getAllVenues();
  }, []);

  venues[0] ? console.log(true) : console.log(false)

  return (

      {!venues[0] ? (
        <>
          <Skeleton />
        </>
      ) : (
        <>

Recommended for Josh

          <VenueCard venues={venues} />
        </>
      )}

  );
};

export default Reccomended;

However, the skeleton is not rending during loading. The returning data is saved to the state variable venues, and I'm using the 'truthiness' as a conditional for the render. I tested this by logging the following:

  venues[0] ? console.log(true) : console.log(false)

In the browser it initially logged false, followed quickly by true
So given this, I don't understand why the skeleton isn't loading - any suggestions?

I've also passed parameters into <Skeleton/> which didn't change anything.

Body:
You must include the CSS styles, or you won't see anything. Just add

import "react-loading-skeleton/dist/skeleton.css";

with the rest of the imports.

This is documented in the package readme in the react-loading-skeleton basic Usage section


问:
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource

Possible Duplicate:

  Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result

I'm having a problem with this mysql code. I presume its a basic error in the $sqlx... line but I'm slightly lost.

The code basically prints messages from a db
Here is the code:

```<code>$sqls="SELECT username FROM social WHERE `adder`='$username'";
$results=mysql_query($sqls);
$resulti= mysql_num_rows($results);
if ($resulti==0) {
echo "You haven't added anyone yet. Find some <a   href=\"/social/suggestions\">suggestions</a>";
}
$row=mysql_fetch_array($results);

$sqlx="SELECT * FROM messages WHERE `sender` IN ($row)";
$resultx= mysql_query($sqlx);
$resultz= mysql_num_rows($resultx);
if ($resultz==0){
echo "No messages at all!!";
}
else {
$finished="false";
$r=0;
While(($rowx=mysql_fetch_assoc($resultx))&&($finished=="false")) {
//echo off messages
</code>```

$username is got further up the file.

Here is the error:

Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/user/public_html/social/iframe/index.php on line 34

Line 34 is $resultz= mysql_num_rows($resultx);
But like i said the error is probably the line two up from that.

One interesting happens. "No messages at all!!" is echoed out which means the result of the mysql_query is 0. This is why I am convinced it is the line 32, ($sqlx)

Any idea??

Have I done the mysql_fetch_array wrong when getting $row??
thanks

答:
If your query fails mysql_query($sqlx) returns false rather than resource. So, you need to check, that this function returned true (e.g. if (!results) {}) nad print use mysql_error() to see what error was.

```<code>if(!$resultx){
   print 'error:'.mysql_error();
}
</code>```

Also, you are embedding $row variable into the query string. But this var is an Array, so you end up with a query like this:

```<code>SELECT * FROM messages WHERE `sender` IN (Array)
</code>```

See mysql_fetch_array manual for details

Body:
Possible Duplicate:

  Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result

I'm having a problem with this mysql code. I presume its a basic error in the $sqlx... line but I'm slightly lost.

The code basically prints messages from a db
Here is the code:

$sqls="SELECT username FROM social WHERE `adder`='$username'";
$results=mysql_query($sqls);
$resulti= mysql_num_rows($results);
if ($resulti==0) {
echo "You haven't added anyone yet. Find some suggestions";
}
$row=mysql_fetch_array($results);

$sqlx="SELECT * FROM messages WHERE `sender` IN ($row)";
$resultx= mysql_query($sqlx);
$resultz= mysql_num_rows($resultx);
if ($resultz==0){
echo "No messages at all!!";
}
else {
$finished="false";
$r=0;
While(($rowx=mysql_fetch_assoc($resultx))&&($finished=="false")) {
//echo off messages

$username is got further up the file.

Here is the error:

Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/user/public_html/social/iframe/index.php on line 34

Line 34 is $resultz= mysql_num_rows($resultx);
But like i said the error is probably the line two up from that.

One interesting happens. "No messages at all!!" is echoed out which means the result of the mysql_query is 0. This is why I am convinced it is the line 32, ($sqlx)

Any idea??

Have I done the mysql_fetch_array wrong when getting $row??
thanks

Body:
If your query fails mysql_query($sqlx) returns false rather than resource. So, you need to check, that this function returned true (e.g. if (!results) {}) nad print use mysql_error() to see what error was.

if(!$resultx){
   print 'error:'.mysql_error();
}

Also, you are embedding $row variable into the query string. But this var is an Array, so you end up with a query like this:

SELECT * FROM messages WHERE `sender` IN (Array)

See mysql_fetch_array manual for details


问:
Kubernetes Persistent Volume Access Modes: ReadWriteOnce vs ReadOnlyMany vs ReadWriteMany
As per this official document, Kubernetes Persistent Volumes support three types of access modes.

ReadOnlyMany

ReadWriteOnce

ReadWriteMany

The given definitions of them in the document is very high-level. It would be great if someone can explain them in little more detail along with some examples of different use cases where we should use one vs other.

答:
In Kubernetes you provision storage either statically(using a storage class) or dynamically (Persistent Volume). Once the storage is available to bound and claimed, you need to configure it in what way your Pods or Nodes are connecting to the storage (a persistent volume). That could be configured in below four modes.

ReadOnlyMany (ROX)

In this mode multiple pods running on different Nodes could connect to the storage and carry out read operation.

ReadWriteMany (RWX)

In this mode multiple pods running on different Nodes could connect to the storage and carry out read and write operation.

ReadWriteOnce  (RWO)

In this mode multiple pods running in only one Node could connect to the storage and carry out read and write operation.

ReadWriteOncePod (RWOP)

In this mode the volume can be mounted as read-write by a single Pod. Use ReadWriteOncePod access mode if you want to ensure that only one pod across whole cluster can read that PVC or write to it. This is only supported for CSI volumes and Kubernetes version 1.22+.

Folow the documentation to get more insight.


问:
Twilio SMS is saying a "to" phone number is not provided even though it is
I have very simple code and I just can't figure out what's going wrong.

I have a Twilio trial account and a trial phone number and I am trying to send an SMS using it.

from os import environ
from twilio.rest import Client

client = Client(environ['ACCOUNT_SID'], environ['AUTH_TOKEN'])

message = client.messages.create(body = f'The verification code for Treal is {code}', from_ = "+1**********", to = "+91**********")
```
<p>The one in the from is my Twilio trial number and the one in the "to" is a number I want to send to. I am getting an error:</p>
<pre class="lang-none prettyprint-override"><code>twilio.base.exceptions.TwilioRestException:
HTTP Error Your request was:

POST /Accounts/AC*******1830e0****a3403dfd16d****/Messages.json

Twilio returned the following information:

Unable to create record: A 'To' phone number is required.

More information may be available here:

https://www.twilio.com/docs/errors/21604
</code>```

答:
With a trial account, in Twilio, you can send a message only to the phone you signed in with or verified so if I provided the phone number "1234" I can only send messages to "1234".

Maybe you didn't provide a phone number when you signed up?

Twiilo docs

Body:
I have very simple code and I just can't figure out what's going wrong.

I have a Twilio trial account and a trial phone number and I am trying to send an SMS using it.

from os import environ
from twilio.rest import Client

client = Client(environ['ACCOUNT_SID'], environ['AUTH_TOKEN'])

message = client.messages.create(body = f'The verification code for Treal is {code}', from_ = "+1**********", to = "+91**********")

The one in the from is my Twilio trial number and the one in the "to" is a number I want to send to. I am getting an error:

twilio.base.exceptions.TwilioRestException:
HTTP Error Your request was:

POST /Accounts/AC*******1830e0****a3403dfd16d****/Messages.json

Twilio returned the following information:

Unable to create record: A 'To' phone number is required.

More information may be available here:

https://www.twilio.com/docs/errors/21604


答:
Using a Javascript parser, you can traverse through the syntax-tree (AST) and find each ".stack" inside a catch-block.

For example use slimit in Python:

from slimit import ast
from slimit.parser import Parser
from slimit.visitors import nodevisitor

data = """
try {
    print(new Function(astatement)())
} catch (e) {
    print(e.stack)
}
"""

parser = Parser()
tree = parser.parse(data)

def nextCatch(tree):
    for node in nodevisitor.visit(tree):
        if isinstance(node, ast.Catch):
            return node

def nextIdentifierStack(tree):
    for node in nodevisitor.visit(tree):
        if isinstance(node, ast.Identifier) and node.value == 'stack':
            return node

def printChildren(node):
    for i, ch in enumerate(node.children()):
            print(f"{i:2}: {ch.to_ecma()}")

catch = nextCatch(tree)
printChildren(catch)
stack = nextIdentifierStack(catch)
print(stack.to_ecma())
```
<p>Prints: the catch block with 2 children and the found <code>stack</code> identifier</p>
``` 0: e
 1: {
  print(e.stack);
}
stack
```

See also JavaScript parser in Python

Title: Regex : Find string between brackets after a string

Body:
So far my regex is ->

myRegex = /catch *\(.\) */

I want to be able to search the following string -

try {
print(new Function (astatement)())
} catch (e)  { print(e.stack) }

So that if .stack is present after catch(anything) it should return true, so far I have managed to reach the catch(anything), stuck from here.

Body:
Using a Javascript parser, you can traverse through the syntax-tree (AST) and find each ".stack" inside a catch-block.

For example use slimit in Python:

from slimit import ast
from slimit.parser import Parser
from slimit.visitors import nodevisitor

data = """
try {
    print(new Function(astatement)())
} catch (e) {
    print(e.stack)
}
"""

parser = Parser()
tree = parser.parse(data)

def nextCatch(tree):
    for node in nodevisitor.visit(tree):
        if isinstance(node, ast.Catch):
            return node

def nextIdentifierStack(tree):
    for node in nodevisitor.visit(tree):
        if isinstance(node, ast.Identifier) and node.value == 'stack':
            return node

def printChildren(node):
    for i, ch in enumerate(node.children()):
            print(f"{i:2}: {ch.to_ecma()}")

catch = nextCatch(tree)
printChildren(catch)
stack = nextIdentifierStack(catch)
print(stack.to_ecma())

Prints: the catch block with 2 children and the found stack identifier

 0: e
 1: {
  print(e.stack);
}
stack

See also JavaScript parser in Python


问:
How can I set up a redirect on GKE to GAE?
I have a service deployed on GKE, with a a google cloud external load balancer. I would now like to winddown this service, but initially by redirecting to an app engine service. Is this possible via just the load balancer?</p>

答:
This can be achieved with a Serverless Network Endpoint Group (NEG).

You can find tutorial on creating such a setup here. Certain steps can be skipped since you already have the load balancer configured.


问:
How to include library and header files from another one of my Meson projects?
I have two projects on the go, one is a library, and the other wants to use some of that library.

My directory structure is:

```<code>Work/
      ProjectA/
               src/
                   include/
               build/

      ProjectB/
               src/
               build/
</code>```

Assume both projects are built with meson-build, and projectA is the library.

1- How do I get ProjectB to see the include files of ProjectA?
2- How do I link the .lib file of projectA? (which is currently in the  build folder)

When I try to create a dependency using relative paths, I cant find the thing that gets the .lib file?
I am only able to get the header files using:

```<code>a_dep = declare_dependency(include_directories : include_directories('../../ProjectA/src/include'))
</code>```

Note I am using windows, but also will be using linux.

答:
One way to access the includes from another project is to use subprojects() and get_variable():

Project B:

```<code>project('Project B', ...)
.
.
.
projectB_inc = [ 'inc', 'src/inc' ]
inc_dirs = include_directories(projectB_inc)
.
.
.
projecB_lib = static_library('projectB',...
</code>```

Access Project B from Project A:

```<code>project('Project A', ...)
.
.
.
pB = subproject('projectB')
pB_inc_dirs = rp.get_variable('inc_dirs')
.
.
.
# Use the include dirs:

pA_inc_dirs = ...

exe = executable(
  'projectA_exe',
  'main.c',
  ...
  include_directories:  [pA_inc_dirs, pB_inc_dirs])
</code>```

Body:
I have two projects on the go, one is a library, and the other wants to use some of that library.

My directory structure is:

Work/
      ProjectA/
               src/
                   include/
               build/

      ProjectB/
               src/
               build/

Assume both projects are built with meson-build, and projectA is the library.

1- How do I get ProjectB to see the include files of ProjectA?
2- How do I link the .lib file of projectA? (which is currently in the  build folder)

When I try to create a dependency using relative paths, I cant find the thing that gets the .lib file?
I am only able to get the header files using:

a_dep = declare_dependency(include_directories : include_directories('../../ProjectA/src/include'))

Note I am using windows, but also will be using linux.

Body:
One way to access the includes from another project is to use subprojects() and get_variable():

Project B:

project('Project B', ...)
.
.
.
projectB_inc = [ 'inc', 'src/inc' ]
inc_dirs = include_directories(projectB_inc)
.
.
.
projecB_lib = static_library('projectB',...

Access Project B from Project A:

project('Project A', ...)
.
.
.
pB = subproject('projectB')
pB_inc_dirs = rp.get_variable('inc_dirs')
.
.
.
# Use the include dirs:

pA_inc_dirs = ...

exe = executable(
  'projectA_exe',
  'main.c',
  ...
  include_directories:  [pA_inc_dirs, pB_inc_dirs])


问:
How to get button to inherit color
Color inheritance doesn't seem to work for button.

```<code><div style='color:blue'>
    <button>
        hi
    </button>
</div>
</code>```

When I debug the above code, I see that the button inherits the color "blue" from div. However, it is still rendered as black.

If I set the button's color to blue directly, it renders blue as expected.

How do I get color inheritance to work for button?

jsfiddle here.

答: The default button behavior does not inherit, that is why buttons are rendered in the default look except directly styled</p>

Title: How to get button to inherit color

Body:
Color inheritance doesn't seem to work for button.

    <button>
        hi
    </button>

When I debug the above code, I see that the button inherits the color "blue" from div. However, it is still rendered as black.

If I set the button's color to blue directly, it renders blue as expected.

How do I get color inheritance to work for button?

jsfiddle here.


问:
IBOutlet and IBAction
What is the purpose of using IBOutlets and IBActions in Xcode and Interface Builder?

Does it make any difference if I don't use IBOutlets and IBActions?

Swift:

```<code>@IBOutlet weak var textField: UITextField!

@IBAction func buttonPressed(_ sender: Any) { /* ... */ }
</code>```

Objective-C:

```<code>@property (nonatomic, weak) IBOutlet UITextField *textField;

- (IBAction)buttonPressed:(id)sender { /* ... */ }
</code>```

答: I didn't know you didn't need them anymore, they used to be to make it possible for interface builder to find them in your source, in swift I would image that IBAction is still needed, because it needed to change how your method can be called from interface builder though I imaging @objc would do the same thing. I personal intend to still keep using them because it documents what the method or interface is suppose to do.</p>

Title: IBOutlet and IBAction

Body:
What is the purpose of using IBOutlets and IBActions in Xcode and Interface Builder?

Does it make any difference if I don't use IBOutlets and IBActions?

Swift:

@IBOutlet weak var textField: UITextField!

@IBAction func buttonPressed(_ sender: Any) { /* ... */ }

Objective-C:

@property (nonatomic, weak) IBOutlet UITextField *textField;

- (IBAction)buttonPressed:(id)sender { /* ... */ }


问:
How can change/convert timezone when I query in PostgreSQL
I need a query to convert timezone in PostgreSQL

I have already tried this query

```<code>Select users.last_update_time + interval '7 hours'
</code>```

And it plus for my result 7 hours.

But I have a problem that if I choose results from 31/01/2022 to 06/02/2022. It will include the result on 07/02/2022. Example before I plus 7 hours, it's on around 17:00 06/02/2022 to 00:00 07/02/2022.

The correct result has to be after +7 hours. So it means that result after plus 7 hours from 17:00 06/02/2022 to 00:00 07/02/2022 shouldn't be in there.

答:
Then you should include the time zone in the query like this:

```<code>SELECT ... FROM ...
WHERE tscol BETWEEN '2022-01-31 00:00:00 America/Vancouver'
                AND '2022-02-07 00:00:00 America/Vancouver';
</code>```

If you don't want to hard code the time zone, the best thing is to set the timezone database parameter to the correct time zone in your database session. Then you can use a simple type cast, which will respect the setting:

```<code>SELECT ... FROM ...
WHERE tscol BETWEEN CAST ('2022-01-31 00:00:00' AS timestamp with time zone)
                AND CAST ('2022-02-07 00:00:00' AS timestamp with time zone);
</code>```

Body:
I need a query to convert timezone in PostgreSQL

I have already tried this query

Select users.last_update_time + interval '7 hours'

And it plus for my result 7 hours.

But I have a problem that if I choose results from 31/01/2022 to 06/02/2022. It will include the result on 07/02/2022. Example before I plus 7 hours, it's on around 17:00 06/02/2022 to 00:00 07/02/2022.

The correct result has to be after +7 hours. So it means that result after plus 7 hours from 17:00 06/02/2022 to 00:00 07/02/2022 shouldn't be in there.

Body:
Then you should include the time zone in the query like this:

SELECT ... FROM ...
WHERE tscol BETWEEN '2022-01-31 00:00:00 America/Vancouver'
                AND '2022-02-07 00:00:00 America/Vancouver';

If you don't want to hard code the time zone, the best thing is to set the timezone database parameter to the correct time zone in your database session. Then you can use a simple type cast, which will respect the setting:

SELECT ... FROM ...
WHERE tscol BETWEEN CAST ('2022-01-31 00:00:00' AS timestamp with time zone)
                AND CAST ('2022-02-07 00:00:00' AS timestamp with time zone);


问:
Swagger UI : "Choose file" button when input has both file AND json object?
Asp.Net, .Net 5.0

I have this POST endpoint that requires to BOTH upload a file and a "complex" object (json). In order to test it, I use Swagger UI.

1. Testing the upload of a file alone is easy.

If the endpoint looks like this...

```<code>public ActionResult TestUpload(bool testBool, IFormFile file) {
</code>```

...then Swagger UI looks like this :

2. Testing the upload of a json object alone is easy too.

```<code>public class DummyInput {
    public bool Field { get; set; }
}
</code>```

If the endpoint looks like this...

```<code>public ActionResult TestUpload(bool testBool, DummyInput input) {
</code>```

...then Swagger UI looks like this :

3. I can even make my life easier like this :

public ActionResult TestUpload(bool testBool, [FromForm] DummyInput input) {

That's great.

4. But what if I want BOTH the file and the 'input' json object ?

attempt #1 :

```<code>public ActionResult TestUpload(bool testBool, IFormFile file, DummyInput input) {
</code>```

That obviously doesn't work because you cannot have two parameters "From body", there can be only one.

attempt #2:

public ActionResult TestUpload(bool testBool, [FromForm] IFormFile file, [FromForm]
DummyInput input) {

attempt #3:

```<code>public class WrapperInput {
    public DummyInput Input { get; set; }
    public IFormFile File { get; set; }
}

public ActionResult TestUpload(bool testBool, WrapperInput input) {
</code>```

So, in conclusion :  how do I get to enter my nice fields AND my "Select file" button?
I've looked at this article but it seems overly complicated -- and to be honest I'm not sure it's even related to my needs. I have a feeling that it's for OpenApi 2.0 rather than the better things we get from OpenApi 3.0.

答:
I found the right combination of settings, I was so close :

```<code>public class WrapperInput {
    public DummyInput Input { get; set; }
    public IFormFile File { get; set; }
}
</code>```

public ActionResult TestUpload(bool testBool, [FromForm]
WrapperInput input) {

Then you get this (image below). Solved!

Body:
Asp.Net, .Net 5.0

I have this POST endpoint that requires to BOTH upload a file and a "complex" object (json). In order to test it, I use Swagger UI.

1. Testing the upload of a file alone is easy.

If the endpoint looks like this...

public ActionResult TestUpload(bool testBool, IFormFile file) {

...then Swagger UI looks like this :

2. Testing the upload of a json object alone is easy too.

public class DummyInput {
    public bool Field { get; set; }
}

If the endpoint looks like this...

public ActionResult TestUpload(bool testBool, DummyInput input) {

...then Swagger UI looks like this :

3. I can even make my life easier like this :

public ActionResult TestUpload(bool testBool, [FromForm] DummyInput input) {

That's great.

4. But what if I want BOTH the file and the 'input' json object ?

attempt #1 :

public ActionResult TestUpload(bool testBool, IFormFile file, DummyInput input) {

That obviously doesn't work because you cannot have two parameters "From body", there can be only one.

attempt #2:

public ActionResult TestUpload(bool testBool, [FromForm] IFormFile file, [FromForm]
DummyInput input) {

attempt #3:

public class WrapperInput {
    public DummyInput Input { get; set; }
    public IFormFile File { get; set; }
}

public ActionResult TestUpload(bool testBool, WrapperInput input) {

So, in conclusion :  how do I get to enter my nice fields AND my "Select file" button?
I've looked at this article but it seems overly complicated -- and to be honest I'm not sure it's even related to my needs. I have a feeling that it's for OpenApi 2.0 rather than the better things we get from OpenApi 3.0.

Body:
I found the right combination of settings, I was so close :

public class WrapperInput {
    public DummyInput Input { get; set; }
    public IFormFile File { get; set; }
}

public ActionResult TestUpload(bool testBool, [FromForm]
WrapperInput input) {

Then you get this (image below). Solved!