问:
Snake game in python, how do I add a border inside the window to serve as the playing space for the user?
I am new to python and i am trying to make a snake game. How do I add a border or limit on my window (window size is 1280x720) to serve as the playing space for the user so it does not overlap on the score display on the top-left of the window?

I'll insert my code to show my progress. I would really appreciate any help! :)
`

```<code>import pygame
import time
import random
pygame.init()

#Importing Colors
white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)
orange = (218,103,60)
pink = (255, 105, 180)
lime = (232, 244, 140)
cream = (255,253,208)
medium_green = (60,179,113)

#Window Size
dis_width = 1280
dis_height = 720

#Initialize window
dis = pygame.display.set_mode((dis_width, dis_height))

#Title
pygame.display.set_caption('  ISNEKK  ')

#Clock Variable
clock = pygame.time.Clock()

#Snake Block Size
snake_block = 10

font_style = pygame.font.SysFont("timesnewroman", 40)
score_font = pygame.font.SysFont("arial", 25) #Score Display

def game_border(border):
    pygame.draw.line(surface, (255,255,255), (x,rows_space), (x,w))
    pygame.draw.line(surface, (255,255,255), (rows_space,y), (w,y))

def Your_score(score):
    value = score_font.render("SCORE: " + str(score), True, black)
    dis.blit(value, [0, 0])

def our_snake(snake_block, snake_list):
    for x in snake_list:
        pygame.draw.rect(dis, medium_green, [x[0], x[1], snake_block, snake_block])

def message(msg, color):
    mesg = font_style.render(msg, True, color)
    dis.blit(mesg, [dis_width / 8, dis_height / 3])

def gameLoop():
    game_over = False
    game_close = False

    x1 = dis_width/2
    y1 = dis_height/2

    x1_change = 0
    y1_change = 0

    snake_List = []
    Length_of_snake = 1

    foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
    foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0

    snake_speed = 10

    while not game_over:
        while game_close == True:
            dis.fill(black)
            message("GAME OVER! Press G to play again or Q to quit", white)
            Your_score(Length_of_snake - 1)
            pygame.display.update()

            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        game_over = True
                        game_close = False
                    if event.key == pygame.K_g:
                        gameLoop()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_over = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x1_change = -snake_block
                    y1_change = 0
                elif event.key == pygame.K_RIGHT:
                    x1_change = snake_block
                    y1_change = 0
                elif event.key == pygame.K_UP:
                    y1_change = -snake_block
                    x1_change = 0
                elif event.key == pygame.K_DOWN:
                    y1_change = snake_block
                    x1_change = 0

        if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:
            game_close = True
        x1 += x1_change
        y1 += y1_change
        dis.fill(cream)
        pygame.draw.rect(dis, red, [foodx, foody, snake_block, snake_block])
        snake_Head = []
        snake_Head.append(x1)
        snake_Head.append(y1)
        snake_List.append(snake_Head)
        if len(snake_List) > Length_of_snake:
            del snake_List[0]

        for x in snake_List[:-1]:
            if x == snake_Head:
                game_close = True

        our_snake(snake_block, snake_List)
        Your_score(Length_of_snake - 1)

        pygame.display.update()

        if x1 == foodx and y1 == foody:
            foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
            foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
            Length_of_snake += 1
            snake_speed = snake_speed + 0.5

        clock.tick(snake_speed)

    pygame.quit()
    quit()

gameLoop()

</code>```

Body:
I am new to python and i am trying to make a snake game. How do I add a border or limit on my window (window size is 1280x720) to serve as the playing space for the user so it does not overlap on the score display on the top-left of the window?

I'll insert my code to show my progress. I would really appreciate any help! :)
`

import pygame
import time
import random
pygame.init()

#Importing Colors
white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)
orange = (218,103,60)
pink = (255, 105, 180)
lime = (232, 244, 140)
cream = (255,253,208)
medium_green = (60,179,113)

#Window Size
dis_width = 1280
dis_height = 720

#Initialize window
dis = pygame.display.set_mode((dis_width, dis_height))

#Title
pygame.display.set_caption('  ISNEKK  ')

#Clock Variable
clock = pygame.time.Clock()

#Snake Block Size
snake_block = 10

font_style = pygame.font.SysFont("timesnewroman", 40)
score_font = pygame.font.SysFont("arial", 25) #Score Display

def game_border(border):
    pygame.draw.line(surface, (255,255,255), (x,rows_space), (x,w))
    pygame.draw.line(surface, (255,255,255), (rows_space,y), (w,y))

def Your_score(score):
    value = score_font.render("SCORE: " + str(score), True, black)
    dis.blit(value, [0, 0])

def our_snake(snake_block, snake_list):
    for x in snake_list:
        pygame.draw.rect(dis, medium_green, [x[0], x[1], snake_block, snake_block])

def message(msg, color):
    mesg = font_style.render(msg, True, color)
    dis.blit(mesg, [dis_width / 8, dis_height / 3])

def gameLoop():
    game_over = False
    game_close = False

    x1 = dis_width/2
    y1 = dis_height/2

    x1_change = 0
    y1_change = 0

    snake_List = []
    Length_of_snake = 1

    foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
    foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0

    snake_speed = 10

    while not game_over:
        while game_close == True:
            dis.fill(black)
            message("GAME OVER! Press G to play again or Q to quit", white)
            Your_score(Length_of_snake - 1)
            pygame.display.update()

            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        game_over = True
                        game_close = False
                    if event.key == pygame.K_g:
                        gameLoop()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_over = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x1_change = -snake_block
                    y1_change = 0
                elif event.key == pygame.K_RIGHT:
                    x1_change = snake_block
                    y1_change = 0
                elif event.key == pygame.K_UP:
                    y1_change = -snake_block
                    x1_change = 0
                elif event.key == pygame.K_DOWN:
                    y1_change = snake_block
                    x1_change = 0

        if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:
            game_close = True
        x1 += x1_change
        y1 += y1_change
        dis.fill(cream)
        pygame.draw.rect(dis, red, [foodx, foody, snake_block, snake_block])
        snake_Head = []
        snake_Head.append(x1)
        snake_Head.append(y1)
        snake_List.append(snake_Head)
        if len(snake_List) > Length_of_snake:
            del snake_List[0]

        for x in snake_List[:-1]:
            if x == snake_Head:
                game_close = True

        our_snake(snake_block, snake_List)
        Your_score(Length_of_snake - 1)

        pygame.display.update()

        if x1 == foodx and y1 == foody:
            foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
            foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
            Length_of_snake += 1
            snake_speed = snake_speed + 0.5

        clock.tick(snake_speed)

    pygame.quit()
    quit()

gameLoop()


来源: stackexchange

问:
Confusing Error:- Function components cannot have string refs. We recommend using useRef() instead
Creating a ref via useRef():

export default function LexicalEditor() {
  const floatingAnchorElem = useRef(null);

  return(
      <LexicalComposer initialConfig={editorConfig} >
        <Container fluid >
          <LexicalToolbarPlugin />
          <Row className="justify-content-xl-center" id="editor-body" >
            <Col xs={7}>

                <RichTextPlugin
                  contentEditable={
                    <ContentEditable className="editor-input" style={ { borderColor: 'green', borderStyle: 'solid', minWidth: '50%', width: 'auto', minHeight: 500, height: 'auto' }} />
                  }
                />

            </Col>
            <LocalStoragePlugin />
            {floatingAnchorElem.current && (
              <>
                <FloatingLinkEditorPlugin anchorElem={floatingAnchorElem.current} />
              </>
              )
            }
          </Row>
        </Container>
      </LexicalComposer>
  )
}
```
<p>and then inside <code>FloatingLinkEditorPlugin</code>, creating portal like so:</p>
<pre class="lang-js prettyprint-override"><code>
export function ZiFloatingLinkEditorPlugin(props){
  return(
    createPortal(
        <FloatingLinkEditor editor={activeEditor} anchorElem={props.anchorElem} />,
        props.anchorElem,
      )
)
</code>```

However, getting this error:

```<code>Function components cannot have string refs. We recommend using useRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Creating a ref via useRef():

export default function LexicalEditor() {
  const floatingAnchorElem = useRef(null);

  return(
      <LexicalComposer initialConfig={editorConfig} >
        <Container fluid >
          <LexicalToolbarPlugin />
          <Row className="justify-content-xl-center" id="editor-body" >
            <Col xs={7}>

                <RichTextPlugin
                  contentEditable={
                    <ContentEditable className="editor-input" style={ { borderColor: 'green', borderStyle: 'solid', minWidth: '50%', width: 'auto', minHeight: 500, height: 'auto' }} />
                  }
                />

            </Col>
            <LocalStoragePlugin />
            {floatingAnchorElem.current && (
              <>
                <FloatingLinkEditorPlugin anchorElem={floatingAnchorElem.current} />
              </>
              )
            }
          </Row>
        </Container>
      </LexicalComposer>
  )
}

and then inside FloatingLinkEditorPlugin, creating portal like so:

export function ZiFloatingLinkEditorPlugin(props){
  return(
    createPortal(
        <FloatingLinkEditor editor={activeEditor} anchorElem={props.anchorElem} />,
        props.anchorElem,
      )
)

However, getting this error:

Function components cannot have string refs. We recommend using useRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref


问:
How to import a function or variable from the sibling directory of Django project?
I want to import some functions a constants variables from 5 levels upper of the current app of Django application.

My problem is that the package that I want to import from, is outside of the Django application, so Django isn't aware of it.

project structure:

```<code>├── lawcrawler
│   ├── get_all_amended_laws_urls.py # import a function from this file
│   ├── lawcrawler
│   │   └── spiders
│   │       └── settings.py # import variables from this file
│   │
├── project
│   ├── apps
│   │   ├── laws
│   │       ├── management
│   │           ├── commands
│   │               ├── add_list_of_amended_laws.py # import function and variables to this file
│   ├── manage.py
</code>```

As per python docs, two or more leading dots indicate a relative import to the parent(s) of the current package, one level per dot after the first. So, I tried relative import like this:

```<code>from .......lawcrawler.lawcrawler.spiders.settings import SPARQL_ENDPOINT, AMENDED_URL_FILE_PATH, get_law_amendment_query
</code>```

and this:

```<code>from .....lawcrawler import get_all_amended_urls
</code>```

but got this error:

```<code>ImportError: attempted relative import with no known parent package
</code>```

How to import the functions and variables or solve this issue?

Body:
I want to import some functions a constants variables from 5 levels upper of the current app of Django application.

My problem is that the package that I want to import from, is outside of the Django application, so Django isn't aware of it.

project structure:

├── lawcrawler
│   ├── get_all_amended_laws_urls.py # import a function from this file
│   ├── lawcrawler
│   │   └── spiders
│   │       └── settings.py # import variables from this file
│   │
├── project
│   ├── apps
│   │   ├── laws
│   │       ├── management
│   │           ├── commands
│   │               ├── add_list_of_amended_laws.py # import function and variables to this file
│   ├── manage.py

As per python docs, two or more leading dots indicate a relative import to the parent(s) of the current package, one level per dot after the first. So, I tried relative import like this:

from .......lawcrawler.lawcrawler.spiders.settings import SPARQL_ENDPOINT, AMENDED_URL_FILE_PATH, get_law_amendment_query

and this:

from .....lawcrawler import get_all_amended_urls

but got this error:

ImportError: attempted relative import with no known parent package

How to import the functions and variables or solve this issue?


问:
Error while resampling from daily to monthly frequency
I have a csv data with daily frequency as shown below:

```<code>d = pd.read_csv("DGS5.csv")
d['DATE'] = pd.to_datetime(d.DATE)
d.set_index('DATE', inplace=True)
print(d)

            DGS5
      DATE
