问:
How to change 'cost' of path here?
I'm reading this python code about A star algorithm. For me, I understand how this algorithm work, but when I come to the code I got some confusing things until to understand. I want to be able to change the cost of paths here. I mean I need to be able to set a cost to each pixel here while calculating the best path but I couldn't figure out where to do it. I have 2 paths and I want the algorithm to choose the bottom path because of the cost of the top path. How do I do that?

Image of the paths. I want algorithm to choose bottom one.

Entire code of the algorithm:

```<code>"""

A* grid planning

author: Atsushi Sakai(@Atsushi_twi)
        Nikos Kanargias (nkana@tee.gr)

See Wikipedia article (https://en.wikipedia.org/wiki/A*_search_algorithm)

"""

import math

import matplotlib.pyplot as plt

show_animation = True

class AStarPlanner:

    def __init__(self, ox, oy, reso, rr):
        """
        Initialize grid map for a star planning

        ox: x position list of Obstacles [m]
        oy: y position list of Obstacles [m]
        reso: grid resolution [m]
        rr: robot radius[m]
        """

        self.reso = reso
        self.rr = rr
        self.calc_obstacle_map(ox, oy)
        self.motion = self.get_motion_model()

    class Node:
        def __init__(self, x, y, cost, pind):
            self.x = x  # index of grid
            self.y = y  # index of grid
            self.cost = cost
            self.pind = pind

        def __str__(self):
            return str(self.x) + "," + str(self.y) + "," + str(
                self.cost) + "," + str(self.pind)

    def planning(self, sx, sy, gx, gy):
        """
        A star path search

        input:
            sx: start x position [m]
            sy: start y position [m]
            gx: goal x position [m]
            gy: goal y position [m]

        output:
            rx: x position list of the final path
            ry: y position list of the final path
        """

        nstart = self.Node(self.calc_xyindex(sx, self.minx),
                           self.calc_xyindex(sy, self.miny), 0.0, -1)
        ngoal = self.Node(self.calc_xyindex(gx, self.minx),
                          self.calc_xyindex(gy, self.miny), 0.0, -1)

        open_set, closed_set = dict(), dict()
        open_set[self.calc_grid_index(nstart)] = nstart

        while 1:
            if len(open_set) == 0:
                print("Open set is empty..")
                break

            c_id = min(
                open_set,
                key=lambda o: open_set[o].cost + self.calc_heuristic(ngoal,
                                                                     open_set[
                                                                         o]))
            current = open_set[c_id]

            # show graph
            if show_animation:  # pragma: no cover
                plt.plot(self.calc_grid_position(current.x, self.minx),
                         self.calc_grid_position(current.y, self.miny), "xc")
                # for stopping simulation with the esc key.
                plt.gcf().canvas.mpl_connect('key_release_event',
                                             lambda event: [exit(
                                                 0) if event.key == 'escape' else None])
                if len(closed_set.keys()) % 10 == 0:
                    plt.pause(0.001)

            if current.x == ngoal.x and current.y == ngoal.y:
                print("Find goal")
                ngoal.pind = current.pind
                ngoal.cost = current.cost
                break

            # Remove the item from the open set
            del open_set[c_id]

            # Add it to the closed set
            closed_set[c_id] = current

            # expand_grid search grid based on motion model
            for i, _ in enumerate(self.motion):
                node = self.Node(current.x + self.motion[i][0],
                                 current.y + self.motion[i][1],
                                 current.cost + self.motion[i][2], c_id)
                n_id = self.calc_grid_index(node)

                # If the node is not safe, do nothing
                if not self.verify_node(node):
                    continue

                if n_id in closed_set:
                    continue

                if n_id not in open_set:
                    open_set[n_id] = node  # discovered a new node
                else:
                    if open_set[n_id].cost > node.cost:
                        # This path is the best until now. record it
                        open_set[n_id] = node

        rx, ry = self.calc_final_path(ngoal, closed_set)

        return rx, ry

    def calc_final_path(self, ngoal, closedset):
        # generate final course
        rx, ry = [self.calc_grid_position(ngoal.x, self.minx)], [
            self.calc_grid_position(ngoal.y, self.miny)]
        pind = ngoal.pind
        while pind != -1:
            n = closedset[pind]
            rx.append(self.calc_grid_position(n.x, self.minx))
            ry.append(self.calc_grid_position(n.y, self.miny))
            pind = n.pind

        return rx, ry

    @staticmethod
    def calc_heuristic(n1, n2):
        w = 1.0  # weight of heuristic
        d = w * math.hypot(n1.x - n2.x, n1.y - n2.y)
        return d

    def calc_grid_position(self, index, minp):
        """
        calc grid position

        :param index:
        :param minp:
        :return:
        """
        pos = index * self.reso + minp
        return pos

    def calc_xyindex(self, position, min_pos):
        return round((position - min_pos) / self.reso)

    def calc_grid_index(self, node):
        return (node.y - self.miny) * self.xwidth + (node.x - self.minx)

    def verify_node(self, node):
        px = self.calc_grid_position(node.x, self.minx)
        py = self.calc_grid_position(node.y, self.miny)

        if px < self.minx:
            return False
        elif py < self.miny:
            return False
        elif px >= self.maxx:
            return False
        elif py >= self.maxy:
            return False

        # collision check
        if self.obmap[node.x][node.y]:
            return False

        return True

    def calc_obstacle_map(self, ox, oy):

        self.minx = round(min(ox))
        self.miny = round(min(oy))
        self.maxx = round(max(ox))
        self.maxy = round(max(oy))
        print("minx:", self.minx)
        print("miny:", self.miny)
        print("maxx:", self.maxx)
        print("maxy:", self.maxy)

        self.xwidth = round((self.maxx - self.minx) / self.reso)
        self.ywidth = round((self.maxy - self.miny) / self.reso)
        print("xwidth:", self.xwidth)
        print("ywidth:", self.ywidth)

        # obstacle map generation
        self.obmap = [[False for i in range(self.ywidth)]
                      for i in range(self.xwidth)]
        for ix in range(self.xwidth):
            x = self.calc_grid_position(ix, self.minx)
            for iy in range(self.ywidth):
                y = self.calc_grid_position(iy, self.miny)
                for iox, ioy in zip(ox, oy):
                    d = math.hypot(iox - x, ioy - y)
                    if d <= self.rr:
                        self.obmap[ix][iy] = True
                        break

    @staticmethod
    def get_motion_model():
        # dx, dy, cost
        motion = [[1, 0, 1],
                  [0, 1, 1],
                  [-1, 0, 1],
                  [0, -1, 1],
                  [-1, -1, math.sqrt(2)],
                  [-1, 1, math.sqrt(2)],
                  [1, -1, math.sqrt(2)],
                  [1, 1, math.sqrt(2)]]

        return motion

def main():
    print(__file__ + " start!!")

    # start and goal position
    sx = 1.0  # [m]
    sy = 1.0  # [m]
    gx = 50.0  # [m]
    gy = 50.0  # [m]
    grid_size = 10.0  # [m]
    robot_radius = 1.0  # [m]

    # set obstacle positions
    ox, oy = [], []
    for i in range(-10, 60):
        ox.append(i)
        oy.append(-10.0)
    for i in range(-10, 60):
        ox.append(60.0)
        oy.append(i)
    for i in range(-10, 61):
        ox.append(i)
        oy.append(60.0)
    for i in range(-10, 61):
        ox.append(-10.0)
        oy.append(i)
    for i in range(-10, 40):
        ox.append(20.0)
        oy.append(i)
    for i in range(0, 10):
        ox.append(40.0)
        oy.append(i)
    for i in range(0, 40):
        ox.append(40.0)
        oy.append(60.0 - i)

    if show_animation:  # pragma: no cover
        plt.plot(ox, oy, ".k")
        plt.plot(sx, sy, "og")
        plt.plot(gx, gy, "xb")
        plt.grid(True)
        plt.axis("equal")

    a_star = AStarPlanner(ox, oy, grid_size, robot_radius)
    rx, ry = a_star.planning(sx, sy, gx, gy)

    if show_animation:  # pragma: no cover
        plt.plot(rx, ry, "-r")
        plt.show()
        plt.pause(0.001)

if __name__ == '__main__':
    main()
</code>```

答:
I did it with adding a part of code like that</p>

```<code> # expand_grid search grid based on motion model
        for i, _ in enumerate(self.motion):
            cost = 0
            if(current.x + self.motion[i][0] >= 45 and (current.x + self.motion[i][0]) <= 55 and current.y + self.motion[i][1] >= 20 and current.y + self.motion[i][1] <= 31):
                cost = 15

            node = self.Node(current.x + self.motion[i][0],
                             current.y + self.motion[i][1],
                             current.cost + self.motion[i][2] + cost, c_id)
            n_id = self.calc_grid_index(node)
</code>```

Title: How to change 'cost' of path here?

Body:
I'm reading this python code about A star algorithm. For me, I understand how this algorithm work, but when I come to the code I got some confusing things until to understand. I want to be able to change the cost of paths here. I mean I need to be able to set a cost to each pixel here while calculating the best path but I couldn't figure out where to do it. I have 2 paths and I want the algorithm to choose the bottom path because of the cost of the top path. How do I do that?

Image of the paths. I want algorithm to choose bottom one.

Entire code of the algorithm:

"""

A* grid planning

author: Atsushi Sakai(@Atsushi_twi)
        Nikos Kanargias (nkana@tee.gr)

See Wikipedia article (https://en.wikipedia.org/wiki/A*_search_algorithm)

"""

import math

import matplotlib.pyplot as plt

show_animation = True