1962-01-02  3.88
1962-01-03  3.87
1962-01-04  3.86
1962-01-05  3.89
1962-01-08  3.91
... ...
2022-11-17  3.93
2022-11-18  3.99
2022-11-21  3.97
2022-11-22  3.93
2022-11-23  3.88
</code>```

When I try to resample this to monthly frequency, I get the following output; where DATE column is DATE column is converted to monthly frequency by missing DGS5 values.

```<code>d.resample('1m').mean()

      DATE
2022-01-31
2022-02-28
2022-03-31
2022-04-30
2022-05-31
2022-06-30
2022-07-31
2022-08-31
</code>```

Below the information about the data.

```<code><class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 15887 entries, 1962-01-02 to 2022-11-23
Data columns (total 1 columns):
 #   Column  Non-Null Count  Dtype
---  ------  --------------  -----
 0   DGS5    15887 non-null  object
dtypes: object(1)
</code>```

Appreciate support from the community to show where I am going wrong here.

Body:
I have a csv data with daily frequency as shown below:

d = pd.read_csv("DGS5.csv")
d['DATE'] = pd.to_datetime(d.DATE)
d.set_index('DATE', inplace=True)
print(d)

            DGS5
      DATE
1962-01-02  3.88
1962-01-03  3.87
1962-01-04  3.86
1962-01-05  3.89
1962-01-08  3.91
... ...
2022-11-17  3.93
2022-11-18  3.99
2022-11-21  3.97
2022-11-22  3.93
2022-11-23  3.88

When I try to resample this to monthly frequency, I get the following output; where DATE column is DATE column is converted to monthly frequency by missing DGS5 values.

d.resample('1m').mean()

      DATE
2022-01-31
2022-02-28
2022-03-31
2022-04-30
2022-05-31
2022-06-30
2022-07-31
2022-08-31

Below the information about the data.

<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 15887 entries, 1962-01-02 to 2022-11-23
Data columns (total 1 columns):
 #   Column  Non-Null Count  Dtype
---  ------  --------------  -----
 0   DGS5    15887 non-null  object
dtypes: object(1)

Appreciate support from the community to show where I am going wrong here.


问:
Reverse traffic tunneling by using ssh and socks
I got 3 machines. One is my local machine, let's say it's got this address:

44.44.44.44 this is my machine it is behind NAT running windows

55.55.55.55 The other machine it is my other remote machine not in local network, behind NAT too.

The 3rd machine is a Linux server. with the address 128.128.128.128

Now what i want to try and do is to use remote machine 55.55.55.55 as a socks proxy to forward traffic to outer world and local network, from 44.44.44.44 by using 128.128.128.128 as a medium.

Let's say now, i want to use as 55.55.55.55 as socks proxy for ftpserver:21 - so when i connect to ftpserver:21 my ip will be 55.55.55.55.

As i understand, what i do on 44.44.44.44 - i run this command:

```<code>ssh -N -L 9999:127.0.0.1:9000 user@128.128.128.128

ssh user@127.0.0.1 -p 9000 -N -D 127.0.0.1:9050
</code>```

This will redirect all traffic from my localhost port 9000 to 128.128.128.128 port 9999
Second command will create proxy on 127.0.0.1:9050 which will forward to 9000 port, which forwards to server 9999

Now, i don't understand very well what should i do on server 128.128.128.128 and on 55.55.55.55

I suppose i need to do something like this on 55.55.55.55:

```<code>ssh -N -R 9999:127.0.0.1:80 user@128.128.128.128
</code>```

This will forward from server 9999 to localhost:80 but i need to forward localhost:80 to the outer network now, not just to ftpserver:21.

Can someone help with this setup?

So essentially what i want:

44.44.44.44 -> 128.128.128.128 -> 55.55.55.55 -> Internet 44.44.44.44 <- 128.128.128.128 <- 55.55.55.55 <- Internet

55.55.55.55 is acting like a socks proxy

Body:
I got 3 machines. One is my local machine, let's say it's got this address:

44.44.44.44 this is my machine it is behind NAT running windows

55.55.55.55 The other machine it is my other remote machine not in local network, behind NAT too.

The 3rd machine is a Linux server. with the address 128.128.128.128

Now what i want to try and do is to use remote machine 55.55.55.55 as a socks proxy to forward traffic to outer world and local network, from 44.44.44.44 by using 128.128.128.128 as a medium.

Let's say now, i want to use as 55.55.55.55 as socks proxy for ftpserver:21 - so when i connect to ftpserver:21 my ip will be 55.55.55.55.

As i understand, what i do on 44.44.44.44 - i run this command:

ssh -N -L 9999:127.0.0.1:9000 user@128.128.128.128

ssh user@127.0.0.1 -p 9000 -N -D 127.0.0.1:9050

This will redirect all traffic from my localhost port 9000 to 128.128.128.128 port 9999
Second command will create proxy on 127.0.0.1:9050 which will forward to 9000 port, which forwards to server 9999

Now, i don't understand very well what should i do on server 128.128.128.128 and on 55.55.55.55

I suppose i need to do something like this on 55.55.55.55:

ssh -N -R 9999:127.0.0.1:80 user@128.128.128.128

This will forward from server 9999 to localhost:80 but i need to forward localhost:80 to the outer network now, not just to ftpserver:21.

Can someone help with this setup?

So essentially what i want:

44.44.44.44 -> 128.128.128.128 -> 55.55.55.55 -> Internet 44.44.44.44 <- 128.128.128.128 <- 55.55.55.55 <- Internet

55.55.55.55 is acting like a socks proxy


问:
how to manage bubbles' transitions in D3js
I am trying to create a moving bubbles with forceSimulation and a dropdown menu.

What I have now is that all bubbles start appearing at the same position and expanding due to d3.forceCollide(). Whenever I select from the dropdown, there are new bubbles appearing in another position together before expanding.

What I want is that all bubbles move without collapsing and expanding every time I make a choice from the dropdown menu.

Below is my code

```<code>function drawAvgExcessReturn_(
    data,
    dimensions,
    plan,
    benchmark,
    bound,
    legend,
    tooltip
){
    const yearAccessor = d => parseInt(d.fy)
    const aalAccessor = d => parseFloat(d.aal)
    const percentFormat = d3.format(".1%");

    let benchmarkReturnAccessor
    if(benchmark === 'Optimal benchmark'){
        benchmarkReturnAccessor =  d => parseFloat(d.avg_opt_benchmark_excess)
    } else {
        benchmarkReturnAccessor = d => parseFloat(d.avg_custom_benchmark_excess)
    }

    const rScale = d3.scaleSqrt()
        .domain(d3.extent(data, aalAccessor))
        .range([0,50])

    const xScale = d3.scaleLinear()
        .domain(d3.extent(data, benchmarkReturnAccessor))
        // .domain([-0.15,0.1])
        .range([0, 0.9 * dimensions.boundedWidth])
        .nice()

    // Create nodes for each data points
    let nodes = data.map(function(d, i){
        return {
            id: "node" + i,
            x: xScale(benchmarkReturnAccessor(d)),
            y: dimensions.boundedHeight / 2,
            r: rScale(aalAccessor(d)),
            rate: benchmarkReturnAccessor(d),
            cnt: aalAccessor(d),
            planName: d.plan_name,
            data: d
        }
    })

    const bubble_avgExcessReturn = bound
        .select(".bubbleAvgExcessReturn")
        .selectAll("circle")
        .data(nodes)
        .join("circle")
        .attr("cx", d => d.x)
        .attr("cy", d => d.y)
        .attr("id", d => "circle" + d.id)
        .attr("r", d => d.r)
        .style('fill', d => d.planName === plan ? "red": "grey")
        .attr('fill-opacity', d => d.planName === plan ? 0.5 : 0.2)
        .on("mouseover", function(e, d) {
            tooltip.html(d.planName + "<br/>" + percentFormat(d.rate))
            return tooltip.style('visibility', 'visible')
        })
        .on("mousemove", function(e, d){
            return tooltip.style("top", (e.pageY - 100) + "px").style("left", (e.pageX - 200) + "px");
        })
        .on("mouseout", function() {
            return tooltip.style("visibility", "hidden");
        })

    function ticked(e) {
        bubble_avgExcessReturn
            .attr("cx", d => d.x)
            .attr("cy", d => d.y)
    }

    const simulation = d3.forceSimulation(nodes)
        // .force("charge", d3.forceManyBody().strength([5]))
        .force("x", d3.forceX(d => d.x))
        .force("y", d3.forceY(dimensions.boundedWidth/5))
        .force("collision", d3.forceCollide().radius(d => d.r + dimensions.padding))
        // .alpha(.5)
        // .alphaDecay(0)
        .on("tick", ticked)

    const xAxis = d3.axisBottom(xScale)
        .tickFormat(d => percentFormat(d))
        .tickSize(8)
        .tickPadding(5)

    const xAxisEl = bound.select(".x-axis")
    xAxisEl.append("text")
        .attr("class", "axistitle")
        .attr("x", dimensions.width / 2)
        .attr("y", dimensions.margin.bottom - 10)
        .style("text-anchor", "middle")
        .style("fill", "grey")
        .style("fill-opacity", 1)
        .text("Average Excess Return")
    xAxisEl.call(xAxis)

    const zeroLine = bound.select(".zeroLine")
        .transition().duration(500)
        .attr("x1", xScale(0))
        .attr("x2", xScale(0))
        .attr("y1", dimensions.height * 0.85)
        .attr("y2", - dimensions.height)
        .style("stroke", "blue")
        .style("stroke-dasharray", "2px 4px")

    legend.selectAll(".ind")
        .data([50000000, 250000000, 500000000])
        .join('circle')
        .attr("class", "ind")
        .attr("r", d => rScale(d))
        .attr("cx", 100)
        .attr("cy", d => 130 - rScale(d))
        .style("fill", "none")
        .style("stroke", '#ccc')

    legend.selectAll(".leglabel")
        .data([50000000, 250000000, 500000000])
        .join("text")
        .attr("class", "leglabel")
        .attr("x", 100)
        .attr("y", d => 130 - rScale(d) * 2)
        .attr("dy", -4)
        .text(d => d3.format(",")(d / 1000000) + "mn")
        .style("font-size", ".7rem")
        .style("text-anchor", "middle")

}

export {drawAvgExcessReturn_}

</code>```

Body:
I am trying to create a moving bubbles with forceSimulation and a dropdown menu.

What I have now is that all bubbles start appearing at the same position and expanding due to d3.forceCollide(). Whenever I select from the dropdown, there are new bubbles appearing in another position together before expanding.

What I want is that all bubbles move without collapsing and expanding every time I make a choice from the dropdown menu.

Below is my code

function drawAvgExcessReturn_(
    data,
    dimensions,
    plan,
    benchmark,
    bound,
    legend,
    tooltip
){
    const yearAccessor = d => parseInt(d.fy)
    const aalAccessor = d => parseFloat(d.aal)
    const percentFormat = d3.format(".1%");

    let benchmarkReturnAccessor
    if(benchmark === 'Optimal benchmark'){
        benchmarkReturnAccessor =  d => parseFloat(d.avg_opt_benchmark_excess)
    } else {
        benchmarkReturnAccessor = d => parseFloat(d.avg_custom_benchmark_excess)
    }

    const rScale = d3.scaleSqrt()
        .domain(d3.extent(data, aalAccessor))
        .range([0,50])

    const xScale = d3.scaleLinear()
        .domain(d3.extent(data, benchmarkReturnAccessor))
        // .domain([-0.15,0.1])
        .range([0, 0.9 * dimensions.boundedWidth])
        .nice()

    // Create nodes for each data points
    let nodes = data.map(function(d, i){
        return {
            id: "node" + i,
            x: xScale(benchmarkReturnAccessor(d)),
            y: dimensions.boundedHeight / 2,
            r: rScale(aalAccessor(d)),
            rate: benchmarkReturnAccessor(d),
            cnt: aalAccessor(d),
            planName: d.plan_name,
            data: d
        }
    })

    const bubble_avgExcessReturn = bound
        .select(".bubbleAvgExcessReturn")
        .selectAll("circle")
        .data(nodes)
        .join("circle")
        .attr("cx", d => d.x)
        .attr("cy", d => d.y)
        .attr("id", d => "circle" + d.id)
        .attr("r", d => d.r)
        .style('fill', d => d.planName === plan ? "red": "grey")
        .attr('fill-opacity', d => d.planName === plan ? 0.5 : 0.2)
        .on("mouseover", function(e, d) {
            tooltip.html(d.planName + "
" + percentFormat(d.rate))
            return tooltip.style('visibility', 'visible')
        })
        .on("mousemove", function(e, d){
            return tooltip.style("top", (e.pageY - 100) + "px").style("left", (e.pageX - 200) + "px");
        })
        .on("mouseout", function() {
            return tooltip.style("visibility", "hidden");
        })

    function ticked(e) {
        bubble_avgExcessReturn
            .attr("cx", d => d.x)
            .attr("cy", d => d.y)
    }

    const simulation = d3.forceSimulation(nodes)
        // .force("charge", d3.forceManyBody().strength([5]))
        .force("x", d3.forceX(d => d.x))
        .force("y", d3.forceY(dimensions.boundedWidth/5))
        .force("collision", d3.forceCollide().radius(d => d.r + dimensions.padding))
        // .alpha(.5)
        // .alphaDecay(0)
        .on("tick", ticked)

    const xAxis = d3.axisBottom(xScale)
        .tickFormat(d => percentFormat(d))
        .tickSize(8)
        .tickPadding(5)

    const xAxisEl = bound.select(".x-axis")
    xAxisEl.append("text")
        .attr("class", "axistitle")
        .attr("x", dimensions.width / 2)
        .attr("y", dimensions.margin.bottom - 10)
        .style("text-anchor", "middle")
        .style("fill", "grey")
        .style("fill-opacity", 1)
        .text("Average Excess Return")
    xAxisEl.call(xAxis)

    const zeroLine = bound.select(".zeroLine")
        .transition().duration(500)
        .attr("x1", xScale(0))
        .attr("x2", xScale(0))
        .attr("y1", dimensions.height * 0.85)
        .attr("y2", - dimensions.height)
        .style("stroke", "blue")
        .style("stroke-dasharray", "2px 4px")

    legend.selectAll(".ind")
        .data([50000000, 250000000, 500000000])
        .join('circle')
        .attr("class", "ind")
        .attr("r", d => rScale(d))
        .attr("cx", 100)
        .attr("cy", d => 130 - rScale(d))
        .style("fill", "none")
        .style("stroke", '#ccc')

    legend.selectAll(".leglabel")
        .data([50000000, 250000000, 500000000])
        .join("text")
        .attr("class", "leglabel")
        .attr("x", 100)
        .attr("y", d => 130 - rScale(d) * 2)
        .attr("dy", -4)
        .text(d => d3.format(",")(d / 1000000) + "mn")
        .style("font-size", ".7rem")
        .style("text-anchor", "middle")

}

export {drawAvgExcessReturn_}


问:
Solving the Rosalind challenge "Finding a Motif in DNA"
The problem I am currently working on gives you a DNA string and a substring. You need to have your code output the start location of each instance of the substring in the DNA string. For ex;
given DNA string = "GATATATGCATATACTT"
substring = "ATAT"
output should be: 2 4 10
this ex is what I am using to test my code

Link to rosalind problem if you need: https://rosalind.info/problems/subs/

The code I currently have almost works correctly:

```<code># Finding a Motif in DNA

input <- readLines("input.txt", warn = FALSE) # Load data

DNAseq1 <- input[1] # line 1 of data file is DNA string
substring1 <- input[2] # line 2 of data file is the substring being searched for

print(DNAseq1)     #
print(substring1)  # Test commands to make sure the lines are being assigned to the variables correctly

print(unlist(gregexpr(substring1, DNAseq1)))
</code>```

The output it returns is:

```<code>[1] 2 10
</code>```

However, it should output:

```<code>[1] 2 4 10
</code>```

The DNA string is "GATATATGCATATACTT" and the substring is "ATAT", I believe it's not picking up location 4 (2nd instance of substring) due to it being in the middle of the first instance of the substring. I'm not sure how to fix this, please help!

Body:
The problem I am currently working on gives you a DNA string and a substring. You need to have your code output the start location of each instance of the substring in the DNA string. For ex;
given DNA string = "GATATATGCATATACTT"
substring = "ATAT"
output should be: 2 4 10
this ex is what I am using to test my code

Link to rosalind problem if you need: https://rosalind.info/problems/subs/

The code I currently have almost works correctly:

# Finding a Motif in DNA

input <- readLines("input.txt", warn = FALSE) # Load data

DNAseq1 <- input[1] # line 1 of data file is DNA string
substring1 <- input[2] # line 2 of data file is the substring being searched for

print(DNAseq1)     #
print(substring1)  # Test commands to make sure the lines are being assigned to the variables correctly

print(unlist(gregexpr(substring1, DNAseq1)))

The output it returns is:

[1] 2 10

However, it should output:

[1] 2 4 10

The DNA string is "GATATATGCATATACTT" and the substring is "ATAT", I believe it's not picking up location 4 (2nd instance of substring) due to it being in the middle of the first instance of the substring. I'm not sure how to fix this, please help!


问:
How to create a customized hovertemplate for plotly graph object parcats or express parallel categories
on hover on the nodes, how can I show the label of that node in hoverbox?</p>


问:
list ALL revisions of googlesheets file
I found that Drive.Revisions.list(fileId) lists the last refresh of each history group but not the list of revisions inside each group ( see the screenshotpicture[1]).
Is there a way to obtain this detail or failing to cause/force the creation of a new group with appscript to have access to it?
[1]: https://i.stack.imgur.com/3GwVc.png</p>

Title: list ALL revisions of googlesheets file


问:
integrating zoom account type checking for third party zoom integration
How to check the plan type of the zoom account we are using.
Here i have to check if the zoom account the user is giving is eligibile for webinar.

in the account details of zoom support it is showing the account type, i have to integrate this to my app so before registering for the webinar we can alert the user that the users zoom account is eligible for webinar or not,
thanks in advance


问:
How to click a button, which is present in the next page using Javascript
I am actually trying to automate a course completing process (Just need to click next, next...). In this process I have to click series of buttons. At first I have to click next btn and after that the next page loads and then I have to click a start button which is present in the newly loaded page. For clicking the same button in every page, it worked perfectly with setInterval. But when I need to click different buttons in a sequence it's not working. It either shows .click() function of that new btn is not available or it shows no error at all. I tried using async/await, promises, sleep to overcome this problem, but no hope. Even if you guys had any idea with the methods mentioned earlier, feel free to share.

" button" />

">" button needs to be clicked, which loads the next page(image below)

start button needs to be clicked.

Using setInterval

```<code>//function for single button click (works fine)
  setInterval(()=>{
    document.getElementsByClassName("nextButton")[0].click()
  },500)
// https://youtu.be/EFLfde7x0TE
</code>```
```<code>//In this code, the next btn is working but the start btn is not working.
  setInterval(() => {
    next_btn.click()
    start_btn.click()
  }, 5000);
//MasterInterval in the error denotes the above setInterval function.
</code>```

Using Promises

```<code>let P1 = new Promise(() => {
    setTimeout(() => {
        next_btn.click()
    }, 3000);
})

P1.then(() => {
    setTimeout(() => {
        start_btn.click()
    }, 3000);
})
//no errors, next btn is only working nothing else
</code>```

Body:
I am actually trying to automate a course completing process (Just need to click next, next...). In this process I have to click series of buttons. At first I have to click next btn and after that the next page loads and then I have to click a start button which is present in the newly loaded page. For clicking the same button in every page, it worked perfectly with setInterval. But when I need to click different buttons in a sequence it's not working. It either shows .click() function of that new btn is not available or it shows no error at all. I tried using async/await, promises, sleep to overcome this problem, but no hope. Even if you guys had any idea with the methods mentioned earlier, feel free to share.

" button" />

">" button needs to be clicked, which loads the next page(image below)

start button needs to be clicked.

Using setInterval

//function for single button click (works fine)
  setInterval(()=>{
    document.getElementsByClassName("nextButton")[0].click()
  },500)
// https://youtu.be/EFLfde7x0TE

//In this code, the next btn is working but the start btn is not working.
  setInterval(() => {
    next_btn.click()
    start_btn.click()
  }, 5000);
//MasterInterval in the error denotes the above setInterval function.

Using Promises

let P1 = new Promise(() => {
    setTimeout(() => {
        next_btn.click()
    }, 3000);
})

P1.then(() => {
    setTimeout(() => {
        start_btn.click()
    }, 3000);
})
//no errors, next btn is only working nothing else


问:
Too few arguments to function Pengaturan::penggunaedit(), 0 passed
Error process to database on click submit (CodeIgniter 3)

Please help me.

An uncaught Exception was encountered

Type: ArgumentCountError

Message: Too few arguments to function Pengaturan::penggunaedit(), 0 passed in D:\xampp_7.4\htdocs\simpro\system\core\CodeIgniter.php on line 533 and exactly 1 expected

Filename: D:\xampp_7.4\htdocs\simpro\application\modules\pengaturan\controllers\Pengaturan.php

Line Number: 144

Backtrace:

File: D:\xampp_7.4\htdocs\simpro\index.php

Line: 315

Function: require_once

Controller

```<code>public function penggunaedit($id)
    {
        //var_dump($id);
        $session['sesi'] = $this->db->get_where('pengguna', ['id' => $this->session->userdata('id')])->row_array();
        $data['title'] = "Pengaturan | Pengguna";

        $data['pengguna'] = $this->PenggunaModel->getPenggunaById($id);

        $this->form_validation->set_rules('id', 'ID', 'required|trim');
        $this->form_validation->set_rules('nama', 'Nama', 'required|trim');
        $this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email');
        $this->form_validation->set_rules('password', 'Password', 'required|trim|min_length[3]', ['min_length' => 'Password min 3 characters']);

        if ($this->form_validation->run() == false) {
            $this->load->view('templates/header', $data);
            $this->load->view('templates/topbar', $session);
            $this->load->view('templates/pengaturan/sidebar', $data);
            $this->load->view('pengaturan/pengguna/update', $data);
            $this->load->view('templates/footer', $data);
        } else {
            $this->load->model('pengaturan/PenggunaModel');
            $this->PenggunaModel->UpdatePengguna($id);
            redirect('pengaturan/pengguna');
        }
    }