class AStarPlanner:

    def __init__(self, ox, oy, reso, rr):
        """
        Initialize grid map for a star planning

        ox: x position list of Obstacles [m]
        oy: y position list of Obstacles [m]
        reso: grid resolution [m]
        rr: robot radius[m]
        """

        self.reso = reso
        self.rr = rr
        self.calc_obstacle_map(ox, oy)
        self.motion = self.get_motion_model()

    class Node:
        def __init__(self, x, y, cost, pind):
            self.x = x  # index of grid
            self.y = y  # index of grid
            self.cost = cost
            self.pind = pind

        def __str__(self):
            return str(self.x) + "," + str(self.y) + "," + str(
                self.cost) + "," + str(self.pind)

    def planning(self, sx, sy, gx, gy):
        """
        A star path search

        input:
            sx: start x position [m]
            sy: start y position [m]
            gx: goal x position [m]
            gy: goal y position [m]

        output:
            rx: x position list of the final path
            ry: y position list of the final path
        """

        nstart = self.Node(self.calc_xyindex(sx, self.minx),
                           self.calc_xyindex(sy, self.miny), 0.0, -1)
        ngoal = self.Node(self.calc_xyindex(gx, self.minx),
                          self.calc_xyindex(gy, self.miny), 0.0, -1)

        open_set, closed_set = dict(), dict()
        open_set[self.calc_grid_index(nstart)] = nstart

        while 1:
            if len(open_set) == 0:
                print("Open set is empty..")
                break

            c_id = min(
                open_set,
                key=lambda o: open_set[o].cost + self.calc_heuristic(ngoal,
                                                                     open_set[
                                                                         o]))
            current = open_set[c_id]

            # show graph
            if show_animation:  # pragma: no cover
                plt.plot(self.calc_grid_position(current.x, self.minx),
                         self.calc_grid_position(current.y, self.miny), "xc")
                # for stopping simulation with the esc key.
                plt.gcf().canvas.mpl_connect('key_release_event',
                                             lambda event: [exit(
                                                 0) if event.key == 'escape' else None])
                if len(closed_set.keys()) % 10 == 0:
                    plt.pause(0.001)

            if current.x == ngoal.x and current.y == ngoal.y:
                print("Find goal")
                ngoal.pind = current.pind
                ngoal.cost = current.cost
                break

            # Remove the item from the open set
            del open_set[c_id]

            # Add it to the closed set
            closed_set[c_id] = current

            # expand_grid search grid based on motion model
            for i, _ in enumerate(self.motion):
                node = self.Node(current.x + self.motion[i][0],
                                 current.y + self.motion[i][1],
                                 current.cost + self.motion[i][2], c_id)
                n_id = self.calc_grid_index(node)

                # If the node is not safe, do nothing
                if not self.verify_node(node):
                    continue

                if n_id in closed_set:
                    continue

                if n_id not in open_set:
                    open_set[n_id] = node  # discovered a new node
                else:
                    if open_set[n_id].cost > node.cost:
                        # This path is the best until now. record it
                        open_set[n_id] = node

        rx, ry = self.calc_final_path(ngoal, closed_set)

        return rx, ry

    def calc_final_path(self, ngoal, closedset):
        # generate final course
        rx, ry = [self.calc_grid_position(ngoal.x, self.minx)], [
            self.calc_grid_position(ngoal.y, self.miny)]
        pind = ngoal.pind
        while pind != -1:
            n = closedset[pind]
            rx.append(self.calc_grid_position(n.x, self.minx))
            ry.append(self.calc_grid_position(n.y, self.miny))
            pind = n.pind

        return rx, ry

    @staticmethod
    def calc_heuristic(n1, n2):
        w = 1.0  # weight of heuristic
        d = w * math.hypot(n1.x - n2.x, n1.y - n2.y)
        return d

    def calc_grid_position(self, index, minp):
        """
        calc grid position

        :param index:
        :param minp:
        :return:
        """
        pos = index * self.reso + minp
        return pos

    def calc_xyindex(self, position, min_pos):
        return round((position - min_pos) / self.reso)

    def calc_grid_index(self, node):
        return (node.y - self.miny) * self.xwidth + (node.x - self.minx)

    def verify_node(self, node):
        px = self.calc_grid_position(node.x, self.minx)
        py = self.calc_grid_position(node.y, self.miny)

        if px < self.minx:
            return False
        elif py < self.miny:
            return False
        elif px >= self.maxx:
            return False
        elif py >= self.maxy:
            return False

        # collision check
        if self.obmap[node.x][node.y]:
            return False

        return True

    def calc_obstacle_map(self, ox, oy):

        self.minx = round(min(ox))
        self.miny = round(min(oy))
        self.maxx = round(max(ox))
        self.maxy = round(max(oy))
        print("minx:", self.minx)
        print("miny:", self.miny)
        print("maxx:", self.maxx)
        print("maxy:", self.maxy)

        self.xwidth = round((self.maxx - self.minx) / self.reso)
        self.ywidth = round((self.maxy - self.miny) / self.reso)
        print("xwidth:", self.xwidth)
        print("ywidth:", self.ywidth)

        # obstacle map generation
        self.obmap = [[False for i in range(self.ywidth)]
                      for i in range(self.xwidth)]
        for ix in range(self.xwidth):
            x = self.calc_grid_position(ix, self.minx)
            for iy in range(self.ywidth):
                y = self.calc_grid_position(iy, self.miny)
                for iox, ioy in zip(ox, oy):
                    d = math.hypot(iox - x, ioy - y)
                    if d <= self.rr:
                        self.obmap[ix][iy] = True
                        break

    @staticmethod
    def get_motion_model():
        # dx, dy, cost
        motion = [[1, 0, 1],
                  [0, 1, 1],
                  [-1, 0, 1],
                  [0, -1, 1],
                  [-1, -1, math.sqrt(2)],
                  [-1, 1, math.sqrt(2)],
                  [1, -1, math.sqrt(2)],
                  [1, 1, math.sqrt(2)]]

        return motion

def main():
    print(__file__ + " start!!")

    # start and goal position
    sx = 1.0  # [m]
    sy = 1.0  # [m]
    gx = 50.0  # [m]
    gy = 50.0  # [m]
    grid_size = 10.0  # [m]
    robot_radius = 1.0  # [m]

    # set obstacle positions
    ox, oy = [], []
    for i in range(-10, 60):
        ox.append(i)
        oy.append(-10.0)
    for i in range(-10, 60):
        ox.append(60.0)
        oy.append(i)
    for i in range(-10, 61):
        ox.append(i)
        oy.append(60.0)
    for i in range(-10, 61):
        ox.append(-10.0)
        oy.append(i)
    for i in range(-10, 40):
        ox.append(20.0)
        oy.append(i)
    for i in range(0, 10):
        ox.append(40.0)
        oy.append(i)
    for i in range(0, 40):
        ox.append(40.0)
        oy.append(60.0 - i)

    if show_animation:  # pragma: no cover
        plt.plot(ox, oy, ".k")
        plt.plot(sx, sy, "og")
        plt.plot(gx, gy, "xb")
        plt.grid(True)
        plt.axis("equal")

    a_star = AStarPlanner(ox, oy, grid_size, robot_radius)
    rx, ry = a_star.planning(sx, sy, gx, gy)

    if show_animation:  # pragma: no cover
        plt.plot(rx, ry, "-r")
        plt.show()
        plt.pause(0.001)

if __name__ == '__main__':
    main()

Body:
I did it with adding a part of code like that

 # expand_grid search grid based on motion model
        for i, _ in enumerate(self.motion):
            cost = 0
            if(current.x + self.motion[i][0] >= 45 and (current.x + self.motion[i][0]) <= 55 and current.y + self.motion[i][1] >= 20 and current.y + self.motion[i][1] <= 31):
                cost = 15

            node = self.Node(current.x + self.motion[i][0],
                             current.y + self.motion[i][1],
                             current.cost + self.motion[i][2] + cost, c_id)
            n_id = self.calc_grid_index(node)


来源: stackexchange

问:
Scrape Genius Lyrics
So I have to do a project for school, I need to create a simple website who uses an API. I want to use the genius API to collect the lyrics but you can't because of copyright. I can only use the API to find certain information about a song like creator, url of the cover{image}, or song link (genius). So if I want to get the lyrics I need to scrape the link of the song. I have some problems with scraping because it's usually accomplished with node.js and I can't use node.js because it's not allowed in the project.

Do anybody have an idea how to scrape this link to find the lyrics only with pure javascript (i can also use jQuery): https://genius.com/Lil-peep-white-tee-lyrics

I know that the html page contain a tag  and all the lyrics are here.

Example :

```<code><div class="lyrics">
   <p> This is the lyrics</p>
</div>
</code>```

If anybody has an idea it would be very helpful. Thanks

答:
By using jQuery try to learn how to select specific html section by tag, class or id.</p>

```<code>var myLyrics = $('.lyrics').find('div:first').find('p:first').html();
alert(myLyrics);
</code>```

ContentLicense: CC BY-SA 4.0

Title: Scrape Genius Lyrics

Body:
So I have to do a project for school, I need to create a simple website who uses an API. I want to use the genius API to collect the lyrics but you can't because of copyright. I can only use the API to find certain information about a song like creator, url of the cover{image}, or song link (genius). So if I want to get the lyrics I need to scrape the link of the song. I have some problems with scraping because it's usually accomplished with node.js and I can't use node.js because it's not allowed in the project.

Do anybody have an idea how to scrape this link to find the lyrics only with pure javascript (i can also use jQuery): https://genius.com/Lil-peep-white-tee-lyrics

I know that the html page contain a tag  and all the lyrics are here.

Example :

 This is the lyrics

If anybody has an idea it would be very helpful. Thanks

Body:
By using jQuery try to learn how to select specific html section by tag, class or id.

var myLyrics = $('.lyrics').find('div:first').find('p:first').html();
alert(myLyrics);


问:
Trouble with pycurl.POSTFIELDS
I'm familiar with CURL in PHP but am using it for the first time in Python with pycurl.

I keep getting the error:

```<code>Exception Type:     error
Exception Value:    (2, '')
</code>```

I have no idea what this could mean.  Here is my code:

```<code>data = {'cmd': '_notify-synch',
        'tx': str(request.GET.get('tx')),
        'at': paypal_pdt_test
        }

post = urllib.urlencode(data)

b = StringIO.StringIO()

ch = pycurl.Curl()
ch.setopt(pycurl.URL, 'https://www.sandbox.paypal.com/cgi-bin/webscr')
ch.setopt(pycurl.POST, 1)
ch.setopt(pycurl.POSTFIELDS, post)
ch.setopt(pycurl.WRITEFUNCTION, b.write)
ch.perform()
ch.close()
</code>```

The error is referring to the line ch.setopt(pycurl.POSTFIELDS, post)

答: I know this is an old post but I've just spent my morning trying to track down this same error.  It turns out that there's a bug in pycurl that was fixed in 7.16.2.1 that caused setopt() to break on 64-bit machines.</p>

ContentLicense: CC BY-SA 2.5

Title: Trouble with pycurl.POSTFIELDS

Body:
I'm familiar with CURL in PHP but am using it for the first time in Python with pycurl.

I keep getting the error:

Exception Type:     error
Exception Value:    (2, '')

I have no idea what this could mean.  Here is my code:

data = {'cmd': '_notify-synch',
        'tx': str(request.GET.get('tx')),
        'at': paypal_pdt_test
        }

post = urllib.urlencode(data)

b = StringIO.StringIO()

ch = pycurl.Curl()
ch.setopt(pycurl.URL, 'https://www.sandbox.paypal.com/cgi-bin/webscr')
ch.setopt(pycurl.POST, 1)
ch.setopt(pycurl.POSTFIELDS, post)
ch.setopt(pycurl.WRITEFUNCTION, b.write)
ch.perform()
ch.close()

The error is referring to the line ch.setopt(pycurl.POSTFIELDS, post)

ContentLicense: CC BY-SA 3.0


问:
Group and sum by week
I have a dataframe where the columns are by day in this format:

```<code>a    b    c     01/01/2020  01/02/2020  01/03/2020 ...
1000 2000 3000  2           5           7
.
.
.
</code>```

These are just arbitrary values. What I want is to sum the date columns and group them by week, like week_1, week_2,... so on and so forth. So for the example above it would look like:

```<code>a    b    c     week_1...
1000 2000 3000  14
.
.
.
</code>```

Is there a clean way to do it for columns? I know I can sum all the columns by selecting the date columns and summing them on the axis, but I'm not sure how to do it per week. Any help is appreciated!

答:
You can do:

```<code># move `a`, `b`, `c` out of columns
df = df.set_index(['a','b','c'])

# convert columns to datetime
df.columns = pd.to_datetime(df.columns)

# groupby sum:
(df.groupby(df.columns.week, axis=1)
   .sum()
   .add_prefix('week_')
   .reset_index()
)
</code>```

Output:

```<code>      a     b     c   week_1
0  1000  2000  3000       14
</code>```

Title: Group and sum by week

Body:
I have a dataframe where the columns are by day in this format:

a    b    c     01/01/2020  01/02/2020  01/03/2020 ...
1000 2000 3000  2           5           7
.
.
.

These are just arbitrary values. What I want is to sum the date columns and group them by week, like week_1, week_2,... so on and so forth. So for the example above it would look like:

a    b    c     week_1...
1000 2000 3000  14
.
.
.

Is there a clean way to do it for columns? I know I can sum all the columns by selecting the date columns and summing them on the axis, but I'm not sure how to do it per week. Any help is appreciated!

Body:
You can do:

# move `a`, `b`, `c` out of columns
df = df.set_index(['a','b','c'])

# convert columns to datetime
df.columns = pd.to_datetime(df.columns)

# groupby sum:
(df.groupby(df.columns.week, axis=1)
   .sum()
   .add_prefix('week_')
   .reset_index()
)

Output:

      a     b     c   week_1
0  1000  2000  3000       14


问:
Write a basic function in R to get the interquartile (Q3-Q1)
I have a question for the code as follows. The question is shown below.

Write a basic function (call it getIQR) that takes in a vector of numbers and returns the interquartile
range (75th percentile - 25th percentile). You can use the quantile function. Remove the name on the
returned vector (i.e. make sure the returned item doesn’t have a name like 75% or something like that).
Allow your function to pass unnamed arguments to the quantile function.

Have your function check if the passed value is numeric and if it is appropriate for this argument (i.e. is a vector or a data frame/tibble with only one column - don’t allow for matrices) - if not, stop the
function and return an appropriate message.