</code>```

Model

```<code>public function getPenggunaById($id)
    {
        return $this->db->get_where('pengguna', ['id' => $id])->row_array();
    }
    // public function edit_data($id)
    // {
    //     $data = array(
    //         'nama' => $this->input->post('nama'),
    //         'email' => $this->input->post('email'),
    //         'password' => hash('sha256', $this->input->post('password'))
    //     );
    //     $this->db->where('id', $id);
    //     return $this->db->update('pengguna', $data);
    // }

    public function UpdatePengguna()
    {
        $id = $this->input->post('id', true);
        var_dump($id);
        $data = [
            'nama' => $this->input->post('nama'),
            'email' => $this->input->post('email')
        ];
        $this->db->set('pengguna', $data);
        $this->db->where('id', $id);
        return $this->db->update('pengguna');
    }
</code>```

View

```<code><form method="POST" action="<?= base_url('pengaturan/penggunaedit'); ?>">
                                    <div class="col-md-5">
                                        <input type="hidden" name="id" value="<?= $pengguna['id']; ?>">
                                        <div class="form-grup pb-3">
                                            <label for="formGroupExampleInput1" class="form-label">Masukkan ID</label>
                                            <input type="text" class="form-control" placeholder="ID" value="<?= set_value('id'); ?><?= $pengguna['id']; ?>" disabled>
                                            <?= form_error('id', '<small class="text-danger pl-3">', '</small>'); ?>
                                        </div>
                                        <div class="form-grup pb-3">
                                            <label for="formGroupExampleInput1" class="form-label">Masukkan Nama</label>
                                            <input type="text" class="form-control" placeholder="Nama" name="nama" value="<?= $pengguna['nama'] ?><?= set_value('nama'); ?>">
                                            <?= form_error('nama', '<small class="text-danger pl-3">', '</small>'); ?>
                                        </div>
                                        <div class="form-grup pb-3">
                                            <label for="formGroupExampleInput1" class="form-label">Masukkan Email</label>
                                            <input type="email" class="form-control" placeholder="Email" name="email" value="<?= set_value('email'); ?><?= $pengguna['email']; ?>">
                                            <?= form_error('email', '<small class="text-danger pl-3">', '</small>'); ?>
                                        </div>
                                        <button class="btn btn-primary" type="submit">Simpan</button>
                                    </div>
                                </form>
</code>```
```<code></code>```

Body:
Error process to database on click submit (CodeIgniter 3)

Please help me.

An uncaught Exception was encountered

Type: ArgumentCountError

Message: Too few arguments to function Pengaturan::penggunaedit(), 0 passed in D:\xampp_7.4\htdocs\simpro\system\core\CodeIgniter.php on line 533 and exactly 1 expected

Filename: D:\xampp_7.4\htdocs\simpro\application\modules\pengaturan\controllers\Pengaturan.php

Line Number: 144

Backtrace:

File: D:\xampp_7.4\htdocs\simpro\index.php

Line: 315

Function: require_once

Controller

public function penggunaedit($id)
    {
        //var_dump($id);
        $session['sesi'] = $this->db->get_where('pengguna', ['id' => $this->session->userdata('id')])->row_array();
        $data['title'] = "Pengaturan | Pengguna";

        $data['pengguna'] = $this->PenggunaModel->getPenggunaById($id);

        $this->form_validation->set_rules('id', 'ID', 'required|trim');
        $this->form_validation->set_rules('nama', 'Nama', 'required|trim');
        $this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email');
        $this->form_validation->set_rules('password', 'Password', 'required|trim|min_length[3]', ['min_length' => 'Password min 3 characters']);

        if ($this->form_validation->run() == false) {
            $this->load->view('templates/header', $data);
            $this->load->view('templates/topbar', $session);
            $this->load->view('templates/pengaturan/sidebar', $data);
            $this->load->view('pengaturan/pengguna/update', $data);
            $this->load->view('templates/footer', $data);
        } else {
            $this->load->model('pengaturan/PenggunaModel');
            $this->PenggunaModel->UpdatePengguna($id);
            redirect('pengaturan/pengguna');
        }
    }

Model

public function getPenggunaById($id)
    {
        return $this->db->get_where('pengguna', ['id' => $id])->row_array();
    }
    // public function edit_data($id)
    // {
    //     $data = array(
    //         'nama' => $this->input->post('nama'),
    //         'email' => $this->input->post('email'),
    //         'password' => hash('sha256', $this->input->post('password'))
    //     );
    //     $this->db->where('id', $id);
    //     return $this->db->update('pengguna', $data);
    // }

    public function UpdatePengguna()
    {
        $id = $this->input->post('id', true);
        var_dump($id);
        $data = [
            'nama' => $this->input->post('nama'),
            'email' => $this->input->post('email')
        ];
        $this->db->set('pengguna', $data);
        $this->db->where('id', $id);
        return $this->db->update('pengguna');
    }

View

<form method="POST" action="<?= base_url('pengaturan/penggunaedit'); ?>">

                                        <input type="hidden" name="id" value="<?= $pengguna['id']; ?>">

                                            Masukkan ID
                                            <input type="text" class="form-control" placeholder="ID" value="<?= set_value('id'); ?><?= $pengguna['id']; ?>" disabled>
                                            <?= form_error('id', '', ''); ?>

                                            Masukkan Nama
                                            <input type="text" class="form-control" placeholder="Nama" name="nama" value="<?= $pengguna['nama'] ?><?= set_value('nama'); ?>">
                                            <?= form_error('nama', '', ''); ?>

                                            Masukkan Email
                                            <input type="email" class="form-control" placeholder="Email" name="email" value="<?= set_value('email'); ?><?= $pengguna['email']; ?>">
                                            <?= form_error('email', '', ''); ?>

                                        <button class="btn btn-primary" type="submit">Simpan</button>

                                </form>


问:
How to get the count of the number of files were dropped in an input type file?
I want to get a count of the number of files, Its working fine when I select files, but when I use drag and drop onchange is not working.
I'm using filepond for image uploading.

Below is my code

```<code><input type="file" name="imageUpload" id="imageUpload" maxFiles="24" multiple data-allow-reorder="true" data-max-file-size="15MB" data-allow-reorder="true" allowImageResize accept="image/png, image/jpeg, image/gif, image/webp, image/svg"/>
</code>```

Below is my JS function

```<code>$( document ).ready(function()
  {
    $('input[type=file]').on('change',function () {
    fileCount = this.files.length;
    var firstLength = 100/fileCount;
    alert(firstLength );
  });
});
</code>```

I found below code from stack

```<code>$("#imageUpload").on('change drop', function (e) {
  e.preventDefault();
  e.stopPropagation();
  var files = $(this)[0].files;
  alert(files.length);
});
</code>```

Above code give this error in console.
"Uncaught TypeError: Cannot read properties of undefined (reading 'length')"

Any lead is appreciated.

Body:
I want to get a count of the number of files, Its working fine when I select files, but when I use drag and drop onchange is not working.
I'm using filepond for image uploading.

Below is my code

<input type="file" name="imageUpload" id="imageUpload" maxFiles="24" multiple data-allow-reorder="true" data-max-file-size="15MB" data-allow-reorder="true" allowImageResize accept="image/png, image/jpeg, image/gif, image/webp, image/svg"/>

Below is my JS function

$( document ).ready(function()
  {
    $('input[type=file]').on('change',function () {
    fileCount = this.files.length;
    var firstLength = 100/fileCount;
    alert(firstLength );
  });
});

I found below code from stack

$("#imageUpload").on('change drop', function (e) {
  e.preventDefault();
  e.stopPropagation();
  var files = $(this)[0].files;
  alert(files.length);
});

Above code give this error in console.
"Uncaught TypeError: Cannot read properties of undefined (reading 'length')"

Any lead is appreciated.


问:
Is that possible to display jMeter run time in grafana dashboard
i created a dashboard for display load test results. i used JMeter, influx dB, grafana for that. after that I found a dashboard it is able to fulfill my need. but it's not display respond time correctly.in that case i want to know is that possible to display in grafana panel how much time does JMeter takes for run a script.

I tried it using grafana annunciator panel also. but its not given me right time spent for run that process.


问:
How to mount docker container directories files to host directory
path to my host directory the directory name is snorttest

The above image contains the host directory which contains a directory called snorttest

docker container directory

The above image contains my docker container directory path which is /etc/snort/etc which i am trying to bindmount to my host directory.

I am trying to get the content of docker containers /etc/snort/etc to my host directories /etc/snorttest/etc/snort directory. But when I am running the below command which is
$docker run -d -t -v /etc/snorttest/etc/snort:/etc/snort/etc  snort5:latest /bin/bash

nothing is reflecting in my host directories etc/snort folder( I want the contents of docker containers /etc/snort folders to my host directory).


问:
How to treat different cases of a character as different base letter in Unicode Collation Algorithm (UCA)?
UCA defines serveral levels for character comparsion.

The case level is swamped by the stronger level and only take effect when the base characters and accents are same for two strings, so how can I treat the cases as base characters in a comparsion? For example, I want to get the order role < roles < Role (all strings that start with r order before those start with R)?


问:
Component not rendering and test case fails
i have created a test case for my navbar component but it is not working and when i console debug my component is not rendered i am giving my code :

```<code>import React from "react";
import { render, fireEvent } from "@testing-library/react";
import { Navbar } from "../component/Navbar";
import { Provider, useDispatch } from "react-redux";
import { Router } from "react-router-dom";
import { createMemoryHistory } from "history";
import { reducers } from "../redux/reducers";
import { createStore } from "redux";

jest.mock("react-redux", () => {
  return {
    useDispatch: jest.fn()
  };
});

describe("Navbar component", () => {
  it("should dispatch the logout action when the logout button is clicked", () => {
    const dispatch = jest.fn();
    useDispatch.mockReturnValue(dispatch);
    const history = createMemoryHistory("/");
    let store = createStore(reducers);
    const { getByText } = render(
        <Provider store={store}>
        <Router location={history.location} navigator={history}>
          <Navbar />
        </Router>
      </Provider>
    );
    fireEvent.click(getByText("Logout"));
    expect(dispatch).toHaveBeenCalledWith(Logout());
  });
});
</code>```

when i debug i am getting the value as:

```<code> console.log
      <ContextProvider value={{...}}>
        <Router location={{...}} navigator={{...}}>
          <Navbar />
        </Router>
      </ContextProvider>
</code>```

i am using react redux in my project can anyone help me with it

Body:
i have created a test case for my navbar component but it is not working and when i console debug my component is not rendered i am giving my code :

import React from "react";
import { render, fireEvent } from "@testing-library/react";
import { Navbar } from "../component/Navbar";
import { Provider, useDispatch } from "react-redux";
import { Router } from "react-router-dom";
import { createMemoryHistory } from "history";
import { reducers } from "../redux/reducers";
import { createStore } from "redux";

jest.mock("react-redux", () => {
  return {
    useDispatch: jest.fn()
  };
});

describe("Navbar component", () => {
  it("should dispatch the logout action when the logout button is clicked", () => {
    const dispatch = jest.fn();
    useDispatch.mockReturnValue(dispatch);
    const history = createMemoryHistory("/");
    let store = createStore(reducers);
    const { getByText } = render(
        <Provider store={store}>
        <Router location={history.location} navigator={history}>
          <Navbar />
        </Router>
      </Provider>
    );
    fireEvent.click(getByText("Logout"));
    expect(dispatch).toHaveBeenCalledWith(Logout());
  });
});

when i debug i am getting the value as:

 console.log
      <ContextProvider value={{...}}>
        <Router location={{...}} navigator={{...}}>
          <Navbar />
        </Router>
      </ContextProvider>

i am using react redux in my project can anyone help me with it


问:
Getting "try reformatting" in play console help page
i am getting an error in play console help page "try reformatting even though i fill up all the details but in location i am getting this error, i even change the country and browser but it is not working

i lost my upload key, without that i can't publish new updates, please help me
screenshot of the page's error

tried changing country, fill up all the details, and even change my browser as well.


问:
Unauthorized error while using api key in ios or android app
Am using here api for autosuggest, api is restricted at domain level, Api is working fine at my website but when i use the same api key at android or ios its giving unauthorized error.

PS: I have not integrated sdk to my ios or android, I am directly calling the here api

I tried removing the restriction at domain level then api is working fine but when i add restriction at domain level in my project section its giving error.


问:
Adding filter expression in collection mapping rules XDCR with Java client
I am integrating XDCR via JAVA Sdk. If I need to setup filter expression per collection mapping rule how to do in java?
say collection mapping rule 1 has one filter expression,
collection mapping rule 2 has some other filter expression and so on.</p>


问:
Google Sheet Formula: Preventing the serial number of duplicates below to go up
I'm currently struggling to assign serial number to a series of dynamic data in google spreadsheet.

for example, i have this table below

Product
Serial Number

Apple
1

Orange
1

Lemon
1

Banana
1

Apple
2

Melon
1

Lemon
2

Orange
2

Banana
2

Apple
3

currently on column B i'm using the formula =COUNTIF($A$1:A1,A1)

But the problem is, when i change the product on column A to another, the serial number of the duplicates below will automatically go up. for instance, if i change the 2nd Apple to Orange, the serial number of the 3rd Apple will automatically go up to 2.

I'd like the serial number of duplicates below to not be changed because it will be sent to the customer (i hope i'm making sense).

is there a way for me to do this?
any help will be much appreciated.


问:
How to use JMapper
How to use JMapper to concatenate two properties
For example

```<code>class MyDestination {
  String name;
  Integer age;
  String address;
}
</code>```
```<code>class MySOURCE{
  String name;
  String lastname;
  Integer age;
  String address;
}
</code>```

From which I want the result when mapping the concatenation of first and last name

```<code>class MyDestination {
    @JMap(attributes = {"name", "lastname"})
    String name;
    @JMap("age")
    Integer age;
    @JMap("address")
    String address;
}

class MySOURCE{
  String name;
  String lastname;
  Integer age;
  String address;
}
</code>```

Title: How to use JMapper

Body:
How to use JMapper to concatenate two properties
For example

class MyDestination {
  String name;
  Integer age;
  String address;
}

class MySOURCE{
  String name;
  String lastname;
  Integer age;
  String address;
}

From which I want the result when mapping the concatenation of first and last name

class MyDestination {
    @JMap(attributes = {"name", "lastname"})
    String name;
    @JMap("age")
    Integer age;
    @JMap("address")
    String address;
}

class MySOURCE{
  String name;
  String lastname;
  Integer age;
  String address;
}


问:
CI/CD pipleline to not allow push of staging URL
So I have a staging URL in my React app to test out the staging features of our website, whenever I am working on a feature we test the feature on the staging URL and then later while pushing to production we update the base URL to production.

```<code>export const ApiConfigData = {
  STAGING_URL: 'https://app.xyz.io/staging-app/',
  BASE_URL: 'https://app.xyz.io/app/',
};
</code>```

At times staging URL has been pushed to production, as we forgot to update it in ApiConfigData. I was thinking of including a Jest test case to check if the staging URL is being used or not and depending on the result the pipeline would continue.

Can someone help me with the test case, I just want to check if the above staging URL is being used or not. Or if there is some other better way to handle this issue of not pushing the staging URL.

Any advice would be appreciated as I don't have much experience with CI/CD and writing test cases.

Body:
So I have a staging URL in my React app to test out the staging features of our website, whenever I am working on a feature we test the feature on the staging URL and then later while pushing to production we update the base URL to production.

export const ApiConfigData = {
  STAGING_URL: 'https://app.xyz.io/staging-app/',
  BASE_URL: 'https://app.xyz.io/app/',
};

At times staging URL has been pushed to production, as we forgot to update it in ApiConfigData. I was thinking of including a Jest test case to check if the staging URL is being used or not and depending on the result the pipeline would continue.

Can someone help me with the test case, I just want to check if the above staging URL is being used or not. Or if there is some other better way to handle this issue of not pushing the staging URL.

Any advice would be appreciated as I don't have much experience with CI/CD and writing test cases.


问:
How to reference arcGIS MapViewModel in codebehind?
I'm using the recommended MVVM method to create an ArcGIS map in my WPF app and in my map initialisation SetupMap() I'm using a local webservice for the map resource, however the URL for the webservice is not known at the time the MapViewModel instance is created and hence the map initialisation function cannot create the map at that time. The URL for webservice is loaded later from an XML config file, so I need to call the SetupMap() function once that URL is known.

.xaml code is -

```<code>    <Window.Resources>
        <local:MapViewModel x:Key="MapViewModel" />
    </Window.Resources>
</code>```

and below in the grid -

```<code>  <Grid>
     <esri:MapView x:Name="MainMapView" Map="{Binding SiteBaseMap, Source={StaticResource MapViewModel}}" />
  </Grid>