Note: trying to deal with data frames/tibbles of 1 dimension was a bit tricky for me. I first checked
if it was a data frame, if so, I checked if it had only one column. If those were both true I converted
that column to a vector (using [[ or pull). I then checked to see if the value was not numeric or not a
vector.

Here is my partial code and I do not know why it fails to work out.

```<code># Write the function
getIQR <- function(vec){
  if(!is.data.frame(vec)){
    stop("This function first requires a data.frame.")
  }
  if(ncol(vec) != 1){
   stop("This function requires only one column.")
  }
  if(is.data.frame(vec) && ncol(vec) == 1){
    as.numeric(t(vec))
  }
  if(!is.numeric(vec)){
    stop("This function only works for a numeric")
  }

  Q3 <- quantile(vec, .75)
  Q1 <- quantile(vec, .25)
  IQR <- Q3 - Q1
  IQR
}

vec <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
getIQR(vec)
</code>```

It always says that "This function first requires a data.frame." What else should I input according to the note?

Thanks  so much for your kind help.

答:
The following code

```<code>if(!is.data.frame(vec)){
  stop("This function first requires a data.frame.")
}
</code>```

is meant to produce an error message if you don't provide an object of type data.frame to your function. It's an input type check.

The object you provide:

```<code>vec <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
</code>```

is not a data.frame, but a numeric vector. Therefore you get the error.

So either you decide that your function expects vec to be a vector, in that case remove the if clauses and maybe add

```<code>if(!is.numeric(vec)){
    stop("Input is not a numeric vector")
}
</code>```

to check for it. Or, you or you provide a data.frame to your function

```<code>vec <- data.frame(x = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
</code>```

However, then you need to correct one more error in your function: You forgot to assign the result of

```<code>as.numeric(t(vec))
</code>```

to any variable (using <-), so this code can have no effect

Body:
I have a question for the code as follows. The question is shown below.

Write a basic function (call it getIQR) that takes in a vector of numbers and returns the interquartile
range (75th percentile - 25th percentile). You can use the quantile function. Remove the name on the
returned vector (i.e. make sure the returned item doesn’t have a name like 75% or something like that).
Allow your function to pass unnamed arguments to the quantile function.

Have your function check if the passed value is numeric and if it is appropriate for this argument (i.e. is a vector or a data frame/tibble with only one column - don’t allow for matrices) - if not, stop the
function and return an appropriate message.

Note: trying to deal with data frames/tibbles of 1 dimension was a bit tricky for me. I first checked
if it was a data frame, if so, I checked if it had only one column. If those were both true I converted
that column to a vector (using [[ or pull). I then checked to see if the value was not numeric or not a
vector.

Here is my partial code and I do not know why it fails to work out.

# Write the function
getIQR <- function(vec){
  if(!is.data.frame(vec)){
    stop("This function first requires a data.frame.")
  }
  if(ncol(vec) != 1){
   stop("This function requires only one column.")
  }
  if(is.data.frame(vec) && ncol(vec) == 1){
    as.numeric(t(vec))
  }
  if(!is.numeric(vec)){
    stop("This function only works for a numeric")
  }

  Q3 <- quantile(vec, .75)
  Q1 <- quantile(vec, .25)
  IQR <- Q3 - Q1
  IQR
}

vec <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
getIQR(vec)

It always says that "This function first requires a data.frame." What else should I input according to the note?

Thanks  so much for your kind help.

Body:
The following code

if(!is.data.frame(vec)){
  stop("This function first requires a data.frame.")
}

is meant to produce an error message if you don't provide an object of type data.frame to your function. It's an input type check.

The object you provide:

vec <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

is not a data.frame, but a numeric vector. Therefore you get the error.

So either you decide that your function expects vec to be a vector, in that case remove the if clauses and maybe add

if(!is.numeric(vec)){
    stop("Input is not a numeric vector")
}

to check for it. Or, you or you provide a data.frame to your function

vec <- data.frame(x = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))

However, then you need to correct one more error in your function: You forgot to assign the result of

as.numeric(t(vec))

to any variable (using <-), so this code can have no effect


问:
name 'doc2vec' is not defined
I am trying to use doc2vec for text classification but after importing when i am trying to use it inside a function its says doc2vec in not defined. Please help me to identify which all libraries should I be installing to use doc2vec.

here I have 2 columns called Action(Text or sentences) and Category(actual tags)

```<code>from gensim.models import Doc2Vec
import gensim
from gensim.models.doc2vec import TaggedDocument
def label_sentences(corpus, label_type):
    labeled = []
    for i, v in enumerate(corpus):
        label = label_type + '_' + str(i)
        labeled.append(doc2vec.TaggedDocument(v.split(), [label]))
    return labeled
X_train, X_test, y_train, y_test = train_test_split(df.Action, df.Category, random_state=0, test_size=0.3)
X_train = label_sentences(X_train, 'Train')

Error
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-66-d20e5f21684d> in <module>
----> 1 X_train = label_sentences(X_train, 'Train')

<ipython-input-53-bca3c695cfb6> in label_sentences(corpus, label_type)
      8     for i, v in enumerate(corpus):
      9         label = label_type + '_' + str(i)
---> 10         labeled.append(doc2vec.TaggedDocument(v.split(), [label]))
     11     return labeled

NameError: name 'doc2vec' is not defined
</code>```

答:
from gensim.models import doc2vec
or
labeled.append(TaggedDocument(v.split(), [label]))

works fine

Title: name 'doc2vec' is not defined

Body:
I am trying to use doc2vec for text classification but after importing when i am trying to use it inside a function its says doc2vec in not defined. Please help me to identify which all libraries should I be installing to use doc2vec.

here I have 2 columns called Action(Text or sentences) and Category(actual tags)

from gensim.models import Doc2Vec
import gensim
from gensim.models.doc2vec import TaggedDocument
def label_sentences(corpus, label_type):
    labeled = []
    for i, v in enumerate(corpus):
        label = label_type + '_' + str(i)
        labeled.append(doc2vec.TaggedDocument(v.split(), [label]))
    return labeled
X_train, X_test, y_train, y_test = train_test_split(df.Action, df.Category, random_state=0, test_size=0.3)
X_train = label_sentences(X_train, 'Train')

Error
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-66-d20e5f21684d> in <module>
----> 1 X_train = label_sentences(X_train, 'Train')

<ipython-input-53-bca3c695cfb6> in label_sentences(corpus, label_type)
      8     for i, v in enumerate(corpus):
      9         label = label_type + '_' + str(i)
---> 10         labeled.append(doc2vec.TaggedDocument(v.split(), [label]))
     11     return labeled

NameError: name 'doc2vec' is not defined


问:
How to edit values in `Option` by reference
Given some list of options of big structs:

```<code>struct big_struct {
    a:i32 // Imagine this is some big datatype
}

let mut tester:Vec<Option<(big_struct,big_struct)>> = vec![
    None,
    Some((big_struct{a:1},big_struct{a:2})),
    None,
];
</code>```

I'm iterating over this list, by another check I know which elements have Some, on these elements I want to call a function which edits their values

Example function:

```<code>fn tester_method(pos:&mut (big_struct,big_struct)) {
    pos.0 = big_struct {a:8};
    pos.1 = big_struct {a:9};
}
</code>```

Function call which doesn't work: tester_method(&mut tester[1].unwrap());

How can I do this?

On the function call I get the error:

```<code>cannot move out of index of `std::vec::Vec<std::option::Option<(big_struct, big_struct)>>`
move occurs because value has type `std::option::Option<(big_struct, big_struct)>`, which does not implement the `Copy` traitrustc(E0507)
main.rs(132, 24): consider borrowing the `Option`'s content
</code>```

答:
Calling: tester_method(tester[1].as_mut().unwrap()); fixes it.

.as_mut()

Body:
Given some list of options of big structs:

struct big_struct {
    a:i32 // Imagine this is some big datatype
}

let mut tester:Vec<Option<(big_struct,big_struct)>> = vec![
    None,
    Some((big_struct{a:1},big_struct{a:2})),
    None,
];

I'm iterating over this list, by another check I know which elements have Some, on these elements I want to call a function which edits their values

Example function:

fn tester_method(pos:&mut (big_struct,big_struct)) {
    pos.0 = big_struct {a:8};
    pos.1 = big_struct {a:9};
}

Function call which doesn't work: tester_method(&mut tester[1].unwrap());

How can I do this?

On the function call I get the error:

cannot move out of index of `std::vec::Vec<std::option::Option<(big_struct, big_struct)>>`
move occurs because value has type `std::option::Option<(big_struct, big_struct)>`, which does not implement the `Copy` traitrustc(E0507)
main.rs(132, 24): consider borrowing the `Option`'s content


问:
Java CDF file Parsing with UnsatisfiedLinkError
I am working on a CDF(file mastercard uses) file parser in Java and I am using the API found here. In order to use this API you need the jar file..

I don't understand how I am getting this exception since it should be handled in the getFile() method.. I google'd around and I still don't understand what the issue is.. if anyone can point me in the right direction that would be great. By following the stacktrace.. to me it seems it's an issue with the library.

The link to the api is found here: http://cdf.gsfc.nasa.gov/cdfjava_doc/cdf34/

When trying to open a CDF file I am getting this error after running the program:

```<code>    Exception in thread "main" java.lang.UnsatisfiedLinkError: no cdfNativeLibrary in jav
a.library.path
        at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1860)
        at java.lang.Runtime.loadLibrary0(Runtime.java:845)
        at java.lang.System.loadLibrary(System.java:1084)
        at gsfc.nssdc.cdf.CDFNativeLibrary.<clinit>(CDFNativeLibrary.java:47)
        at gsfc.nssdc.cdf.CDF.open(CDF.java:426)
        at gsfc.nssdc.cdf.CDF.open(CDF.java:385)
        at FileModel.getFile(FileModel.java:21)
        at FileModel.main(FileModel.java:9)
</code>```

Here is my source code:

```<code>import gsfc.nssdc.cdf.*;
import gsfc.nssdc.cdf.util.*;

public class FileModel
{

    public static void main(String[] args)
    {
        getFile();
    }

    public static void getFile()
    {

        try
        {
            CDF cdf = CDF.open("outbound_MidCycle_File.xml");
            //System.out.println(cdf.getID());
        }
        catch(CDFException e)
        {
            System.out.println("ERROR Cannot open CDF File");
        }
        catch(Exception e)
        {
            System.out.println("ERROR");
            System.out.println(e.getMessage());
            e.printStackTrace();
        }

    }

}
</code>```

The commands I run are as follows:

```<code>javac -cp '.:cdfjava.jar' FileModel.java
java -cp '.:cdfjava.jar' FileModel
</code>```

答: The CDF library you got is one we use in Space Physics, for a particular file format, and has nothing to do with </p>

Body:
I am working on a CDF(file mastercard uses) file parser in Java and I am using the API found here. In order to use this API you need the jar file..

I don't understand how I am getting this exception since it should be handled in the getFile() method.. I google'd around and I still don't understand what the issue is.. if anyone can point me in the right direction that would be great. By following the stacktrace.. to me it seems it's an issue with the library.

The link to the api is found here: http://cdf.gsfc.nasa.gov/cdfjava_doc/cdf34/

When trying to open a CDF file I am getting this error after running the program:

    Exception in thread "main" java.lang.UnsatisfiedLinkError: no cdfNativeLibrary in jav
a.library.path
        at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1860)
        at java.lang.Runtime.loadLibrary0(Runtime.java:845)
        at java.lang.System.loadLibrary(System.java:1084)
        at gsfc.nssdc.cdf.CDFNativeLibrary.<clinit>(CDFNativeLibrary.java:47)
        at gsfc.nssdc.cdf.CDF.open(CDF.java:426)
        at gsfc.nssdc.cdf.CDF.open(CDF.java:385)
        at FileModel.getFile(FileModel.java:21)
        at FileModel.main(FileModel.java:9)

Here is my source code:

import gsfc.nssdc.cdf.*;
import gsfc.nssdc.cdf.util.*;

public class FileModel
{

    public static void main(String[] args)
    {
        getFile();
    }

    public static void getFile()
    {

        try
        {
            CDF cdf = CDF.open("outbound_MidCycle_File.xml");
            //System.out.println(cdf.getID());
        }
        catch(CDFException e)
        {
            System.out.println("ERROR Cannot open CDF File");
        }
        catch(Exception e)
        {
            System.out.println("ERROR");
            System.out.println(e.getMessage());
            e.printStackTrace();
        }

    }

}

The commands I run are as follows:

javac -cp '.:cdfjava.jar' FileModel.java
java -cp '.:cdfjava.jar' FileModel


问:
.NET Regex: Get all matched groups
I've stuck with regex problem using .NET. For example, I have next regex pattern: (?'group1'A|C)|(?'group2'B|C)|(?'group3'A|B|C)

When I do match of "AXYZ" I receive match object which contains Value and Groups; if I go to Groups I'll see that only one group has success in true - group1 (group3 is in false). If I do match of "BXYZ" I'll receive only group2 with success in true (group3 is in false).

How could I receive in match not only one group but all groups satisfying the match?

For example above it should be: group1 & group3 in "AXYZ" and group2 & group3 in "BXYZ".

All above is only example in real system there are different patterns (3+ letters each) and more complicated input text (1000+ words).

答:
The question seems a little abstract, but if you insist on a single regex you can do something like this, using optional lookaheads:

```<code>(?=(?'group1'A|C)?)(?=(?'group2'B|C)?)(?=(?'group3'A|B|C)?)
</code>```

Lookaheads match but don't capture, so your match will be empty in this case, but the groups will be as you expect, and may overlap.

Working example: http://ideone.com/PTtQu

Title: .NET Regex: Get all matched groups

Body:
The question seems a little abstract, but if you insist on a single regex you can do something like this, using optional lookaheads:

(?=(?'group1'A|C)?)(?=(?'group2'B|C)?)(?=(?'group3'A|B|C)?)

Lookaheads match but don't capture, so your match will be empty in this case, but the groups will be as you expect, and may overlap.

Working example: http://ideone.com/PTtQu


问:
Email address regular expression, limited character before and after @ symbol
I have a regexp that check for valid email.

/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

how would I limit the number of character before @ to 64 and after @ to 64.

答:
Here is a simple regex example:

```<code>/^[a-zA-Z]{7}$/
</code>```

This expression means:

A single character between A-Z

A single character between a-z

Finally, matches exactly 7 times -> {7}

You can simply add your regex {64} to check if it's 64 character long or not.

Body:
Here is a simple regex example:

/^[a-zA-Z]{7}$/

This expression means:

A single character between A-Z

A single character between a-z

Finally, matches exactly 7 times -> {7}

You can simply add your regex {64} to check if it's 64 character long or not.


问:
Can a class method call an instance method in python?
I am learning to program a binary tree and I want to check if a given number is already in the tree so when I try to add the same number it stops.

```<code>class Node:

    exist = True

    @classmethod
    def num_exist(cls, n):
        cls.exist = cls.find(n)

    def find(self, n):

        if n != self.value:
            if n < self.value:
                if self.right != None:
                    self.right.find(n)

                else:
                    return False

            if n > self.value:
                if self.left != None:
                    self.left.find(n)

                else:
                    return False
        else:
            return self

    def add(self, n):

        self.num_exist(n)

        if self.exist == False:
            if n != self.value:
                if n < self.value:
                    if self.right != None:
                    self.add(n)

                else:
                    self.right = Node(n)

            if n > self.value:
                if self.left != None:
                    self.add(n)

                else:
                    self.left = Node(n)
</code>```

The problem here is that when I call the function num_exist() it gives me the following error:

```<code>TypeError: find() missing 1 required positional argument: 'n'
</code>```

I suppose this error is because the self parameter hasn't been passed, but I don't know how to do it or if it is possible to pass the function find() to the @classmethod. I'm pretty newbie in oop.

答: What you are trying to do makes no sense. You are trying to find the number n in a given tree, which is an instance, so what does it mean for it to be a class method?

Body:
I am learning to program a binary tree and I want to check if a given number is already in the tree so when I try to add the same number it stops.

class Node:

    exist = True

    @classmethod
    def num_exist(cls, n):
        cls.exist = cls.find(n)

    def find(self, n):

        if n != self.value:
            if n < self.value:
                if self.right != None:
                    self.right.find(n)

                else:
                    return False

            if n > self.value:
                if self.left != None:
                    self.left.find(n)

                else:
                    return False
        else:
            return self

    def add(self, n):

        self.num_exist(n)

        if self.exist == False:
            if n != self.value:
                if n < self.value:
                    if self.right != None:
                    self.add(n)

                else:
                    self.right = Node(n)

            if n > self.value:
                if self.left != None:
                    self.add(n)

                else:
                    self.left = Node(n)

The problem here is that when I call the function num_exist() it gives me the following error:

TypeError: find() missing 1 required positional argument: 'n'

I suppose this error is because the self parameter hasn't been passed, but I don't know how to do it or if it is possible to pass the function find() to the @classmethod. I'm pretty newbie in oop.


问:
Vuetify combobox not getting focus after clicking cancel on dialog
I have a v-combobox component in my app. I have it to where I can type something in the input then @blur a check happens to see if the typed Item exists in the list or not. If it does not exist a modal opens up asking the user if they want to add it to the list.

I have it if the user clicks yes it is added to the list the problem I am having is if they click cancel and the dialog is closed focus should go back to the combobx input

When I try and set the focus I get the blue animation bar but no input cursor in the input of the combo box

I have set up a codesandbox example of my issue

CodeSandbox Example of Issue

I was wondering If i could get some help or pointers on why Im not getting the full focus to be able to type after clicking cancel on the dialog .

答:
You can try to use $nextTick like this:</p>

```<code>    closeConfirmationDialog() {
      // const comboBox = this.$refs[this.forInput];
      // comboBox.$el.querySelector("input").focus();
      this.showDialog = false;
      this.cancelDialog = true;
      this.$nextTick(() => {
        this.$refs.categories.focus();
      });
    }
</code>```

Body:
You can try to use $nextTick like this:

    closeConfirmationDialog() {
      // const comboBox = this.$refs[this.forInput];
      // comboBox.$el.querySelector("input").focus();
      this.showDialog = false;
      this.cancelDialog = true;
      this.$nextTick(() => {
        this.$refs.categories.focus();
      });
    }


问:
Flutter: How can I style the title of FlexibleSpaceBar?
I would like to create a title with highlighted text like this one in a SliverAppBar</p>

答:
Just wrap your text in a container which acts as the background and give it dimensions and color.

```<code>Container(
  padding: const EdgeInsets.all(8.0),
  color: Colors.yellow,
  child: Text("New Years),
)
</code>```

Edit: As you mentioned that you need this text style in a FlexibleSpaceBar.

Assuming you want to decorate the title text in FlexibleSpaceBar, note that it is not necessary to pass a Text widget to title field, you can pass any widget to it.

Pass a Container whose child is a Text widget and style the container. Refer the code below:

```<code>import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(home: MyApp()));

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        physics: const BouncingScrollPhysics(),
        slivers: <Widget>[
          SliverAppBar(
            stretch: true,
            onStretchTrigger: () {
              // Function callback for stretch
              return;
            },
            expandedHeight: 300.0,
            flexibleSpace: FlexibleSpaceBar(
              stretchModes: <StretchMode>[
                StretchMode.zoomBackground,
                StretchMode.blurBackground,
                StretchMode.fadeTitle,
              ],
              centerTitle: true,
              title: Container(  //HERE...
                color: Colors.yellow,
                padding: const EdgeInsets.all(8),
                child: Text(
                  'NEW YEARS',
                  style: TextStyle(
                    color: Colors.black,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
              background: Stack(
                fit: StackFit.expand,
                children: [
                  Image.network(
                    'https://flutter.github.io/assets-for-api-docs/assets/widgets/owl-2.jpg',
                    fit: BoxFit.cover,
                  ),
                  const DecoratedBox(
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment(0.0, 0.5),
                        end: Alignment(0.0, 0.0),
                        colors: <Color>[
                          Color(0x60000000),
                          Color(0x00000000),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
          SliverList(
            delegate: SliverChildListDelegate([
              ListTile(
                leading: Icon(Icons.wb_sunny),
                title: Text('Sunday'),
                subtitle: Text('sunny, h: 80, l: 65'),
              ),
              ListTile(
                leading: Icon(Icons.wb_sunny),
                title: Text('Monday'),
                subtitle: Text('sunny, h: 80, l: 65'),
              ),
              // ListTiles++
            ]),
          ),
        ],
      ),
    );
  }
}
</code>```

Body:
Just wrap your text in a container which acts as the background and give it dimensions and color.

Container(
  padding: const EdgeInsets.all(8.0),
  color: Colors.yellow,
  child: Text("New Years),
)

Edit: As you mentioned that you need this text style in a FlexibleSpaceBar.

Assuming you want to decorate the title text in FlexibleSpaceBar, note that it is not necessary to pass a Text widget to title field, you can pass any widget to it.

Pass a Container whose child is a Text widget and style the container. Refer the code below:

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(home: MyApp()));

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        physics: const BouncingScrollPhysics(),
        slivers: <Widget>[
          SliverAppBar(
            stretch: true,
            onStretchTrigger: () {
              // Function callback for stretch
              return;
            },
            expandedHeight: 300.0,
            flexibleSpace: FlexibleSpaceBar(
              stretchModes: <StretchMode>[
                StretchMode.zoomBackground,
                StretchMode.blurBackground,
                StretchMode.fadeTitle,
              ],
              centerTitle: true,
              title: Container(  //HERE...
                color: Colors.yellow,
                padding: const EdgeInsets.all(8),
                child: Text(
                  'NEW YEARS',
                  style: TextStyle(
                    color: Colors.black,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
              background: Stack(
                fit: StackFit.expand,
                children: [
                  Image.network(
                    'https://flutter.github.io/assets-for-api-docs/assets/widgets/owl-2.jpg',
                    fit: BoxFit.cover,
                  ),
                  const DecoratedBox(
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment(0.0, 0.5),
                        end: Alignment(0.0, 0.0),
                        colors: <Color>[
                          Color(0x60000000),
                          Color(0x00000000),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
          SliverList(
            delegate: SliverChildListDelegate([
              ListTile(
                leading: Icon(Icons.wb_sunny),
                title: Text('Sunday'),
                subtitle: Text('sunny, h: 80, l: 65'),
              ),
              ListTile(
                leading: Icon(Icons.wb_sunny),
                title: Text('Monday'),
                subtitle: Text('sunny, h: 80, l: 65'),
              ),
              // ListTiles++
            ]),
          ),
        ],
      ),
    );
  }
}


问:
flutter - Rewarded Video Ads Error when Reload : "ad_not_loaded, show failed for rewarded video, no ad was loaded, null)"
i try to reload Rewarded Video Ads, when i call RewardedVideoAd.instance.load(adUnitId: "xxx", targetingInfo: xyz); i find below error :

W/MessageQueue(13672): Handler (android.os.Handler) {1a13e8a} sending message to a Handler on a dead thread
  W/MessageQueue(13672): java.lang.IllegalStateException: Handler (android.os.Handler) {1a13e8a} sending message to a Handler on a dead thread
  W/MessageQueue(13672):  at android.os.MessageQueue.enqueueMessage(MessageQueue.java:543)
  W/MessageQueue(13672):  at android.os.Handler.enqueueMessage(Handler.java:643)
  W/MessageQueue(13672):  at android.os.Handler.sendMessageAtTime(Handler.java:612)
  W/MessageQueue(13672):  at android.os.Handler.sendMessageDelayed(Handler.java:582)
  W/MessageQueue(13672):  at android.os.Handler.sendEmptyMessageDelayed(Handler.java:546)
  W/MessageQueue(13672):  at android.os.Handler.sendEmptyMessage(Handler.java:531)
  W/MessageQueue(13672):  at com.google.android.gms.ads.exoplayer1.h.c(:com.google.android.gms.policy_ads_fdr_dynamite@20300003@20300003.251657827.251657827:2)
  W/MessageQueue(13672):  at com.google.android.gms.ads.internal.video.exoplayer1.f.b(:com.google.android.gms.policy_ads_fdr_dynamite@20300003@20300003.251657827.251657827:1)
  W/MessageQueue(13672):  at com.google.android.gms.ads.internal.webview.t.E(:com.google.android.gms.policy_ads_fdr_dynamite@20300003@20300003.251657827.251657827:5)
  W/MessageQueue(13672):  at com.google.android.gms.ads.internal.webview.j.onPageFinished(:com.google.android.gms.policy_ads_fdr_dynamite@20300003@20300003.251657827.251657827:2)
  W/MessageQueue(13672):  at uU.d(PG:307)
  W/MessageQueue(13672):  at aIV.handleMessage(PG:73)
  W/MessageQueue(13672):  at android.os.Handler.dispatchMessage(Handler.java:102)
  W/MessageQueue(13672):  at android.os.Looper.loop(Looper.java:154)
  W/MessageQueue(13672):  at android.app.ActivityThread.main(ActivityThread.java:6780)
  W/MessageQueue(13672):  at java.lang.reflect.Method.invoke(Native Method)
  W/MessageQueue(13672):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
  W/MessageQueue(13672):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)
  W/ExoPlayerImplInternal(13672): Sent message(1) after release. Message ignored.
  D/Graph   (13672): removeVertex() : insertDummyVertex, because there is no ancestor.
  D/ViewRootImpl@b8db50eAdActivity: mHardwareRenderer.destroy()#4
  D/ViewRootImpl@b8db50eAdActivity: dispatchDetachedFromWindow

i place the listener in initState() of my screen. in this screen i have a button where if we tap it, it should show Rewarded Video Ads.

Moreover, after getting error when Rewarded Ads reloaded, i got below error after tap the button to show ads (because ads instance was null):

E/flutter (13672): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: PlatformException(ad_not_loaded, show failed for rewarded video, no ad was loaded, null)
  E/flutter (13672): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:564:7)
  E/flutter (13672): #1      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:316:33)
  E/flutter (13672):
  E/flutter (13672): #2      _invokeBooleanMethod (package:firebase_admob/firebase_admob.dart:518:61)
  E/flutter (13672):
  E/flutter (13672): #3      RewardedVideoAd.show (package:firebase_admob/firebase_admob.dart:392:12)

I place Rewarded Video Ads Listener at initState(), below are the codes:

```<code>@override
  void initState() {
    super.initState();
...
    RewardedVideoAd.instance.listener =
        (RewardedVideoAdEvent event, {String rewardType, int rewardAmount}) {
      if (event == RewardedVideoAdEvent.completed) {
        setState(() {
          print ("::debug:: ads should be reloaded");
          RewardedVideoAd.instance.load(adUnitId: "ca-app-pub-3940256099942544/5224354917", targetingInfo: targetingInfos);
        });
      }
    };
...
</code>```

However, if i put code at button's onPressed like below, the video ads will show after tap for 2-3 times (where at debug is show ads  = null)

```<code>RaisedButton(
  onPressed: () {
    RewardedVideoAd.instance.show().whenComplete(() {
              RewardedVideoAd.instance.load(adUnitId: "ca-app-pub-3940256099942544/5224354917", targetingInfo: targetingInfos);
    })
},
...
</code>```

Any Idea ?

Thanks in Advance...

答:
No need for calling set state as it is expensive and causes a full rebuild.

This problem can easily be fixed in the following way:

```<code>import 'package:flutter/material.dart';
import 'package:firebase_admob/firebase_admob.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: HomePage());
  }
}

class HomePage extends StatefulWidget {
  HomePage({Key key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  //The targeting info required for Rewarded Videos Ads
  MobileAdTargetingInfo targetingInfo = MobileAdTargetingInfo(
    keywords: <String>['flutterio', 'beautiful apps'],
    contentUrl: 'https://flutter.io',
    childDirected: false,
    testDevices: <String>[], // Android emulators are considered test devices
  );

  //An instance to be called in the init state
  RewardedVideoAd _videoAd = RewardedVideoAd.instance;

  @override
  void initState() {
    //---------------------------------------//
    //Initialise the listener with the values.
    _videoAd.listener =
        (RewardedVideoAdEvent event, {String rewardType, int rewardAmount}) {
      if (event == RewardedVideoAdEvent.completed) {
        //When the video ad gets completed load a new video ad
        _videoAd
            .load(
                adUnitId: RewardedVideoAd.testAdUnitId,
                targetingInfo: targetingInfo)
            .catchError((e) => print('Error in loading.'));
      }

      //On every other event change pass the values to the _handleEvent Method.
      _handleEvent(event, rewardType, 'Reward', rewardAmount);
    };
    //------------------------------------------------------------------//

    //This will load the video when the widget is built for the first time.
    _videoAd
        .load(
            adUnitId: RewardedVideoAd.testAdUnitId,
            targetingInfo: targetingInfo)
        .catchError((e) => print('Error in loading.'));

    //-----------------------------------------------------//
    super.initState();
  }

  //---- Useful function to know exactly what is being done ----//
  void _handleEvent(RewardedVideoAdEvent event, String rewardType,
      String adType, int rewardAmount) {
    switch (event) {
      case RewardedVideoAdEvent.loaded:
        _showSnackBar('New Admob $adType Ad loaded!', 1500);
        break;
      case RewardedVideoAdEvent.opened:
        _showSnackBar('Admob $adType Ad opened!', 1500);
        break;
      //
      //The way we are fixing the issue is here.
      //This is by calling the video to be loaded when the other rewarded video is closed.
      case RewardedVideoAdEvent.closed:
        _showSnackBar('Admob $adType Ad closed!', 1500);
        _videoAd
            .load(
                adUnitId: RewardedVideoAd.testAdUnitId,
                targetingInfo: targetingInfo)
            .catchError((e) => print('Error in loading.'));
        break;
      case RewardedVideoAdEvent.failedToLoad:
        _showSnackBar('Admob $adType failed to load.', 1500);
        break;
      case RewardedVideoAdEvent.rewarded:
        _showSnackBar('Rewarded $rewardAmount', 3000);
        break;
      default:
    }
  }

  //Snackbar shown with ad status
  void _showSnackBar(String content, int duration) {
    Scaffold.of(context).showSnackBar(SnackBar(
      content: Text(content),
      duration: Duration(milliseconds: duration),
    ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: FlatButton(
          child: Text('Play AD'),
          onPressed: () {
            _videoAd.show().catchError(
                (e) => print("error in showing ad: ${e.toString()}"));
          },
        ),
      ),
    );
  }
}

</code>```

Body:
i try to reload Rewarded Video Ads, when i call RewardedVideoAd.instance.load(adUnitId: "xxx", targetingInfo: xyz); i find below error :

W/MessageQueue(13672): Handler (android.os.Handler) {1a13e8a} sending message to a Handler on a dead thread
  W/MessageQueue(13672): java.lang.IllegalStateException: Handler (android.os.Handler) {1a13e8a} sending message to a Handler on a dead thread
  W/MessageQueue(13672):  at android.os.MessageQueue.enqueueMessage(MessageQueue.java:543)
  W/MessageQueue(13672):  at android.os.Handler.enqueueMessage(Handler.java:643)
  W/MessageQueue(13672):  at android.os.Handler.sendMessageAtTime(Handler.java:612)
  W/MessageQueue(13672):  at android.os.Handler.sendMessageDelayed(Handler.java:582)
  W/MessageQueue(13672):  at android.os.Handler.sendEmptyMessageDelayed(Handler.java:546)
  W/MessageQueue(13672):  at android.os.Handler.sendEmptyMessage(Handler.java:531)
  W/MessageQueue(13672):  at com.google.android.gms.ads.exoplayer1.h.c(:com.google.android.gms.policy_ads_fdr_dynamite@20300003@20300003.251657827.251657827:2)
  W/MessageQueue(13672):  at com.google.android.gms.ads.internal.video.exoplayer1.f.b(:com.google.android.gms.policy_ads_fdr_dynamite@20300003@20300003.251657827.251657827:1)
  W/MessageQueue(13672):  at com.google.android.gms.ads.internal.webview.t.E(:com.google.android.gms.policy_ads_fdr_dynamite@20300003@20300003.251657827.251657827:5)
  W/MessageQueue(13672):  at com.google.android.gms.ads.internal.webview.j.onPageFinished(:com.google.android.gms.policy_ads_fdr_dynamite@20300003@20300003.251657827.251657827:2)
  W/MessageQueue(13672):  at uU.d(PG:307)
  W/MessageQueue(13672):  at aIV.handleMessage(PG:73)
  W/MessageQueue(13672):  at android.os.Handler.dispatchMessage(Handler.java:102)
  W/MessageQueue(13672):  at android.os.Looper.loop(Looper.java:154)
  W/MessageQueue(13672):  at android.app.ActivityThread.main(ActivityThread.java:6780)
  W/MessageQueue(13672):  at java.lang.reflect.Method.invoke(Native Method)
  W/MessageQueue(13672):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
  W/MessageQueue(13672):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)
  W/ExoPlayerImplInternal(13672): Sent message(1) after release. Message ignored.
  D/Graph   (13672): removeVertex() : insertDummyVertex, because there is no ancestor.
  D/ViewRootImpl@b8db50eAdActivity: mHardwareRenderer.destroy()#4
  D/ViewRootImpl@b8db50eAdActivity: dispatchDetachedFromWindow

i place the listener in initState() of my screen. in this screen i have a button where if we tap it, it should show Rewarded Video Ads.

Moreover, after getting error when Rewarded Ads reloaded, i got below error after tap the button to show ads (because ads instance was null):

E/flutter (13672): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: PlatformException(ad_not_loaded, show failed for rewarded video, no ad was loaded, null)
  E/flutter (13672): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:564:7)
  E/flutter (13672): #1      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:316:33)
  E/flutter (13672):
  E/flutter (13672): #2      _invokeBooleanMethod (package:firebase_admob/firebase_admob.dart:518:61)
  E/flutter (13672):
  E/flutter (13672): #3      RewardedVideoAd.show (package:firebase_admob/firebase_admob.dart:392:12)

I place Rewarded Video Ads Listener at initState(), below are the codes:

@override
  void initState() {
    super.initState();
...
    RewardedVideoAd.instance.listener =
        (RewardedVideoAdEvent event, {String rewardType, int rewardAmount}) {
      if (event == RewardedVideoAdEvent.completed) {
        setState(() {
          print ("::debug:: ads should be reloaded");
          RewardedVideoAd.instance.load(adUnitId: "ca-app-pub-3940256099942544/5224354917", targetingInfo: targetingInfos);
        });
      }
    };
...

However, if i put code at button's onPressed like below, the video ads will show after tap for 2-3 times (where at debug is show ads  = null)

RaisedButton(
  onPressed: () {
    RewardedVideoAd.instance.show().whenComplete(() {
              RewardedVideoAd.instance.load(adUnitId: "ca-app-pub-3940256099942544/5224354917", targetingInfo: targetingInfos);
    })
},
...

Any Idea ?

Thanks in Advance...

Body:
No need for calling set state as it is expensive and causes a full rebuild.

This problem can easily be fixed in the following way:

import 'package:flutter/material.dart';
import 'package:firebase_admob/firebase_admob.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: HomePage());
  }
}

class HomePage extends StatefulWidget {
  HomePage({Key key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  //The targeting info required for Rewarded Videos Ads
  MobileAdTargetingInfo targetingInfo = MobileAdTargetingInfo(
    keywords: <String>['flutterio', 'beautiful apps'],
    contentUrl: 'https://flutter.io',
    childDirected: false,
    testDevices: <String>[], // Android emulators are considered test devices
  );

  //An instance to be called in the init state
  RewardedVideoAd _videoAd = RewardedVideoAd.instance;

  @override
  void initState() {
    //---------------------------------------//
    //Initialise the listener with the values.
    _videoAd.listener =
        (RewardedVideoAdEvent event, {String rewardType, int rewardAmount}) {
      if (event == RewardedVideoAdEvent.completed) {
        //When the video ad gets completed load a new video ad
        _videoAd
            .load(
                adUnitId: RewardedVideoAd.testAdUnitId,
                targetingInfo: targetingInfo)
            .catchError((e) => print('Error in loading.'));
      }

      //On every other event change pass the values to the _handleEvent Method.
      _handleEvent(event, rewardType, 'Reward', rewardAmount);
    };
    //------------------------------------------------------------------//

    //This will load the video when the widget is built for the first time.
    _videoAd
        .load(
            adUnitId: RewardedVideoAd.testAdUnitId,
            targetingInfo: targetingInfo)
        .catchError((e) => print('Error in loading.'));

    //-----------------------------------------------------//
    super.initState();
  }

  //---- Useful function to know exactly what is being done ----//
  void _handleEvent(RewardedVideoAdEvent event, String rewardType,
      String adType, int rewardAmount) {
    switch (event) {
      case RewardedVideoAdEvent.loaded:
        _showSnackBar('New Admob $adType Ad loaded!', 1500);
        break;
      case RewardedVideoAdEvent.opened:
        _showSnackBar('Admob $adType Ad opened!', 1500);
        break;
      //
      //The way we are fixing the issue is here.
      //This is by calling the video to be loaded when the other rewarded video is closed.
      case RewardedVideoAdEvent.closed:
        _showSnackBar('Admob $adType Ad closed!', 1500);
        _videoAd
            .load(
                adUnitId: RewardedVideoAd.testAdUnitId,
                targetingInfo: targetingInfo)
            .catchError((e) => print('Error in loading.'));
        break;
      case RewardedVideoAdEvent.failedToLoad:
        _showSnackBar('Admob $adType failed to load.', 1500);
        break;
      case RewardedVideoAdEvent.rewarded:
        _showSnackBar('Rewarded $rewardAmount', 3000);
        break;
      default:
    }
  }

  //Snackbar shown with ad status
  void _showSnackBar(String content, int duration) {
    Scaffold.of(context).showSnackBar(SnackBar(
      content: Text(content),
      duration: Duration(milliseconds: duration),
    ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: FlatButton(
          child: Text('Play AD'),
          onPressed: () {
            _videoAd.show().catchError(
                (e) => print("error in showing ad: ${e.toString()}"));
          },
        ),
      ),
    );
  }
}


问:
Get cell value from kendo grid using jquery
How to get the kendo grid cell value using jquery function?Am new to kendo grid

```<code>{field:abc,title:values}
</code>```

I need the abc value in javascript or jquery?

答:
If anyone still looking for an answer then you can try using following steps:

Note: Basically KendoGrid all rows have it's unique uid property assigned for identify each row. So if you are having uid then you can follow these steps:

```<code>var grid = $("#grid").data("kendoGrid");

var tr = grid.dataSource.getByUid("your-row-uid");

var yourFieldValue = tr.yourFieldName;
</code>```

Even you can get value throught following steps:

First :

```<code>var grid = $("#grid").data("kendoGrid");
</code>```

Second :

```<code>var dataItem = grid.dataItem(grid.select());
</code>```

or

```<code>var dataItem = grid.dataItem($(event.target).closest("tr"));
</code>```

or

```<code>var dataItem = grid.dataItem("tr.k-grid-edit-row");
</code>```

Third:

```<code>var yourFieldValue = dataItem.yourFieldName;
</code>```

Body:
How to get the kendo grid cell value using jquery function?Am new to kendo grid

{field:abc,title:values}

I need the abc value in javascript or jquery?

Body:
If anyone still looking for an answer then you can try using following steps:

Note: Basically KendoGrid all rows have it's unique uid property assigned for identify each row. So if you are having uid then you can follow these steps:

var grid = $("#grid").data("kendoGrid");

var tr = grid.dataSource.getByUid("your-row-uid");

var yourFieldValue = tr.yourFieldName;

Even you can get value throught following steps:

First :

var grid = $("#grid").data("kendoGrid");

Second :

var dataItem = grid.dataItem(grid.select());

or

var dataItem = grid.dataItem($(event.target).closest("tr"));

or

var dataItem = grid.dataItem("tr.k-grid-edit-row");

Third:

var yourFieldValue = dataItem.yourFieldName;


问:
Javascript: Clean way to check an ovject value (And return false if the value doesn't exist)
So I've got an object containing multiple objects, like this:

```<code>let data = {
    hello: {
        melon: {
           yes: true
        }
    }
}
</code>```

Here I want to check if "yes" is equal to true. The problem being that the "data" object could contain nothing, and the "hello" object could contain nothing, and it goes on. Here's what I did:

```<code>if(data.hello && && data.hello.melon && data.hello.melon.yes && data.hello.melon.yes === true){...}
</code>```

Is there a way to make this condition cleaner?

答:
in ES2020 there is cool feature called optional chaining, so you can use it:

```<code>let foo = data?.hello?.melon?.yes
</code>```

Also you can combine it with feature called nulish coalescing to set default value:

```<code>let foo = data?.hello?.melon?.yes ?? 'default value'
</code>```

So the condition will look like:

if (data?.hello?.melon?.yes === true)

Body:
So I've got an object containing multiple objects, like this:

let data = {
    hello: {
        melon: {
           yes: true
        }
    }
}

Here I want to check if "yes" is equal to true. The problem being that the "data" object could contain nothing, and the "hello" object could contain nothing, and it goes on. Here's what I did:

if(data.hello && && data.hello.melon && data.hello.melon.yes && data.hello.melon.yes === true){...}

Is there a way to make this condition cleaner?

Body:
in ES2020 there is cool feature called optional chaining, so you can use it:

let foo = data?.hello?.melon?.yes

Also you can combine it with feature called nulish coalescing to set default value:

let foo = data?.hello?.melon?.yes ?? 'default value'

So the condition will look like:

if (data?.hello?.melon?.yes === true)


问:
Javascript. How can I access a variable outside of a function?
I'm trying to create a simple application that generates a random question with an onclick, and will generate a solution to said question with a different onclick.  I've been able to create the random question function simple enough, but what I'm having trouble with is the solution part.  Essentially I cant access the variables produced from the "generate question" function.

The following function generates a random question: "Convert 10mg/mL to mcg/mL"

```<code>const arr = ['mg/mL', 'mcg/mL', 'mg/L'];

function genConversion () {
  function clearBox(elementID){ //this resets the question
      document.getElementById(elementID).innerHTML = "";
  }

  clearBox('output');

  function shuffle(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
  }

   function randomNum() {
    var number = Math.floor((Math.random() * 100) +1);
    return number
  }

  var num = randomNum()

  shuffle(arr);

  output.innerHTML += "Convert " + num + ' ' + arr[0] + ' to ' + arr[1]

}
</code>```

Now, when I try to create a function that will solve the generated problem (the actual logic will come once I can figure out how to access the question variables), I cant seem to access variable 'num'.  Interestingly, I am able to access the random array element arr[0].

```<code>function solveProb() {
  console.log(arr[0]);
  console.log(num);
}
</code>```

Im sure this has something to do with scope that Im having trouble with, but any advice would be appreciated.

答:
Just define your variable above the function as a "let" and then in the function modify the variable. Then call the function. Then you can access the updated value of the variable OUTSIDE the function.</p>

```<code>let a = null;
const func = () => a = 5;
func();
console.log(a); // 5
</code>```

Body:
I'm trying to create a simple application that generates a random question with an onclick, and will generate a solution to said question with a different onclick.  I've been able to create the random question function simple enough, but what I'm having trouble with is the solution part.  Essentially I cant access the variables produced from the "generate question" function.

The following function generates a random question: "Convert 10mg/mL to mcg/mL"

const arr = ['mg/mL', 'mcg/mL', 'mg/L'];

function genConversion () {
  function clearBox(elementID){ //this resets the question
      document.getElementById(elementID).innerHTML = "";
  }

  clearBox('output');

  function shuffle(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
  }

   function randomNum() {
    var number = Math.floor((Math.random() * 100) +1);
    return number
  }

  var num = randomNum()

  shuffle(arr);

  output.innerHTML += "Convert " + num + ' ' + arr[0] + ' to ' + arr[1]

}

Now, when I try to create a function that will solve the generated problem (the actual logic will come once I can figure out how to access the question variables), I cant seem to access variable 'num'.  Interestingly, I am able to access the random array element arr[0].

function solveProb() {
  console.log(arr[0]);
  console.log(num);
}

Im sure this has something to do with scope that Im having trouble with, but any advice would be appreciated.

Body:
Just define your variable above the function as a "let" and then in the function modify the variable. Then call the function. Then you can access the updated value of the variable OUTSIDE the function.

let a = null;
const func = () => a = 5;
func();
console.log(a); // 5


问:
WCF error: No end point listening
HI,

I know this is a very common question in case of .Net, but a weird thing is happening. My friend has a wcf service hosted in IIS. I am able to connect to his service by

http://172.16.70.129/newwebsite/eval.svc

Also, when I use wcftestclient to access the service, it is able to get the metadata and download the operations that the service exposes. But, when I try to invoke the operations, I get an error that

"There was no endpoint listening at http://localhost/newwebsite/eval.svc/basic that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details."

He is able to access it in his computer from the wcftestclient, but I am unable to do so. We both are within same wifi connection. And both our firewalls are turned off. Does anybody have a solution to this?

答: If I understand correctly, the WCF service is running on your friend's machine.  The localhost in the endpoint is trying to reference the service as if it's on your own machine.  To fix this, replace localhost with 172.16.70.129 in the endpoint.

Title: WCF error: No end point listening


问:
Error: A cross-origin error was thrown. Error: a secret should be set
I'm following a course to make an e-commerce website and when I try to sign a user up, I receive this error:

The instructor cloned my repo and received no errors however I am receiving an error whenever I try to sign up or sign in.

How can I solve this? Any help would be really appreciated.
Perhaps there's an issue with the errorHandler file that I'm using to handle the error.

controllers/auth.js

```<code>const User = require('../models/user')
const jwt = require('jsonwebtoken') // to generate signed token
const expressJwt = require('express-jwt') // for authorization check
const { errorHandler } = require('../helpers/dbErrorHandler')

exports.signup = (req, res) => {
    console.log("req.body", req.body)
    // signs up new user
 const user = new User(req.body)
 user.save((err, user) => {
if(err) {
    return res.status(400).json({
        err: errorHandler(err)
    })
}
user.salt = undefined
user.hashed_password = undefined

res.json({
    user
 })
 })
}

exports.signin = (req, res) => {
// find user based on email
const { email, password } = req.body
User.findOne({email}, (err, user) => {
if (err || !user) {
    return res.status(400).json({
        error: 'User with that email does not exist.'
    })
}
// if user is found, ensure email & password match
// create authenticate method in user model
if (!user.authenticate(password)) {
    return res.status(401).json({
error: 'Email and password dont match'
    })
}
// generate signed token with user id and secret
const token = jwt.sign({_id: user._id}, process.env.JWT_SECRET)

// persist token as 't' in cookie with expiry date
res.cookie('t', token, {expire: new Date() + 9999 })

// return response with user & token to frontend client
const {_id, name, email, role} = user
return res.json({token, user: {_id, email, name, role}})
})
}

exports.signout = (req, res) => {
    res.clearCookie('t')
    res.json({ message: "Signout success" })
}

exports.requireSignin = expressJwt({
secret: process.env.JWT_SECRET,
userProperty: 'auth'
})

exports.isAuth = (req, res, next) => {
    let user = req.profile && req.auth && req.profile._id == req.auth._id
if(!user) {
    return res.status(403).json({
        error: "Access denied"
    })
}
    next()
}

exports.isAdmin = (req, res, next) => {
    if (req.profile.role === 0) {
        return res.status(403).json({
        error: 'Admin resource! Access denied'
        })
    }
    next()
}

</code>```

The error message in the console:

```<code>  throw new MongooseError('The `uri` parameter to `openUri()` must be a ' +
    ^
Error [MongooseError]: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.
</code>```

答:
You have uncaught exceptions in Components Signup  and Signin.

```<code>// Signin.js
const clickSubmit = (event) => {
    event.preventDefault()
    setValues({ ...values, error: false, loading: true })
    signin({ email, password }).then(data => {
        if (data.error) {
            setValues({ ...values, error: data.error, loading: false })
        } else {
            authenticate(data, () => {
                setValues({
                    ...values,
                    redirectToReferrer: true
                })
            })
        }
    }).catch(exc => {
        console.error("+++ exc signin: ", exc)
        // we log error
        setValues({ ...values, error: exc.message, loading: false })
    });
}

// Signup.js
const clickSubmit = event => {
    event.preventDefault();
    setValues({ ...values, error: false });
    signup({ name, email, password }).then(data => {
        console.log("++ data: ", data);

        // if you need to check error from backend
        // else all exceptions are captured in catch block
        if (data.error) {
            setValues({ ...values, error: data.error, success: false });
        } else {
            setValues({
                ...values,
                name: '',
                email: '',
                password: '',
                error: '',
                success: true
            });
        }
    }).catch(exc => {
        console.error('++ exc: ', exc);

        setValues({ ...values, error: exc.message, success: false });
    })
};
</code>```

Then in auth/index.js, only return fetch promise and let calling function handle exception.

```<code> // cors mode to allow cross-origin
 export const signup = (user) => {
    return fetch(`${API}/signup`, {
        method: "POST",
        mode: 'cors',
        headers: {
            Accept: 'application/json',
            "Content-Type": "application/json"
        },
        body: JSON.stringify(user)
    })
        .then(response => {
            return response.json()
        })

};

// mode cors to allow cross-origin access
export const signin = (user) => {
    return fetch(`${API}/signin`, {
        method: "POST",
        mode: 'cors',
        headers: {
            Accept: 'application/json',
            "Content-Type": "application/json"
        },
        body: JSON.stringify(user)
    })
        .then(response => {
            return response.json()
        })

}
</code>```

On backend end, make sure these keys are set process.env.JWT_SECRET or you can either use a default value in case key is not set or exit app on startup if important keys are not set.

process.env.JWT_SECRET || 'default_ket'

You need to create .env file at root of ecommerce-back and in it

```<code>DATABASE=mongodb://localhost:27017/Ecommerce
JWT_SECRET=secret
</code>```

Here, it is Mongo is running on default port and your database name is Ecommerce, otherwise set values according to your setup.

Body:
I'm following a course to make an e-commerce website and when I try to sign a user up, I receive this error:

The instructor cloned my repo and received no errors however I am receiving an error whenever I try to sign up or sign in.

How can I solve this? Any help would be really appreciated.
Perhaps there's an issue with the errorHandler file that I'm using to handle the error.

controllers/auth.js

const User = require('../models/user')
const jwt = require('jsonwebtoken') // to generate signed token
const expressJwt = require('express-jwt') // for authorization check
const { errorHandler } = require('../helpers/dbErrorHandler')

exports.signup = (req, res) => {
    console.log("req.body", req.body)
    // signs up new user
 const user = new User(req.body)
 user.save((err, user) => {
if(err) {
    return res.status(400).json({
        err: errorHandler(err)
    })
}
user.salt = undefined
user.hashed_password = undefined

res.json({
    user
 })
 })
}

exports.signin = (req, res) => {
// find user based on email
const { email, password } = req.body
User.findOne({email}, (err, user) => {
if (err || !user) {
    return res.status(400).json({
        error: 'User with that email does not exist.'
    })
}
// if user is found, ensure email & password match
// create authenticate method in user model
if (!user.authenticate(password)) {
    return res.status(401).json({
error: 'Email and password dont match'
    })
}
// generate signed token with user id and secret
const token = jwt.sign({_id: user._id}, process.env.JWT_SECRET)

// persist token as 't' in cookie with expiry date
res.cookie('t', token, {expire: new Date() + 9999 })

// return response with user & token to frontend client
const {_id, name, email, role} = user
return res.json({token, user: {_id, email, name, role}})
})
}

exports.signout = (req, res) => {
    res.clearCookie('t')
    res.json({ message: "Signout success" })
}

exports.requireSignin = expressJwt({
secret: process.env.JWT_SECRET,
userProperty: 'auth'
})

exports.isAuth = (req, res, next) => {
    let user = req.profile && req.auth && req.profile._id == req.auth._id
if(!user) {
    return res.status(403).json({
        error: "Access denied"
    })
}
    next()
}

exports.isAdmin = (req, res, next) => {
    if (req.profile.role === 0) {
        return res.status(403).json({
        error: 'Admin resource! Access denied'
        })
    }
    next()
}

The error message in the console:

  throw new MongooseError('The `uri` parameter to `openUri()` must be a ' +
    ^
Error [MongooseError]: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.

Body:
You have uncaught exceptions in Components Signup  and Signin.

// Signin.js
const clickSubmit = (event) => {
    event.preventDefault()
    setValues({ ...values, error: false, loading: true })
    signin({ email, password }).then(data => {
        if (data.error) {
            setValues({ ...values, error: data.error, loading: false })
        } else {
            authenticate(data, () => {
                setValues({
                    ...values,
                    redirectToReferrer: true
                })
            })
        }
    }).catch(exc => {
        console.error("+++ exc signin: ", exc)
        // we log error
        setValues({ ...values, error: exc.message, loading: false })
    });
}

// Signup.js
const clickSubmit = event => {
    event.preventDefault();
    setValues({ ...values, error: false });
    signup({ name, email, password }).then(data => {
        console.log("++ data: ", data);

        // if you need to check error from backend
        // else all exceptions are captured in catch block
        if (data.error) {
            setValues({ ...values, error: data.error, success: false });
        } else {
            setValues({
                ...values,
                name: '',
                email: '',
                password: '',
                error: '',
                success: true
            });
        }
    }).catch(exc => {
        console.error('++ exc: ', exc);

        setValues({ ...values, error: exc.message, success: false });
    })
};

Then in auth/index.js, only return fetch promise and let calling function handle exception.

 // cors mode to allow cross-origin
 export const signup = (user) => {
    return fetch(`${API}/signup`, {
        method: "POST",
        mode: 'cors',
        headers: {
            Accept: 'application/json',
            "Content-Type": "application/json"
        },
        body: JSON.stringify(user)
    })
        .then(response => {
            return response.json()
        })

};

// mode cors to allow cross-origin access
export const signin = (user) => {
    return fetch(`${API}/signin`, {
        method: "POST",
        mode: 'cors',
        headers: {
            Accept: 'application/json',
            "Content-Type": "application/json"
        },
        body: JSON.stringify(user)
    })
        .then(response => {
            return response.json()
        })

}

On backend end, make sure these keys are set process.env.JWT_SECRET or you can either use a default value in case key is not set or exit app on startup if important keys are not set.

process.env.JWT_SECRET || 'default_ket'

You need to create .env file at root of ecommerce-back and in it

DATABASE=mongodb://localhost:27017/Ecommerce
JWT_SECRET=secret

Here, it is Mongo is running on default port and your database name is Ecommerce, otherwise set values according to your setup.


问:
How to exclude words from match in regex?
I am trying to exclude certain URLs from a match, containing /com/de/cms/ e.g.:

match this:

www.example.com/catname/all-from-category/?pageNumber=1

but not this:

example.com/com/de/cms/catname/all-from-category/?pageNumber=3

Regex:

```<code>^[^com\/de\/cms\/]+\/all-from-category\/\?pageNumber=\d(&hitsPerPage=\d)?
</code>```

https://regex101.com/r/Mqpspq/1

How can I exclude URLs with com/de/cms/ while matching the other URL?

答:
There are couple of mistakes in your regex.

The first ^ matches the start of the starting, or the start of a line if multiline mode is enabled.

The [^com\/de\/cms] part means to match any character except c, or o, or m or /, or, etc. But your intent was to match any substring except com/de/cms as a whole. What you want can be done using negative lookbehind, like this: (?<!com\/de\/cms\/)

You're missing the catname part.

A working regex would be:

(?<!com\/de\/cms)\/catname\/all-from-category\/\?pageNumber=\d

The previous regex is simply says the following:

Please, match /catname/all-from-category/?pageNumber=SOME_DIGIT that is not preceded by com/de/cms.

Regexr.

Body:
I am trying to exclude certain URLs from a match, containing /com/de/cms/ e.g.:

match this:

www.example.com/catname/all-from-category/?pageNumber=1

but not this:

example.com/com/de/cms/catname/all-from-category/?pageNumber=3

Regex:

^[^com\/de\/cms\/]+\/all-from-category\/\?pageNumber=\d(&hitsPerPage=\d)?

https://regex101.com/r/Mqpspq/1

How can I exclude URLs with com/de/cms/ while matching the other URL?


问:
how to do basic IO in file in c?
Don't know if it is duplicate, if so, mark it ( I havennot found answers anywhere).

Having this:

```<code>#include <stdio.h>
#include <stdlib.h>

int main (void) {

    FILE *fp = fopen("txt2", "r+"); // does not help a+ or w+
    fprintf(fp,"20");
    fseek(fp,1,SEEK_CUR);
    fprintf(fp,"19");

    for(char c;(c=getc(fp))!=EOF;)
        putchar(c);

    fclose(fp);
    return 0;
}
</code>```

Cannot write to the file, and at the end view the file via putchar. how to open file to read as well as read? (I have tried r+,w+,a+, non helped). Still confused with their differencies(r+/w+ - both are positioned at the beginning of file, so in which differ? only a+ makes sense, as only it writes at the end (after everything else) in the file).

I don't know it the (r/w)+ mode makes some effect, since noone has yet explained the differences and usecases, but I have changed the mode from r+ to w+ and the offset of fseek:

```<code>FILE *fp = fopen("txt2", "w+");
...
fseek(fp,10,SEEK_CUR);
</code>```

but, the output is 2019 instead of 20        19. So does that mean fseek trims white spaces? or why is not the desire output?

and it

答:
You need to add a call to fflush() or fseek() ... between reading and writing.

See https://port70.net/~nsz/c/c11/n1570.html#7.21.5.3p7

When a file is opened with update mode ('+' as the second or third character in the above list of mode argument values), both input and output may be performed on the associated stream. However, output shall not be directly followed by input without an intervening call to the fflush function or to a file positioning function (fseek, fsetpos, or rewind), and input shall not be directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end- of-file. Opening (or creating) a text file with update mode may instead open (or create) a binary stream in some implementations.

```<code>    fprintf(fp,"19");              // write

    rewind(fp);                    // follow rhe rules

    for(int c;(c=getc(fp))!=EOF;)  // read, make sure c is int
</code>```

Title: how to do basic IO in file in c?

Body:
Don't know if it is duplicate, if so, mark it ( I havennot found answers anywhere).

Having this:

#include <stdio.h>
#include <stdlib.h>

int main (void) {

    FILE *fp = fopen("txt2", "r+"); // does not help a+ or w+
    fprintf(fp,"20");
    fseek(fp,1,SEEK_CUR);
    fprintf(fp,"19");

    for(char c;(c=getc(fp))!=EOF;)
        putchar(c);

    fclose(fp);
    return 0;
}

Cannot write to the file, and at the end view the file via putchar. how to open file to read as well as read? (I have tried r+,w+,a+, non helped). Still confused with their differencies(r+/w+ - both are positioned at the beginning of file, so in which differ? only a+ makes sense, as only it writes at the end (after everything else) in the file).

I don't know it the (r/w)+ mode makes some effect, since noone has yet explained the differences and usecases, but I have changed the mode from r+ to w+ and the offset of fseek:

FILE *fp = fopen("txt2", "w+");
...
fseek(fp,10,SEEK_CUR);

but, the output is 2019 instead of 20        19. So does that mean fseek trims white spaces? or why is not the desire output?

and it

Body:
You need to add a call to fflush() or fseek() ... between reading and writing.

See https://port70.net/~nsz/c/c11/n1570.html#7.21.5.3p7

When a file is opened with update mode ('+' as the second or third character in the above list of mode argument values), both input and output may be performed on the associated stream. However, output shall not be directly followed by input without an intervening call to the fflush function or to a file positioning function (fseek, fsetpos, or rewind), and input shall not be directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end- of-file. Opening (or creating) a text file with update mode may instead open (or create) a binary stream in some implementations.

    fprintf(fp,"19");              // write

    rewind(fp);                    // follow rhe rules

    for(int c;(c=getc(fp))!=EOF;)  // read, make sure c is int


问:
sequelize afterConnect hook with mssql (tedious)
While trying to inject prepared statements with MSSQL (tedious) - once I'm trying to execute the request I'm getting the following error:

Database connection failed: Requests can only be made in the LoggedIn state, not the SentClientRequest state

The imports:

import { Connection, Request } from 'tedious';
```

<p>The hook:</p>

<pre class="lang-js prettyprint-override"><code>public static async afterConnect(connection, options): Promise<void> {
    const client = connection['resource'] as Connection;

    let request = new Request('select 42',(err, rowCount, rows) => {
      console.log(`${err} ${rowCount} rows`);
    });

    client.execSql(request);
  }
</code>```

According to tedious I need to chain the request after the previous one, sequelize doesn't seem to pass that data, is there a way to work around this issue?

I've also created an issue on Sequelize GitHub

答:
took some digging inside sequelize code, but found a work around - if anyone has a similar issue.

public static async afterConnect(connection, options): Promise<void> {
    const mssql = connection as { resource: Connection; previous: Promise<unknown> };

    await new Promise((resolve) => {
      let request = new Request('select 42', (err, rowCount) => {
        logger.debug(method, `${err} - ${rowCount} rows`);

        resolve();
      });

      await mssql.previous; // failsafe?
      mssql.resource.execSql(request);
    });
}
```

Body:
While trying to inject prepared statements with MSSQL (tedious) - once I'm trying to execute the request I'm getting the following error:

Database connection failed: Requests can only be made in the LoggedIn state, not the SentClientRequest state

The imports:

import { Connection, Request } from 'tedious';

The hook:

public static async afterConnect(connection, options): Promise<void> {
    const client = connection['resource'] as Connection;

    let request = new Request('select 42',(err, rowCount, rows) => {
      console.log(`${err} ${rowCount} rows`);
    });

    client.execSql(request);
  }

According to tedious I need to chain the request after the previous one, sequelize doesn't seem to pass that data, is there a way to work around this issue?

I've also created an issue on Sequelize GitHub


问:
In c#, determine interfaces implemented by an object at runtime
I know there are ways to determine at runtime if an object implements a particular interface. What I'm wondering is if there's a way to determine at runtime all of the interfaces an object implements without looking for any one interface in particular.

I'd really rather not have to check for each interface one by one - even using asynchronous processing that seems clunky and inelegant to me.

I'm  currently looking into reflection, but if there is a less resource-intensive, in-language way to do it I'd prefer that.

Any ideas?

答:
Type.GetInterfaces will return you the types of the interfaces implemented by the type of an object. For example:</p>

```<code>var interfaces = someObject.GetType().GetInterfaces();
</code>```

Body:
Type.GetInterfaces will return you the types of the interfaces implemented by the type of an object. For example:

var interfaces = someObject.GetType().GetInterfaces();