</code>```

MapViewModel class -

```<code>    public class MapViewModel : INotifyPropertyChanged
    {
        public MapViewModel()
        {
            SetupMap();
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        private Map _map;
        public Map SiteBaseMap
        {
            get { return _map; }
            set { _map = value; OnPropertyChanged(); }
        }
        private void SetupMap()
        {
            // Create a new map with a 'topographic vector' basemap.
            SiteBaseMap = new Map(BasemapStyle.ArcGISImageryStandard);
        }

        public void arcGISAddLayers(string iURI, string sURI)
        {
            Uri imageUri = new Uri(iURI);
            Uri surfaceUri = new Uri(sURI);

            // Create new tiled layer from the url
            ArcGISTiledLayer imageLayer = new ArcGISTiledLayer(imageUri);
            ArcGISTiledLayer surfaceLayer = new ArcGISTiledLayer(surfaceUri);
         }
         // add layers etc below here...
    }

</code>```

As per the previously answered question

Accessing a resource via codebehind in WPF

I have tried

```<code>            object resource = Application.Current.TryFindResource("MapViewModel");
            MapViewModel mvm = (MapViewModel)resource;
</code>```

but mvm is null so it has not found the resource.

Am I assigning the resource incorrectly or why is it not finding the resource?

Update -

this does work -

```<code>            object resource = this.Resources["MapViewModel"];
            MapViewModel mvm = (MapViewModel)resource;
</code>```

and so does this -

```<code>            object resource = this.TryFindResource("MapViewModel");
            MapViewModel mvm = (MapViewModel)resource;
</code>```

but I would like to know why the first way doesn't (since this is one of the suggested solutions in the previously answered question).

Body:
I'm using the recommended MVVM method to create an ArcGIS map in my WPF app and in my map initialisation SetupMap() I'm using a local webservice for the map resource, however the URL for the webservice is not known at the time the MapViewModel instance is created and hence the map initialisation function cannot create the map at that time. The URL for webservice is loaded later from an XML config file, so I need to call the SetupMap() function once that URL is known.

.xaml code is -

    <Window.Resources>
        <local:MapViewModel x:Key="MapViewModel" />
    </Window.Resources>

and below in the grid -

  <Grid>
     <esri:MapView x:Name="MainMapView" Map="{Binding SiteBaseMap, Source={StaticResource MapViewModel}}" />
  </Grid>

MapViewModel class -

    public class MapViewModel : INotifyPropertyChanged
    {
        public MapViewModel()
        {
            SetupMap();
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        private Map _map;
        public Map SiteBaseMap
        {
            get { return _map; }
            set { _map = value; OnPropertyChanged(); }
        }
        private void SetupMap()
        {
            // Create a new map with a 'topographic vector' basemap.
            SiteBaseMap = new Map(BasemapStyle.ArcGISImageryStandard);
        }

        public void arcGISAddLayers(string iURI, string sURI)
        {
            Uri imageUri = new Uri(iURI);
            Uri surfaceUri = new Uri(sURI);

            // Create new tiled layer from the url
            ArcGISTiledLayer imageLayer = new ArcGISTiledLayer(imageUri);
            ArcGISTiledLayer surfaceLayer = new ArcGISTiledLayer(surfaceUri);
         }
         // add layers etc below here...
    }

As per the previously answered question

Accessing a resource via codebehind in WPF

I have tried

            object resource = Application.Current.TryFindResource("MapViewModel");
            MapViewModel mvm = (MapViewModel)resource;

but mvm is null so it has not found the resource.

Am I assigning the resource incorrectly or why is it not finding the resource?

Update -

this does work -

            object resource = this.Resources["MapViewModel"];
            MapViewModel mvm = (MapViewModel)resource;

and so does this -

            object resource = this.TryFindResource("MapViewModel");
            MapViewModel mvm = (MapViewModel)resource;

but I would like to know why the first way doesn't (since this is one of the suggested solutions in the previously answered question).


问:
Apache Camel Quarkus Microservices in Kubernetes using serviceCall()
I have recently read the book "Cloud Native Integration with Apache Camel" (by Guilherme Camposo) and went through the examples. Furthermore, I read the chapter "17.7 Calling clustered services using the Service Call EIP" from "Camel in Action" (by Claus Ibsen).
However, I am failing to understand how 2 separate Camel apps (quarkus/minikube) in the same pod could communicate with each other using the Camel serviceCall() method.

I was wondering if there are any good & simple examples which make use of Kubernetes only and don't require a discovery service (such as Consul , Eureka).

Thank you


问:
Fastai learn.predict show error 'collections.OrderedDict' object has no attribute 'predict'
I try to predict data with fastai2 by using learn.predict() like this code.

```<code>learn = load_learner('face_detection/weights/WIDERFace_DSFD_RES152.pth',cpu=False)

classNames = ['angela_markel','anushka_sharma','donald_trump','narendra_modi',"salman_khan",'shushant_singh_rajput',"valdimir_putin"]

img = load_image('test_data1/imdasd.jpeg')

img.show()
pred_class,preds_idx,outputs = learn.predict(img)
print(pred_class)
</code>```

It show error like this.

```<code>AttributeError: 'collections.OrderedDict' object has no attribute 'predict'
</code>```

How to use fastai predict image?

Body:
I try to predict data with fastai2 by using learn.predict() like this code.

learn = load_learner('face_detection/weights/WIDERFace_DSFD_RES152.pth',cpu=False)

classNames = ['angela_markel','anushka_sharma','donald_trump','narendra_modi',"salman_khan",'shushant_singh_rajput',"valdimir_putin"]

img = load_image('test_data1/imdasd.jpeg')

img.show()
pred_class,preds_idx,outputs = learn.predict(img)
print(pred_class)

It show error like this.

AttributeError: 'collections.OrderedDict' object has no attribute 'predict'

How to use fastai predict image?


问:
How to use multiple lines on react chart
Hello, I'm working on an application where I need to display a given pricing to the user for, say, 10 to 15 seconds. To do this, I need to draw a tracing line for 10 seconds in a row as seen in the figure below.
Here's an example
https://ibb.co/YtBZdvs
And my application stack is nodejs, Reactjs and i am looking for chart solution


问:
How could I open and close debug code blocks in a large project, flexiblely and robostly?
```<code>            if debug:
                cv2.line(image_copy, (x1I, y1I), (x2I, y1I), (255, 0, 0), thickness=1)
                cv2.line(image_copy, (x2I, y1I), (x2I, y2I), (255, 0, 0), thickness=1)
                cv2.line(image_copy, (x2I, y2I), (x1I, y2I), (255, 0, 0), thickness=1)
                cv2.line(image_copy, (x1I, y2I), (x1I, y1I), (255, 0, 0), thickness=1)
                dst_img[:img_h, :img_w] = image_copy
                dst_img[y1I : y2I, x1I + img_w : x2I + img_w] = image
                cv2.imwrite("{}_{}.png".format(index, self.name), dst_img)
</code>```

For Example, I insert a code block like this in my program to debug code. How could I open and close these debug code blocks in a large project, flexiblely and robostly?

Now, I define a local variable 'debug' in current python script. When I want to switch to debug mode, I change 'debug = true'.On the contrary, I change 'debug = false'. But I think this is a little 'hard code'. When somebody else develop this program and this program is large, it is inconvenient to cooperation.

Ps, I don't want to remove these code block, because maybe it is helpful for me later.

Body:
            if debug:
                cv2.line(image_copy, (x1I, y1I), (x2I, y1I), (255, 0, 0), thickness=1)
                cv2.line(image_copy, (x2I, y1I), (x2I, y2I), (255, 0, 0), thickness=1)
                cv2.line(image_copy, (x2I, y2I), (x1I, y2I), (255, 0, 0), thickness=1)
                cv2.line(image_copy, (x1I, y2I), (x1I, y1I), (255, 0, 0), thickness=1)
                dst_img[:img_h, :img_w] = image_copy
                dst_img[y1I : y2I, x1I + img_w : x2I + img_w] = image
                cv2.imwrite("{}_{}.png".format(index, self.name), dst_img)

For Example, I insert a code block like this in my program to debug code. How could I open and close these debug code blocks in a large project, flexiblely and robostly?

Now, I define a local variable 'debug' in current python script. When I want to switch to debug mode, I change 'debug = true'.On the contrary, I change 'debug = false'. But I think this is a little 'hard code'. When somebody else develop this program and this program is large, it is inconvenient to cooperation.

Ps, I don't want to remove these code block, because maybe it is helpful for me later.


问:
Call an Electron function of renderer or main process from online website
An Electron app has a <webview> component inside a renderer process.

IPC is used to communicate between the main process and the renderer process without using remote module. (nodeIntegration=false too)

The <webview> shows an online website (html) under my control.

I want to call a specific function in either renderer process or main process from the online website.

For example,

[Online HTML webpage]

```<code><script>
var arg1 = ....getAsyncFrom...(); // need to fetch from web
function callHandler(arg1, arg2...) {
 window.myElectronApp.callHandlerFromWeb(arg1, arg2);
}
</script>
</code>```

[Electron app (maybe in a renderer process)]

```<code>let myWebViewControl = document.getElementById('myWebView');

// for security reason, "callHandlerFromWeb" is explicitly nominated
sampleCallBack.response("callHandlerFromWeb", (arg1, arg2..) => {
 callHandlerInsideElectron(arg1, arg2...);
});

    function callHandlerInsideElectron(arg1, arg2) {
     console.log("Handler called from webpage" + arg1 + arg2);
    }
</code>```

(I am not asking how to call a main process function from a renderer process. But, how can I call an Electron app's function with arguments from online website inside webview.)

+ Exactly the same thing that I am looking for is possible in Flutter Webview. This is neither a new nor 'dangerous' thing.

Thank you.

Body:
An Electron app has a <webview> component inside a renderer process.

IPC is used to communicate between the main process and the renderer process without using remote module. (nodeIntegration=false too)

The <webview> shows an online website (html) under my control.

I want to call a specific function in either renderer process or main process from the online website.

For example,

[Online HTML webpage]

[Electron app (maybe in a renderer process)]

let myWebViewControl = document.getElementById('myWebView');

// for security reason, "callHandlerFromWeb" is explicitly nominated
sampleCallBack.response("callHandlerFromWeb", (arg1, arg2..) => {
 callHandlerInsideElectron(arg1, arg2...);
});

    function callHandlerInsideElectron(arg1, arg2) {
     console.log("Handler called from webpage" + arg1 + arg2);
    }

(I am not asking how to call a main process function from a renderer process. But, how can I call an Electron app's function with arguments from online website inside webview.)

+ Exactly the same thing that I am looking for is possible in Flutter Webview. This is neither a new nor 'dangerous' thing.

Thank you.


问:
Exact use cases of debounce in React
If an onChange event is invoked for each keyboard input and there is a logic inside the change handler that calls a particular API, we know that unnecessarily many calls are made, and we use debounce to resolve them.

```<code>import React, { useState, useCallback } from 'react';
import { debounce } from 'lodash';

export default function App() {
  const [value, setValue] = useState('');

  const registUser = (value) => {
    // particular API here
  };

  const debouncedOnChange = useCallback(debounce(registUser, 300), []);

  const handleChange = (e) => {
    setInputValue(e.target.value);
    debouncedOnChange(e.target.value);
  };

  return (
    <div>
      <input type="text" value={value} onChange={handleChange} />
    </div>
  );
}
</code>```

But I want to know. Should I use debounce if I simply set the status value in the change handler?

```<code>import React, { useState, useCallback } from 'react';
import { debounce } from 'lodash';

export default function App() {
  const [value, setValue] = useState('');

  const onChange = (value) => {
    setInputValue(e.target.value);
  };

  const debouncedOnChange = useCallback(debounce(onChange, 300), []);

  const handleChange = (e) => {
    debouncedOnChange(e.target.value);
  };

  return (
    <div>
      <input type="text" value={value} onChange={handleChange} />
    </div>
  );
}
</code>```

Title: Exact use cases of debounce in React

Body:
If an onChange event is invoked for each keyboard input and there is a logic inside the change handler that calls a particular API, we know that unnecessarily many calls are made, and we use debounce to resolve them.

import React, { useState, useCallback } from 'react';
import { debounce } from 'lodash';

export default function App() {
  const [value, setValue] = useState('');

  const registUser = (value) => {
    // particular API here
  };

  const debouncedOnChange = useCallback(debounce(registUser, 300), []);

  const handleChange = (e) => {
    setInputValue(e.target.value);
    debouncedOnChange(e.target.value);
  };

  return (

      <input type="text" value={value} onChange={handleChange} />

  );
}

But I want to know. Should I use debounce if I simply set the status value in the change handler?

import React, { useState, useCallback } from 'react';
import { debounce } from 'lodash';

export default function App() {
  const [value, setValue] = useState('');

  const onChange = (value) => {
    setInputValue(e.target.value);
  };

  const debouncedOnChange = useCallback(debounce(onChange, 300), []);

  const handleChange = (e) => {
    debouncedOnChange(e.target.value);
  };

  return (

      <input type="text" value={value} onChange={handleChange} />

  );
}


问:
Migrating from jersey 1.x o 2.x: error on ContainerResponse
I'm getting error below error after migrating from Jersey 1.x to 2.x

Cannot find the symbol method: getContainerResponseWritter   location: variable response of type ContainerResponse

My code is below:

public ContainerResponse filter(ContainerRequest request,
                                ContainerResponse response) {
    setId();
    response.setContainerResponseWriter(
            new Adapter(response.getContainerResponseWriter()));
    return response;
}
```


问:
Object Array can't be call into the loop or call to html
I try to call the object array but in the loop or html, the data not even out. I try to make auto table maker with data inside as well but it seems I can't figure it out the problem until now. I try console log there in some place the data out. How to solve this case so I can call my object array correctly?

const tableListStation = 'listStation-edrvsocket'

const AWS = require( 'aws-sdk' );
const nodemailer = require( 'nodemailer' );
const moment = require('moment')
const fs = require("fs");
const mustache = require("mustache");

const docClient = new AWS.DynamoDB.DocumentClient();

const params = {
  TableName : tableListStation
}

async function listItems(){
  try {
    console.log('========data scan=======');
    const data = await docClient.scan( params ).promise()
    const filter = data.Items.filter( ( item ) => !item.online && item.exp <= Math.floor( ( new Date( Date.now() ) ).getTime() / 1000.0 ) )
    console.log('data', data)

    if ( filter.length >= 1 ) {
      const scanning = fs.readFileSync(
        `./table.html`,
        "utf8")
      const to = 'email@gmail.com';
      const subject = 'Data!!!';
      const text = mustache.render(scanning, { ...data, ...filter })
      const send = await sendEmail( to, subject, text )
      console.log( 'send', send, 'data', data, 'h', data.Items );

      filter.map( item => {
        let putItemParams = {
          TableName: tableListStation,
          Item: {
            id: item.id,
            org: item.org,
            online: item.online,
            endpoint: item.endpoint,
            exp: Math.floor( ( new Date( Date.now() + 172800000 ) ).getTime() / 1000.0 ),
            updatedAt: momentGetDateJKT()
          }
        };
        console.log('item params', putItemParams)
        docClient.put( putItemParams, ( err, datadb ) => {
          if ( err ) {
            console.log('error push')
            return({ message: err.message });
          } else {
            console.log('oke', datadb)
            return data;
          }
        } );
      })
    }
    return data
  } catch (err) {
    return err
  }
}

function momentGetDateJKT() {
  //this return  date as GMT+07
  //adding 420 or 7 hours to AWS Server local time
  let date = new Date();
  let dateDisplay = moment(date).add(420, 'm').format('HH:mm:ss MM/DD/YYYY');
  return dateDisplay;
}

exports.handler = async (event, context) => {
  try {
    const data = await listItems()
    return { body: JSON.stringify(data) }
  } catch (err) {
    return { error: err }
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Charger Station Status</title>

    <style type="text/css">
      .tg {
        border-collapse: collapse;
        border-color: #9abad9;
        border-spacing: 0;
      }
      .tg td {
        background-color: #ebf5ff;
        border-color: #9abad9;
        border-style: solid;
        border-width: 1px;
        color: #444;
        font-family: Arial, sans-serif;
        font-size: 14px;
        overflow: hidden;
        padding: 10px 5px;
        word-break: normal;
      }
      .tg th {
        background-color: #409cff;
        border-color: #9abad9;
        border-style: solid;
        border-width: 1px;
        color: #fff;
        font-family: Arial, sans-serif;
        font-size: 14px;
        font-weight: normal;
        overflow: hidden;
        padding: 10px 5px;
        word-break: normal;
      }
      .tg .tg-yj5y {
        background-color: #efefef;
        border-color: inherit;
        text-align: center;
        vertical-align: top;
      }
      .tg .tg-baqh {
        text-align: center;
        vertical-align: top;
      }
      .tg .tg-jch0 {
        background-color: #9aff99;
        border-color: inherit;
        font-weight: bold;
        text-align: center;
        vertical-align: top;
      }
      .tg #status {
        border-color: inherit;
        text-align: left;
        vertical-align: top;
      }
      .red{
        background-color: red;
        color: blue;
      }
      .green{
        color: #409cff;
        background-color: green;
      }
      @media screen and (max-width: 767px) {
        .tg {
          width: auto !important;
        }
        .tg col {
          width: auto !important;
        }
        .tg-wrap {
          overflow-x: auto;
          -webkit-overflow-scrolling: touch;
        }
      }
    </style>
  </head>
  <body>
    <div class="tc-wrap" >
      <table class="tc" id="output">
      </table>
    </div>
  </body>
  <script src="index.js"></script>
  <!--<script src="script.js"></script>-->
</html></code>```

console.log('a',data);
console.log("b", data.Items);
// console.log("c", Items);
// console.log("d", item);
console.log('fg', filter);

let tableContent = ""
// let stats = document.getElementById("status")

function tables() {
    tableContent += `<thead><tr><th class="tg-jch0" colspan="5">` + data.Items[i].org + "

"

    + `<tr><td class="tg-yj5y">ID</td><td class="tg-yj5y">EndPoint</td><td class="tg-yj5y">Updated At</td><td class="tg-yj5y">Exp</td><td class="tg-yj5y">Status</td></tr></tbody>`
}

function tablesinfo() {
    tableContent +=

        `<tbody><tr><td class="tg-0pky">` + data.Items[j].id + "	"

        + `<td class="tg-0pky">` + data.Items[j].endpoint + "	"

        + `<td class="tg-0pky">` + data.Items[j].updatedAt + "	"

        + `<td class="tg-0pky">` + data.Items[j].exp + "	"

        + `<td id="status">` + data.Items[j].online + "
"
}

for (let i = 0; i < data.Items.length; i++) {
    if (i == 0) {
        tables()
        for (let j = 0; j < data.Items.length; j++) {
            if (data.Items[i].org == data.Items[j].org) {
                tablesinfo()
                // if (Items[j].status == "Offline") {
                //     stats[j].classList.add('red');
                // }
                // else {
                //     stats[j].classList.add('green');
                // }
            }
            else if (data.Items[i].org != data.Items[j].org) {
                j++
            }
        }
    }
    else if (data.Items[i].org != data.Items[i-1].org) {
        tables()
        for (let j = 0; j < data.Items.length; j++) {
            if (data.Items[i].org == data.Items[j].org) {
                tablesinfo()
                // if (Items[j].status == "Offline") {
                //     stats[j].classList.add('red');
                // }
                // else {
                //     stats[j].classList.add('green');
                // }
            }
            else if (data.Items[i].org != data.Items[j].org) {
                j++
            }
        }
    }
}

output.innerHTML = tableContent;```

This is the result i seek

Body:
I try to call the object array but in the loop or html, the data not even out. I try to make auto table maker with data inside as well but it seems I can't figure it out the problem until now. I try console log there in some place the data out. How to solve this case so I can call my object array correctly?

const tableListStation = 'listStation-edrvsocket'

const AWS = require( 'aws-sdk' );
const nodemailer = require( 'nodemailer' );
const moment = require('moment')
const fs = require("fs");
const mustache = require("mustache");

const docClient = new AWS.DynamoDB.DocumentClient();

const params = {
  TableName : tableListStation
}

async function listItems(){
  try {
    console.log('========data scan=======');
    const data = await docClient.scan( params ).promise()
    const filter = data.Items.filter( ( item ) => !item.online && item.exp <= Math.floor( ( new Date( Date.now() ) ).getTime() / 1000.0 ) )
    console.log('data', data)

    if ( filter.length >= 1 ) {
      const scanning = fs.readFileSync(
        `./table.html`,
        "utf8")
      const to = 'email@gmail.com';
      const subject = 'Data!!!';
      const text = mustache.render(scanning, { ...data, ...filter })
      const send = await sendEmail( to, subject, text )
      console.log( 'send', send, 'data', data, 'h', data.Items );

      filter.map( item => {
        let putItemParams = {
          TableName: tableListStation,
          Item: {
            id: item.id,
            org: item.org,
            online: item.online,
            endpoint: item.endpoint,
            exp: Math.floor( ( new Date( Date.now() + 172800000 ) ).getTime() / 1000.0 ),
            updatedAt: momentGetDateJKT()
          }
        };
        console.log('item params', putItemParams)
        docClient.put( putItemParams, ( err, datadb ) => {
          if ( err ) {
            console.log('error push')
            return({ message: err.message });
          } else {
            console.log('oke', datadb)
            return data;
          }
        } );
      })
    }
    return data
  } catch (err) {
    return err
  }
}

function momentGetDateJKT() {
  //this return  date as GMT+07
  //adding 420 or 7 hours to AWS Server local time
  let date = new Date();
  let dateDisplay = moment(date).add(420, 'm').format('HH:mm:ss MM/DD/YYYY');
  return dateDisplay;
}

exports.handler = async (event, context) => {
  try {
    const data = await listItems()
    return { body: JSON.stringify(data) }
  } catch (err) {
    return { error: err }
  }
}

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Charger Station Status</title>

console.log('a',data);
console.log("b", data.Items);
// console.log("c", Items);
// console.log("d", item);
console.log('fg', filter);

let tableContent = ""
// let stats = document.getElementById("status")

function tables() {
    tableContent += `<thead><tr><th class="tg-jch0" colspan="5">` + data.Items[i].org + "

"

    + `<tr><td class="tg-yj5y">ID</td><td class="tg-yj5y">EndPoint</td><td class="tg-yj5y">Updated At</td><td class="tg-yj5y">Exp</td><td class="tg-yj5y">Status</td></tr></tbody>`
}

function tablesinfo() {
    tableContent +=

        `<tbody><tr><td class="tg-0pky">` + data.Items[j].id + "	"

        + `<td class="tg-0pky">` + data.Items[j].endpoint + "	"

        + `<td class="tg-0pky">` + data.Items[j].updatedAt + "	"

        + `<td class="tg-0pky">` + data.Items[j].exp + "	"

        + `<td id="status">` + data.Items[j].online + "
"
}

for (let i = 0; i < data.Items.length; i++) {
    if (i == 0) {
        tables()
        for (let j = 0; j < data.Items.length; j++) {
            if (data.Items[i].org == data.Items[j].org) {
                tablesinfo()
                // if (Items[j].status == "Offline") {
                //     stats[j].classList.add('red');
                // }
                // else {
                //     stats[j].classList.add('green');
                // }
            }
            else if (data.Items[i].org != data.Items[j].org) {
                j++
            }
        }
    }
    else if (data.Items[i].org != data.Items[i-1].org) {
        tables()
        for (let j = 0; j < data.Items.length; j++) {
            if (data.Items[i].org == data.Items[j].org) {
                tablesinfo()
                // if (Items[j].status == "Offline") {
                //     stats[j].classList.add('red');
                // }
                // else {
                //     stats[j].classList.add('green');
                // }
            }
            else if (data.Items[i].org != data.Items[j].org) {
                j++
            }
        }
    }
}

output.innerHTML = tableContent;

This is the result i seek


问:
How to test route file in nodejs with jest which also contains controller inside it and having next function called if any error happens
```<code>router.get("/get-todos", async (req, res, next) => {
    try {
      const response = await getTodoController.getAllTodo()
      if (response?.error) return next(response?.error)
      res.json(response)
    } catch (error) {
      next(error)
    }
  })
</code>```

How to test the above code with all unit test cases will pass and all lines should be cover.

I tried but it's not covering the line with next function

```<code>describe("GET todo data", () => {
    it("should give all todo data with success code", async () => {
      const payload = {
        message: "Todo data fetched successfully",
        status: 200,
        data: [
          {
            id: 2,
            title: "Turkmenbashi Airport",
            description: "",
            createdAt: "2021-12-24T05:08:34.000Z",
          },
        ],
      }
      getTodoSpy.mockResolvedValue(payload as any)
      const resp = await request(app).get("/todos/get-todos").send().expect(200)
      expect(resp.body).toBeDefined
      expect(resp.error).not.toBeDefined
      expect(getTodoSpy).toHaveBeenCalled
    })
    it("should throw error if route not matched", async () => {
      getTodoSpy.mockRejectedValue(new Error("Controller error"))
      const resp = await request(app).get("/todos/get-todo").send().expect(404)
      expect(resp.body).not.toBeDefined
      expect(resp.error).toBeDefined
    })
  })
</code>```

Here above I need to test for next function, handle error.

Body:
router.get("/get-todos", async (req, res, next) => {
    try {
      const response = await getTodoController.getAllTodo()
      if (response?.error) return next(response?.error)
      res.json(response)
    } catch (error) {
      next(error)
    }
  })

How to test the above code with all unit test cases will pass and all lines should be cover.

I tried but it's not covering the line with next function

describe("GET todo data", () => {
    it("should give all todo data with success code", async () => {
      const payload = {
        message: "Todo data fetched successfully",
        status: 200,
        data: [
          {
            id: 2,
            title: "Turkmenbashi Airport",
            description: "",
            createdAt: "2021-12-24T05:08:34.000Z",
          },
        ],
      }
      getTodoSpy.mockResolvedValue(payload as any)
      const resp = await request(app).get("/todos/get-todos").send().expect(200)
      expect(resp.body).toBeDefined
      expect(resp.error).not.toBeDefined
      expect(getTodoSpy).toHaveBeenCalled
    })
    it("should throw error if route not matched", async () => {
      getTodoSpy.mockRejectedValue(new Error("Controller error"))
      const resp = await request(app).get("/todos/get-todo").send().expect(404)
      expect(resp.body).not.toBeDefined
      expect(resp.error).toBeDefined
    })
  })

Here above I need to test for next function, handle error.


问:
Add a sidecar container to open5GS NFs
I'm trying to add a sidecar container inside open5gs NFs. I want to modify the helm charts available here:
https://github.com/Gradiant/openverso-charts/tree/master/charts

I have created a sidecar container image. I want to run this image as a sidecar container in amf. How can I modify AMF's chart to add my sidecar container?

Title: Add a sidecar container to open5GS NFs


问:
OWIN overwriting all claims for user in basic OIDC config
OWIN keeps overwriting all claims for the logged in OIDC user after about 5 minutes.  I've created a minimum example below.  I'm setting a claim called id_token which holds the encoded JWT token so that I can send an IdTokenHint for redirection from IdentityServer4 (but that issue also affects B2C).  If you don't send an IdTokenHint both IdentityServer4 and B2c and others will refuse to redirect you to prevent a redirection attack.

The setup seems correct.  It redirects to the IdentitysServer4.  I can see the claims.  If I click the Logout button right away, the id_token will still be set, and the IdTokenHint works and IdentityServer4 redirects back to my application after sign out.

The problem comes if I wait for five minutes before clicking sign out. In that case, the only claim left is LOCAL AUTHORITY which I never set. I think that's going to be the biggest clue to what's going on.  I'm betting that triggers something in someone's mind right away.  I think it's probably trying to get a refresh token after five minutes and then overwriting all claims.  Maybe.  I have put breakpoints wherever I can, stubbing all of the notification events to set breakpoints, and none are raised before I physically click the Logout button, and then id_token is null (if I wait 5 minutes before click Logout).

On SecurityTokenValidated in Startup.cs I am setting the id_token.

```<code>SecurityTokenValidated = n =>
{
    n.AuthenticationTicket.Identity.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));
</code>```

I created a Logout button and an OIDC controller.  If before the 5 minutes, the first var instruction here, which does nothing, I can inspect and see the id_token.  After 5 minutes, id_token is null.  So I'm pretty sure this method itself isn't causing the issue.

```<code>public void SignOut()
{
    var owin = HttpContext.GetOwinContext(); // here all the claims are gone except for LOCAL AUTHORITY
    HttpContext.GetOwinContext().Authentication.SignOut(
        OpenIdConnectAuthenticationDefaults.AuthenticationType,
        CookieAuthenticationDefaults.AuthenticationType);
}
</code>```

Here's where I really need it, but after waiting 5 minutes and then clicking the Logout button id_token is null and LOCAL AUTHORITY is set:

```<code>RedirectToIdentityProvider = n =>
{
    if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.Logout)
    {
        var id_token_claim = n.OwinContext.Authentication.User.Claims.FirstOrDefault(x => x.Type == "id_token");
        if (id_token_claim != null)
        {
            n.ProtocolMessage.IdTokenHint = id_token_claim.Value;
</code>```

I created a minimal example and the code that I added is so small that this and the Logout button is the only changes I've made:

Startup.cs Startup.Configuration

```<code>public void Configuration(IAppBuilder app)
{
    Console.WriteLine(app.Properties);

    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = "Cookies"
    });

    app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
    {
        SaveTokens = true,
        ClientId = "mvc",
        Authority = "https://localhost:5001",
        RedirectUri = "https://localhost:44307/",
        PostLogoutRedirectUri = "https://localhost:44307/",
        UsePkce = true,
        RedeemCode = true,
        ClientSecret = "####",
        ResponseType = OpenIdConnectResponseType.CodeIdToken,
        Scope = "openid profile",
        SignInAsAuthenticationType = "Cookies",

        TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
        {
            NameClaimType = "name"
        },

        Notifications = new OpenIdConnectAuthenticationNotifications
        {
            SecurityTokenValidated = n =>
            {
                n.AuthenticationTicket.Identity.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));

                return Task.FromResult(0);
            },
            RedirectToIdentityProvider = n =>
            {
                if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.Logout)
                {
                    var id_token_claim = n.OwinContext.Authentication.User.Claims.FirstOrDefault(x => x.Type == "id_token");
                    if (id_token_claim != null)
                    {
                        n.ProtocolMessage.IdTokenHint = id_token_claim.Value;
                    }
                }

                return Task.FromResult(0);
            }
        }
    });
}
</code>```

Here's a tutorial of what I'm basically trying to do which is very similar to other questions on Stack and other documents that have got me this far.

Body:
OWIN keeps overwriting all claims for the logged in OIDC user after about 5 minutes.  I've created a minimum example below.  I'm setting a claim called id_token which holds the encoded JWT token so that I can send an IdTokenHint for redirection from IdentityServer4 (but that issue also affects B2C).  If you don't send an IdTokenHint both IdentityServer4 and B2c and others will refuse to redirect you to prevent a redirection attack.

The setup seems correct.  It redirects to the IdentitysServer4.  I can see the claims.  If I click the Logout button right away, the id_token will still be set, and the IdTokenHint works and IdentityServer4 redirects back to my application after sign out.

The problem comes if I wait for five minutes before clicking sign out. In that case, the only claim left is LOCAL AUTHORITY which I never set. I think that's going to be the biggest clue to what's going on.  I'm betting that triggers something in someone's mind right away.  I think it's probably trying to get a refresh token after five minutes and then overwriting all claims.  Maybe.  I have put breakpoints wherever I can, stubbing all of the notification events to set breakpoints, and none are raised before I physically click the Logout button, and then id_token is null (if I wait 5 minutes before click Logout).

On SecurityTokenValidated in Startup.cs I am setting the id_token.

SecurityTokenValidated = n =>
{
    n.AuthenticationTicket.Identity.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));

I created a Logout button and an OIDC controller.  If before the 5 minutes, the first var instruction here, which does nothing, I can inspect and see the id_token.  After 5 minutes, id_token is null.  So I'm pretty sure this method itself isn't causing the issue.

public void SignOut()
{
    var owin = HttpContext.GetOwinContext(); // here all the claims are gone except for LOCAL AUTHORITY
    HttpContext.GetOwinContext().Authentication.SignOut(
        OpenIdConnectAuthenticationDefaults.AuthenticationType,
        CookieAuthenticationDefaults.AuthenticationType);
}

Here's where I really need it, but after waiting 5 minutes and then clicking the Logout button id_token is null and LOCAL AUTHORITY is set:

RedirectToIdentityProvider = n =>
{
    if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.Logout)
    {
        var id_token_claim = n.OwinContext.Authentication.User.Claims.FirstOrDefault(x => x.Type == "id_token");
        if (id_token_claim != null)
        {
            n.ProtocolMessage.IdTokenHint = id_token_claim.Value;

I created a minimal example and the code that I added is so small that this and the Logout button is the only changes I've made:

Startup.cs Startup.Configuration

public void Configuration(IAppBuilder app)
{
    Console.WriteLine(app.Properties);

    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = "Cookies"
    });

    app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
    {
        SaveTokens = true,
        ClientId = "mvc",
        Authority = "https://localhost:5001",
        RedirectUri = "https://localhost:44307/",
        PostLogoutRedirectUri = "https://localhost:44307/",
        UsePkce = true,
        RedeemCode = true,
        ClientSecret = "####",
        ResponseType = OpenIdConnectResponseType.CodeIdToken,
        Scope = "openid profile",
        SignInAsAuthenticationType = "Cookies",

        TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
        {
            NameClaimType = "name"
        },

        Notifications = new OpenIdConnectAuthenticationNotifications
        {
            SecurityTokenValidated = n =>
            {
                n.AuthenticationTicket.Identity.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));

                return Task.FromResult(0);
            },
            RedirectToIdentityProvider = n =>
            {
                if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.Logout)
                {
                    var id_token_claim = n.OwinContext.Authentication.User.Claims.FirstOrDefault(x => x.Type == "id_token");
                    if (id_token_claim != null)
                    {
                        n.ProtocolMessage.IdTokenHint = id_token_claim.Value;
                    }
                }

                return Task.FromResult(0);
            }
        }
    });
}

Here's a tutorial of what I'm basically trying to do which is very similar to other questions on Stack and other documents that have got me this far.


问:
Alternative for sharing data deep through component hierarchy in Angular besides Input and Services
I'm writing an app in Angular 14.2 where I have a set of components in a hierarchy 4-layers deep. The hierarchy is shown in the image below.

The top of the hierarchy (Card Component) has all of the data needed by all of the hierarchy. I am currently passing the data through the hierarchy using attributes and Input. But something always rubs me the wrong way about that pattern.

I'm thinking about moving this to a service pattern, where I inject a service into each component so they have access to the data that way. This will feel better to me, but there will be multiple card components loaded at the same time, so I have to still pass some unique identifier through the hierarchy so that I can find the correct data for this instance in the service.

My question is, does someone have an alternate way to do this? It would be great if Angular assigned a unique id to each component instance that component children could access automatically, for example, so I don't have to pass a unique key down, but I don't think this is something Angular does. Another downside here is I'll have data in the service I need to destroy when it's no longer needed.


问:
<svg> cannot appear as a child of <option>
error i am getting
validateDOMNesting(...):  cannot appear as a child of .
at svg
at UilCircleenter code here

"I am using react-unicons library for icons and i tried to add it to the select tag but its is showing
"<svg> cannot appear as a child of <option>" error

I tried the icons with li and all it is working there, but in select tag of html it is showing this error and in option tag to it is showing the same error

This is the code
import * as Icon from '@iconscout/react-unicons';
                                                      <Icon.UilRotate360/>