问:
Python mock how to return different value of mock function based on arguments and number of calls
I am testing mock response for URL.

So question is :

I want the mock function return different value on different url, And for the same URL, the first time call and 2nd time call this URL, i also want to return different value.

Here is example:

if i do this:

```<code>url1 = "https://url1"
url2 = "https://url2"
</code>```
```<code>mock_get_http_response.side_effect = {url1: self.readjson('./res_url1_1.json')
                                      url2: self.readjson('./res_url2.json'),
                                      }.get
</code>```

When i call

```<code>get_http_response(url1), it returns res_url1_1.json
</code>```

which is great.

Now  i want to call get_http _response(url1) 2 times.

First time i expect it return res_url1 _1.json,

2nd time i call get_http _response(url1) I expect it return another json response.

i have tried:

```<code>mock_get_http_response.side_effect = {url1: [self.readjson('./res_url1_1.json'), self.readjson('./res_url1_2.json')]
                                      url2: self.readjson('./res_url2.json'),
                                      }.get
</code>```

Not working

```<code>mock_get_http_response.side_effect = {url1: next([self.readjson('./res_url1_1.json'), self.readjson('./res_url1_2.json')])
                                      url2: self.readjson('./res_url2.json'),
                                      }.get
</code>```

Not working either, it only calls next(iterator) once, so it always return  res_url1 _1.json

also tried:

```<code>mock_response = MagicMock()
mock_response.side_effect = [self.readjson('./res_url1_1.json'), self.readjson('./res_url1_2.json')]
mock_get_http_response.side_effect = {url1: mock_response
                                      url2: self.readjson('./res_url2.json'),
                                      }.get
</code>```

Not working, it makes get_http _response(url1) return a magicMock ojbect instead of json response

```<code>self.readjson('./res_url1_1.json')
</code>```

Expect:
Now i want to call get_http _response(url1) 2 times.

First time i expect it return res_url1 _1.json,

2nd time if i call get_http _response(url1) I expect it return another json response res_url1_2.json

And if i call get_http _response(url2), i expect always return res_url2.json response

Body:
I am testing mock response for URL.

So question is :

I want the mock function return different value on different url, And for the same URL, the first time call and 2nd time call this URL, i also want to return different value.

Here is example:

if i do this:

url1 = "https://url1"
url2 = "https://url2"

mock_get_http_response.side_effect = {url1: self.readjson('./res_url1_1.json')
                                      url2: self.readjson('./res_url2.json'),
                                      }.get

When i call

get_http_response(url1), it returns res_url1_1.json

which is great.

Now  i want to call get_http _response(url1) 2 times.

First time i expect it return res_url1 _1.json,

2nd time i call get_http _response(url1) I expect it return another json response.

i have tried:

mock_get_http_response.side_effect = {url1: [self.readjson('./res_url1_1.json'), self.readjson('./res_url1_2.json')]
                                      url2: self.readjson('./res_url2.json'),
                                      }.get

Not working

mock_get_http_response.side_effect = {url1: next([self.readjson('./res_url1_1.json'), self.readjson('./res_url1_2.json')])
                                      url2: self.readjson('./res_url2.json'),
                                      }.get

Not working either, it only calls next(iterator) once, so it always return  res_url1 _1.json

also tried:

mock_response = MagicMock()
mock_response.side_effect = [self.readjson('./res_url1_1.json'), self.readjson('./res_url1_2.json')]
mock_get_http_response.side_effect = {url1: mock_response
                                      url2: self.readjson('./res_url2.json'),
                                      }.get

Not working, it makes get_http _response(url1) return a magicMock ojbect instead of json response

self.readjson('./res_url1_1.json')

Expect:
Now i want to call get_http _response(url1) 2 times.

First time i expect it return res_url1 _1.json,

2nd time if i call get_http _response(url1) I expect it return another json response res_url1_2.json

And if i call get_http _response(url2), i expect always return res_url2.json response


来源: stackexchange

问:
How to use update data shown in antD table using Vue 3?
I recently started using Vue 3 and am still trying to understand ref(). I created a table and a toggle button to show items with status: "active". Initially, I see the table with all the data. When I clicked on the toggle, button itself works and I see the console logs showing an updated data form a total of 8 to 6:

```<code>toggle clicked ~ data:
Proxy {0: {…}, 1: {…}, 2: {…}, 3: {…}, 4: {…}, 5: {…}}
[[Handler]]
:
Object
[[Target]]
:
Array(6)
</code>```

However, the table itself does not update when the toggle is clicked. Am I using ref() incorrectly here? Should I be using computed to display the data on the table?

```<code>  setup(props) {
 // props.data = [
 //     { id: 0, status: 'active' },
 //     { id: 1, status: 'closed' },
 //     { id: 2, status: 'active' },
 //     { id: 3, status: 'active' },
 //     { id: 4, status: 'active' },
 //     { id: 5, status: 'active' },
 //     { id: 6, status: 'closed' },
 //     { id: 7, status: 'active' },
 //    ]
 //
    const tableData = Vue.ref(props.data || [])
    const toggleActive = Vue.ref(false)

    const tableColumn= [
      {
        title: 'ID',
        dataIndex: 'id',
        key: 'id',
        sorter: true
      },
      {
        title: 'Status',
        dataIndex: 'status',
        key: 'status',
        sorter: true
      }
    ]

    const onToggleActive = () => {
       if (!toggleActive.value) {
         tableData.value = data.filter((item) => item.status === "active");
       }
       else {
         tableData.value = data;
       }
    }

    return {
      tableData: tableData.value,
      tableColumn,
      onToggleActive,
      toggleActive
    }
  },

  template: `
    <div>
      <div class="tableHeader">
        <a-switch class="toggleTable" @change="onToggleActive" v-model:checked="toggleActive" />
      </div>
      <a-table
        :locale="{ emptyText: 'No Data Found' }"
        :columns="tableColumn"
        :data-source="tableData"
        :pagination="false"
        size="middle"
      >
        <template #bodyCell="{ column, text, record }">
            {{text}}
        </template>
      </a-table>
    </div>
  `
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I recently started using Vue 3 and am still trying to understand ref(). I created a table and a toggle button to show items with status: "active". Initially, I see the table with all the data. When I clicked on the toggle, button itself works and I see the console logs showing an updated data form a total of 8 to 6:

toggle clicked ~ data:
Proxy {0: {…}, 1: {…}, 2: {…}, 3: {…}, 4: {…}, 5: {…}}
[[Handler]]
:
Object
[[Target]]
:
Array(6)

However, the table itself does not update when the toggle is clicked. Am I using ref() incorrectly here? Should I be using computed to display the data on the table?

  setup(props) {
 // props.data = [
 //     { id: 0, status: 'active' },
 //     { id: 1, status: 'closed' },
 //     { id: 2, status: 'active' },
 //     { id: 3, status: 'active' },
 //     { id: 4, status: 'active' },
 //     { id: 5, status: 'active' },
 //     { id: 6, status: 'closed' },
 //     { id: 7, status: 'active' },
 //    ]
 //
    const tableData = Vue.ref(props.data || [])
    const toggleActive = Vue.ref(false)

    const tableColumn= [
      {
        title: 'ID',
        dataIndex: 'id',
        key: 'id',
        sorter: true
      },
      {
        title: 'Status',
        dataIndex: 'status',
        key: 'status',
        sorter: true
      }
    ]

    const onToggleActive = () => {
       if (!toggleActive.value) {
         tableData.value = data.filter((item) => item.status === "active");
       }
       else {
         tableData.value = data;
       }
    }

    return {
      tableData: tableData.value,
      tableColumn,
      onToggleActive,
      toggleActive
    }
  },

  template: `

        <template #bodyCell="{ column, text, record }">
            {{text}}
        </template>

  `


问:
Is Halide possible for debugging in AOT (ahead of time) compilation?
I am wondering is Halide even possible for debugging in AOT compilation? I saw the Halide tutorials but it seems debugging like print, print_when is only possible under JIT compilation. I am now having a generate() {...} function to get the static library and I want to debug it. How can I do this? I tried putting "print", "print_when" inside the generate() function but nothing printed out?  Any knows how to debug Halide with AOT compilation? Thanks!

I tried putting the "print" in generator but nothing printed out.


问:
Hibernate CascadeType.PERSIST for non null key [parent key not found]
I have these two Entities:

```<code>@SequenceGenerator(...)
@Entity
class A {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "....")
    private Integer id;

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
    @JoinColumns({
        @JoinColumn(name = "aaa", referencedColumnName = "aaa"),
        @JoinColumn(name = "bbb", referencedColumnName = "bbb"),
        @JoinColumn(name = "ccc", referencedColumnName = "ccc"),
        @JoinColumn(name = "ddd", referencedColumnName = "ddd"),
    })
    private B b;

    // ... getters and setters
}
</code>```
```<code>@Entity
class B {
    @EmbeddedId
    private BPk id;

    // ... getters and setters
}
</code>```
```<code>@Embeddable
class BPk {
    private Integer aaa;
    private Integer bbb;
    private Integer ccc;
    private Integer ddd;

    // ... getters and setters
}
</code>```

In my case I have non persisted B object, which values from columns "aaa", "bbb", "ccc", "ddd" are populated.

If I try to persist the new A object and when B doesn't exist in database the hibernate don't make the insert of B entity throwing the following error:

integrity constraint ([FK NAME]) violated - parent key not found

I think it's happening because my B object has the non null PK so hibernate didn't make the insert thinking that B entity exists. How can I fix this?

I have found the following solution for spring boot (example: 54), but it doesn't work for CascadeType.PERSIST. By the way, it was what I noticed.

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.entity-persistence.saving-entites.

I would like something that when I persist the A entity also persist a new B entity if it's a new row in database.

Body:
I have these two Entities:

@SequenceGenerator(...)
@Entity
class A {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "....")
    private Integer id;

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
    @JoinColumns({
        @JoinColumn(name = "aaa", referencedColumnName = "aaa"),
        @JoinColumn(name = "bbb", referencedColumnName = "bbb"),
        @JoinColumn(name = "ccc", referencedColumnName = "ccc"),
        @JoinColumn(name = "ddd", referencedColumnName = "ddd"),
    })
    private B b;

    // ... getters and setters
}

@Entity
class B {
    @EmbeddedId
    private BPk id;

    // ... getters and setters
}

@Embeddable
class BPk {
    private Integer aaa;
    private Integer bbb;
    private Integer ccc;
    private Integer ddd;

    // ... getters and setters
}

In my case I have non persisted B object, which values from columns "aaa", "bbb", "ccc", "ddd" are populated.

If I try to persist the new A object and when B doesn't exist in database the hibernate don't make the insert of B entity throwing the following error:

integrity constraint ([FK NAME]) violated - parent key not found

I think it's happening because my B object has the non null PK so hibernate didn't make the insert thinking that B entity exists. How can I fix this?

I have found the following solution for spring boot (example: 54), but it doesn't work for CascadeType.PERSIST. By the way, it was what I noticed.

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.entity-persistence.saving-entites.

I would like something that when I persist the A entity also persist a new B entity if it's a new row in database.


问:
Server-Sent Events occasionally become malformed when sent in rapid succession
I've written a very basic game in .NET 7 that relies on server-sent events. I've noticed that my event content is occasionally malformed. From what I can tell this happens during small periods of time in which there are several updates in quick succession.

Below is an example - notice the Data for the highlighted record is malformed. In another instance that I did not screenshot, the data was fine, but the event type was lobbyevent:lobbyEvent instead of simply lobbyEvent.

I have to imagine that, somehow, the ResponseBody is not being properly flushed, and/or being "cross-contaminated" due to concurrent requests. The logging in the following code tells me that it's all working as expected up to the point where it sends response data. Furthermore, the problem seems worse out in the wild, as opposed to my localhost where it's much more difficult to replicate - this would seem to align with the idea that slower response times are causing concurrency issues.

My code is below, which was built following the patterns outlined here. Can anyone help me out? Am I correct in my assumption, and what can I do to remedy the issue?

[Produces("text/event-stream")]
[HttpGet("{code}/listen")]
public async Task ListenForNotifications(string code, CancellationToken cancellationToken)
{
    _logger.LogCritical($"CONNECTED");
    var lobby = await _dbContext.Lobbies.FirstOrDefaultAsync(l => l.JoinCode == code);
    if (lobby == null) return;

    SetServerSentEventHeaders();
    await Response.WriteAsync($"event:connected\n", cancellationToken);
    await Response.Body.FlushAsync(cancellationToken);

    async void OnNotification(object? sender, LobbyEventArgs eventArgs)
    {
        try
        {
            if (eventArgs.LobbyEvent.LobbyId != lobby.Id) return;
            var json = JsonSerializer.Serialize(eventArgs.LobbyEvent, _jsonSerializerOptions);
            await Response.WriteAsync("retry:10000\n", cancellationToken);
            await Response.WriteAsync($"event:lobbyEvent\n", cancellationToken);
            await Response.WriteAsync($"data:{json}\n\n", cancellationToken);
            await Response.Body.FlushAsync(cancellationToken);
            _logger.LogCritical($"NOTIFICATION SENT: {eventArgs.LobbyEvent.Type}");
        } catch (Exception ex)
        {
            _logger.LogCritical($"NOTIFICATION FAILED: {ex.Message}");
        }
    }

    async void KeepAlive(object? sender, EventArgs eventArgs)
    {
        await Response.WriteAsync("event:keep-alive\n", cancellationToken);
        await Response.WriteAsync("data:keep-alive\n\n", cancellationToken);
        await Response.Body.FlushAsync(cancellationToken);
    }

    _eventService.LobbyEvent += OnNotification;
    _eventService.KeepAlive += KeepAlive;

    try
    {
        while (!cancellationToken.IsCancellationRequested)
            await Task.Delay(1000, cancellationToken);
    }
    finally
    {
        _logger.LogCritical($"DISCONNECTED");
        _eventService.LobbyEvent -= OnNotification;
        _eventService.KeepAlive -= KeepAlive;
    }
}

private void SetServerSentEventHeaders()
{
    Response.StatusCode = 200;
    Response.Headers.Add("Content-Type", "text/event-stream");
    Response.Headers.Add("Cache-Control", "no-cache");
    Response.Headers.Add("Connection", "keep-alive");
}
```


问:
*** pyarrow.lib.ArrowInvalid: CSV parse error: Empty CSV file or block: cannot infer number of columns
Trying the new pyarrow, this gives error:

```<code>data= pd.read_csv(path,sep='\t',engine="pyarrow")

*** pyarrow.lib.ArrowInvalid: CSV parse error: Empty CSV file or block: cannot infer number of columns
</code>```

But this works:

```<code>data= pd.read_csv(path,sep='\t')
</code>```

Body:
Trying the new pyarrow, this gives error:

data= pd.read_csv(path,sep='\t',engine="pyarrow")

*** pyarrow.lib.ArrowInvalid: CSV parse error: Empty CSV file or block: cannot infer number of columns

But this works:

data= pd.read_csv(path,sep='\t')


问:
How to Import webpage with only the data I need?
I'm new to google sheets and trying to import data from a website to my spreadsheet. The website URL is

https://sagarin.usatoday.com/2023-2/college-basketball-team-ratings-2022-23

I've managed to import some data, but it's not in a format I can use. I want to import the Team name and the 5 power rankings for each team, so I can add the 5 rankings together and come up with a total. When I managed to import the data it includes the team's win lose record in the same cell as the power ranking, which makes it unusable because I can't simply add the power rankings.

Below is the function I'm using to import the data

```<code>=IMPORTXML("https://sagarin.usatoday.com/2023-2/college-basketball-team-ratings-2022-23/","/html/body/div/div/div/div/div/div/pre/font/font/font/font")
</code>```

Any idea how I can get just the team names and the 5 separate power rankings associated with each team?

I've tried numerous times with different functions, but the following is the closest I've come to getting what I want. I only wanted the team names and the 5 power rankings associated with each team. What I got was team names and power rankings, but it also included numbers for win loses and other stats in the same cells, which I don't want.

```<code>=IMPORTXML("https://sagarin.usatoday.com/2023-2/college-basketball-team-ratings-2022-23/","/html/body/div/div/div/div/div/div/pre/font/font/font/font")
</code>```

Body:
I'm new to google sheets and trying to import data from a website to my spreadsheet. The website URL is

https://sagarin.usatoday.com/2023-2/college-basketball-team-ratings-2022-23

I've managed to import some data, but it's not in a format I can use. I want to import the Team name and the 5 power rankings for each team, so I can add the 5 rankings together and come up with a total. When I managed to import the data it includes the team's win lose record in the same cell as the power ranking, which makes it unusable because I can't simply add the power rankings.

Below is the function I'm using to import the data

=IMPORTXML("https://sagarin.usatoday.com/2023-2/college-basketball-team-ratings-2022-23/","/html/body/div/div/div/div/div/div/pre/font/font/font/font")

Any idea how I can get just the team names and the 5 separate power rankings associated with each team?

I've tried numerous times with different functions, but the following is the closest I've come to getting what I want. I only wanted the team names and the 5 power rankings associated with each team. What I got was team names and power rankings, but it also included numbers for win loses and other stats in the same cells, which I don't want.

=IMPORTXML("https://sagarin.usatoday.com/2023-2/college-basketball-team-ratings-2022-23/","/html/body/div/div/div/div/div/div/pre/font/font/font/font")


问:
ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type int). How o rectify this type of error in python?
My training data size and testing data size is ((80000, 77, 1), (8000, 77, 1))
training and testing data shape
fit the data into CNN model during implementation am getting value error

tried to fit my data to CNN model during the training process am getting value error as
ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type int).

I tried using these commands still error occurs as:
x_train = np.asarray(x_train).astype(np.float32)
y_train = np.asarray(y_train).astype(np.float32)

ValueError: could not convert string to float: '10.152.152.11-50.23.134.226-41711-80-6'


问:
NSInternalInconsistencyException - Animator is already stopped
Currently getting the following runtime exception

```<code>libc++abi: terminating with uncaught exception of type NSException
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Animator <UIViewPropertyAnimator(0x600003f24200) [stopped] interruptible> is already stopped!'
</code>```

Because of the following line of code

```<code>// other code up here that modifies offsetAnimator
...

// stop any current running animations on offset
if let offsetAnimator = offsetAnimator {
    offsetAnimator.stopAnimation(false) // this line is where the exception gets raised
    offsetAnimator.finishAnimation(at: .end)
}
</code>```

What is perplexing, however, is why this error is NOT readily reproducible

```<code>// doing this doesn't always result in an error
if let offsetAnimator = offsetAnimator {
    offsetAnimator.stopAnimation(false)
    offsetAnimator.finishAnimation(at: .end)

    offsetAnimator.stopAnimation(false)
    offsetAnimator.finishAnimation(at: .end)
}
</code>```

What on earth is happening? Can someone explain to me why this error is occurring?

Why does it seem to only happen sporadically? Shouldn't calling .stop twice always trigger it?

Body:
Currently getting the following runtime exception

libc++abi: terminating with uncaught exception of type NSException
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Animator <UIViewPropertyAnimator(0x600003f24200) [stopped] interruptible> is already stopped!'

Because of the following line of code

// other code up here that modifies offsetAnimator
...

// stop any current running animations on offset
if let offsetAnimator = offsetAnimator {
    offsetAnimator.stopAnimation(false) // this line is where the exception gets raised
    offsetAnimator.finishAnimation(at: .end)
}

What is perplexing, however, is why this error is NOT readily reproducible

// doing this doesn't always result in an error
if let offsetAnimator = offsetAnimator {
    offsetAnimator.stopAnimation(false)
    offsetAnimator.finishAnimation(at: .end)

    offsetAnimator.stopAnimation(false)
    offsetAnimator.finishAnimation(at: .end)
}

What on earth is happening? Can someone explain to me why this error is occurring?

Why does it seem to only happen sporadically? Shouldn't calling .stop twice always trigger it?


问:
npm watch doesn't trigger browser-sync reloading
I'm trying to create an npm scripts configuration that compiles scss and uses browser-sync to reload the browser when files are written to the css directory.

The scss compilation works.

However, after the css is rewritten, browser-sync is not reloading the browser.

My package.json:

```<code>{
        "name": "bob",
        "version": "0.1.0",
        "description": "testing",
        "watch": {
                "sass": {
                        "patterns": [
                                "./src/sass"
                        ],
                        "extensions": "scss"
                },

                "bsReload": {
                        "patterns": [
                                "./src/css"
                        ],
                        "extensions": "css"
                }
        },
        "scripts": {
                "dev": "concurrently  \"npm run watch\"   \"npm run bs\"   ",
                "bs": "browser-sync start  --proxy \"http://mylocalsite.localdev\"   ",
                "bsReload": "browser-sync reload",
                "watch": "npm-watch",
                "serve": "http-server dist",
                "sass": "sass --style=compressed  ./src/sass/main.scss   ./css/main.css"
        },
        "author": "Bob",
        "license": "ISC",
        "devDependencies": {
               ...
        }
}
</code>```

Body:
I'm trying to create an npm scripts configuration that compiles scss and uses browser-sync to reload the browser when files are written to the css directory.

The scss compilation works.

However, after the css is rewritten, browser-sync is not reloading the browser.

My package.json:

{
        "name": "bob",
        "version": "0.1.0",
        "description": "testing",
        "watch": {
                "sass": {
                        "patterns": [
                                "./src/sass"
                        ],
                        "extensions": "scss"
                },

                "bsReload": {
                        "patterns": [
                                "./src/css"
                        ],
                        "extensions": "css"
                }
        },
        "scripts": {
                "dev": "concurrently  \"npm run watch\"   \"npm run bs\"   ",
                "bs": "browser-sync start  --proxy \"http://mylocalsite.localdev\"   ",
                "bsReload": "browser-sync reload",
                "watch": "npm-watch",
                "serve": "http-server dist",
                "sass": "sass --style=compressed  ./src/sass/main.scss   ./css/main.css"
        },
        "author": "Bob",
        "license": "ISC",
        "devDependencies": {
               ...
        }
}


问:
Does my code have a memory leak for connection?
In this case, I didn't close the s3 client.
Is it problem as code below?
For example, for every single request, client object still remains in the memory if I didn't close it?</p>


问:
Why can't I use Three JS to rotate a mesh if I used a vertex shader to set gl_Position?
I have a bunch of points mapped to a disc and I want to make them rotate about the origin of the scene. I have tried to make the points rotate using the standard approach:

```<code><mesh ref={mesh}>

..

  useFrame((state) => {
    const { clock } = state;

    gPoints.current.material.uniforms.uTime.value = clock.elapsedTime;

    mesh.current.rotation.y += 0.01;

  });
</code>```

However it does not rotate anything. I pass along predetermined starting coordinates to the vertex shader as a uniform,

```<code>const vertexShader = `
uniform float uTime;
uniform float uDistance[1000];
uniform float uPointSizes[1000];

varying vec3 vColor;
varying float vDistance;
varying vec4 vRealPosition;

void main() {

  float minPointSize = 1.0;
  float maxPointSize = 10.0;

  vDistance = distance(position, vec3(0.0));

  vColor = mix(vec3(100.0/255.0, 15.0/255.0, 0.0), vec3(200.0/255.0, 50.0/255.0, 100.0/255.0), vDistance/20.0);

  float pointSize = uPointSizes[gl_VertexID];

  // Do Not Touch
  gl_Position = projectionMatrix * viewMatrix * vec4( position, 1.0 );
  gl_PointSize = pointSize;
  vRealPosition = gl_Position;
}

`

export default vertexShader
</code>```

Alternatively I have tried getting the points to rotate about the origin inside the vertex shader but I can't get it to work

Body:
I have a bunch of points mapped to a disc and I want to make them rotate about the origin of the scene. I have tried to make the points rotate using the standard approach:

<mesh ref={mesh}>

..

  useFrame((state) => {
    const { clock } = state;

    gPoints.current.material.uniforms.uTime.value = clock.elapsedTime;

    mesh.current.rotation.y += 0.01;

  });

However it does not rotate anything. I pass along predetermined starting coordinates to the vertex shader as a uniform,

const vertexShader = `
uniform float uTime;
uniform float uDistance[1000];
uniform float uPointSizes[1000];

varying vec3 vColor;
varying float vDistance;
varying vec4 vRealPosition;

void main() {

  float minPointSize = 1.0;
  float maxPointSize = 10.0;

  vDistance = distance(position, vec3(0.0));

  vColor = mix(vec3(100.0/255.0, 15.0/255.0, 0.0), vec3(200.0/255.0, 50.0/255.0, 100.0/255.0), vDistance/20.0);

  float pointSize = uPointSizes[gl_VertexID];

  // Do Not Touch
  gl_Position = projectionMatrix * viewMatrix * vec4( position, 1.0 );
  gl_PointSize = pointSize;
  vRealPosition = gl_Position;
}

`

export default vertexShader

Alternatively I have tried getting the points to rotate about the origin inside the vertex shader but I can't get it to work


问:
Adding CIFilters to selfie camera feed from ARSCNView
I'm setting up my ARScene using this code which works perfectly. I'm then trying to apply a CIFilter to the selfie camera feed and set it back in real time. The only way I can access the camera feed data is through the -session didUpdateFrame method (I think?) but when I apply the filter and set it back the feed is just pure white as if I set the background.contents = [UIColor White], which I did not.

```<code>self.sceneView = [[ARSCNView alloc] initWithFrame:self.view.frame];
self.sceneView.delegate = self;
self.sceneView.showsStatistics = NO;
[self.view addSubview:self.sceneView];

SCNScene *scene = [SCNScene new];
self.sceneView.scene = scene;

ARFaceTrackingConfiguration *facetrack = [[ARFaceTrackingConfiguration alloc] init];
[self.sceneView.session runWithConfiguration:facetrack];

self.sceneView.session.delegate = self;

- (void)session:(ARSession *)session didUpdateFrame:(ARFrame *)frame {

    CIImage *beginImage = [CIImage imageWithCVPixelBuffer: frame.capturedImage ];

    CIFilter *filter = [CIFilter filterWithName:@"CIComicEffect" keysAndValues: kCIInputImageKey, beginImage, nil];

    CIImage *outputImage = [[filter outputImage] imageByCroppingToRect:beginImage.extent];
    UIImage *sat_img = [UIImage imageWithCIImage:outputImage];

    self.sceneView.scene.background.contents = sat_img;

}
</code>```

Is this even possible?

Body:
I'm setting up my ARScene using this code which works perfectly. I'm then trying to apply a CIFilter to the selfie camera feed and set it back in real time. The only way I can access the camera feed data is through the -session didUpdateFrame method (I think?) but when I apply the filter and set it back the feed is just pure white as if I set the background.contents = [UIColor White], which I did not.

self.sceneView = [[ARSCNView alloc] initWithFrame:self.view.frame];
self.sceneView.delegate = self;
self.sceneView.showsStatistics = NO;
[self.view addSubview:self.sceneView];

SCNScene *scene = [SCNScene new];
self.sceneView.scene = scene;

ARFaceTrackingConfiguration *facetrack = [[ARFaceTrackingConfiguration alloc] init];
[self.sceneView.session runWithConfiguration:facetrack];

self.sceneView.session.delegate = self;

- (void)session:(ARSession *)session didUpdateFrame:(ARFrame *)frame {

    CIImage *beginImage = [CIImage imageWithCVPixelBuffer: frame.capturedImage ];

    CIFilter *filter = [CIFilter filterWithName:@"CIComicEffect" keysAndValues: kCIInputImageKey, beginImage, nil];

    CIImage *outputImage = [[filter outputImage] imageByCroppingToRect:beginImage.extent];
    UIImage *sat_img = [UIImage imageWithCIImage:outputImage];

    self.sceneView.scene.background.contents = sat_img;

}

Is this even possible?


Title: Retrieve next row in pandas dataframe / multiple list comprehension outputs

Body:
I have a Pandas dataframe, wt, with a datetime index and three columns as well as dataframe t with the same datetime index and three other columns below:

wt

date    0   1   2
2004-11-19  0.2 0.3 0.5
2004-11-22  0.0 0.0 0.0
2004-11-23  0.0 0.0 0.0
2004-11-24  0.0 0.0 0.0
2004-11-26  0.0 0.0 0.0
2004-11-29  0.0 0.0 0.0
2004-11-30  0.0 0.0 0.0

t

date    GLD SPY TLT
2004-11-19  0.009013068949977443    -0.011116725618999457   -0.007980218051028332
2004-11-22  0.0037963376507370583   0.004769204564810003    0.005211874008610895
2004-11-23  -0.00444938820912133    0.0015256823190370472   0.0012398557258792575
2004-11-24  0.006703910614525022    0.0023696682464455776   0.0
2004-11-26  0.005327413984461682    -0.0007598784194529085  -0.00652932567826181
2004-11-29  0.002428792227864962    -0.004562737642585524   -0.010651558073654366
2004-11-30  -0.006167400881057272   0.0006790595025889523   -0.004237773450922022
2004-12-01  0.005762411347517871    0.011366528119433505    -0.0015527950310557648

I'm currently using the Pandas iterrrows method to run through each row for processing, and as a first step, I check if the row entries are non-zero, as below:

for dt, row in t.iterrows():
    if sum(wt.loc[dt]) <= 0:
        ...

Based on this, I'd like to assign values to dataframe wt if non-zero values don't currently exist.  How can I retrieve the next row for a given dt entry (eg, '11/22/2004' for dt = '11/19/2004')?

Part 2

As an addendum, I'm setting this up using a for loop for testing but would like to use list comprehension once complete.  Processing will return the wt dataframe described above, as well as an intermediate, secondary dataframe again with datetime index and a single column (sample below):

r

date    r
2004-11-19  0.030202
2004-11-22  -0.01047
2004-11-23  0.002456
2004-11-24  -0.01274
2004-11-26  0.00928

Is there a way to use list comprehensions to return both the above wt and this r dataframes without simply creating two separate comprehensions?

Edit

I was able to get desired results by changing my approach, so adding for clarification (referenced dataframes are as described above).  Wonder if there's any way to apply list comprehensions for this.

r = pd.DataFrame(columns=['ret'],index=wt.index.copy())
dts = wt.reset_index().date

for i, dt in enumerate(dts):

    row = t.loc[dt]
    dt_1 = dts.shift(-1).iloc[i]

    try:
       wt.loc[dt_1] = ((wt.loc[dt].tolist() * (1+row)).transpose() / np.dot(wt.loc[dt].tolist(), (1+row))).tolist()
       r.loc[dt] = np.dot(wt.loc[dt], row)

    except:
        print(f'Error calculating for date {dt}')
        continue


问:
Stress test all CPU cores to 100% utilization with THREAD_PRIORITY_TIME_CRITICAL stops Windows from handling ctr+alt+delete?
Trying to create a C program to stress test all CPU cores to 100% utilization.
However, it works too well such that I have to reboot Windows 11 because everything is unresponsive, even Ctrl + Alt + Delete.

Ctrl+Alt+Delete is a Windows function, baked into the OS. So no matter
how frozen a program may be as long as the OS is still working it will
detect that key combo and override everything else.

Why doesn't the Windows 11 OS detect Ctrl + Alt + Delete and allow the stress test program to be terminated?

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

DWORD WINAPI consume_cpu(LPVOID arg)
{
    while (1) {}
    return 0;
}

int main(int argc, char** argv)
{
    // Get the number of CPU cores
    SYSTEM_INFO sysinfo;
    GetSystemInfo(&sysinfo);
    int num_cores = sysinfo.dwNumberOfProcessors;

    HANDLE* threads = (HANDLE*)malloc(num_cores * sizeof(HANDLE));

    // Create one thread per CPU core
    for (int i = 0; i < num_cores; i++)
    {
        threads[i] = CreateThread(NULL, 0, consume_cpu, NULL, 0, NULL);
        SetThreadPriority(threads[i], THREAD_PRIORITY_TIME_CRITICAL);
    }

    // Wait for the threads to finish
    WaitForMultipleObjects(num_cores, threads, TRUE, INFINITE);

    free(threads);
    return 0;
}
</code>```

Notes

As suggested in the comments, removing THREAD_PRIORITY_TIME_CRITICAL
allows for 100% CPU utilization plus the OS is now responsive.

Body:
Trying to create a C program to stress test all CPU cores to 100% utilization.
However, it works too well such that I have to reboot Windows 11 because everything is unresponsive, even Ctrl + Alt + Delete.

Ctrl+Alt+Delete is a Windows function, baked into the OS. So no matter
how frozen a program may be as long as the OS is still working it will
detect that key combo and override everything else.

Why doesn't the Windows 11 OS detect Ctrl + Alt + Delete and allow the stress test program to be terminated?

#include <windows.h>
#include <stdio.h>

DWORD WINAPI consume_cpu(LPVOID arg)
{
    while (1) {}
    return 0;
}

int main(int argc, char** argv)
{
    // Get the number of CPU cores
    SYSTEM_INFO sysinfo;
    GetSystemInfo(&sysinfo);
    int num_cores = sysinfo.dwNumberOfProcessors;

    HANDLE* threads = (HANDLE*)malloc(num_cores * sizeof(HANDLE));

    // Create one thread per CPU core
    for (int i = 0; i < num_cores; i++)
    {
        threads[i] = CreateThread(NULL, 0, consume_cpu, NULL, 0, NULL);
        SetThreadPriority(threads[i], THREAD_PRIORITY_TIME_CRITICAL);
    }

    // Wait for the threads to finish
    WaitForMultipleObjects(num_cores, threads, TRUE, INFINITE);

    free(threads);
    return 0;
}

Notes

As suggested in the comments, removing THREAD_PRIORITY_TIME_CRITICAL
allows for 100% CPU utilization plus the OS is now responsive.


问:
why is stop-loss and take-profit not working?
I am pretty new to pinescript. Although my code runs, changing the values of my stop loss percent and take profit percent does not have any bearing on the outcome. while examining the outcome of a backtest, my losses in trades exceed the stop loss percent. any insight would be helpful, as I am at a loss.

```<code>//@version=4

//define the strategy
strategy("Long-Only Momentum Strategy")

//set the lookback period
lookback = 365

//calculate the momentum
momentum = close - close[lookback]

//calculate the RSI
rsiValue = rsi(close, 14)

//set the entry rule
entry = momentum > 0 and rsiValue < 80

//set the stop loss percentage
stopLossPercent = 2

//set the take profit percentage
takeProfitPercent = 5

//calculate the stop loss price
stopLossPrice = close * (1 - stopLossPercent/100)

//calculate the take profit price
takeProfitPrice = close * (1 + takeProfitPercent/100)

//enter a long position when the entry rule is triggered
if entry
strategy.entry("Long", strategy.long)

//exit the long position when the stop loss is triggered
if close < stopLossPrice
strategy.close("Long")

//exit the long position when the take profit is triggered
if close > takeProfitPrice
strategy.close("Long")

//exit the long position when the exit rule is triggered
if close < sma(close,200)
strategy.close("Long")
</code>```

I tried rewriting the stoploss and take profit various ways, with the same result

Body:
I am pretty new to pinescript. Although my code runs, changing the values of my stop loss percent and take profit percent does not have any bearing on the outcome. while examining the outcome of a backtest, my losses in trades exceed the stop loss percent. any insight would be helpful, as I am at a loss.

//@version=4

//define the strategy
strategy("Long-Only Momentum Strategy")

//set the lookback period
lookback = 365

//calculate the momentum
momentum = close - close[lookback]

//calculate the RSI
rsiValue = rsi(close, 14)

//set the entry rule
entry = momentum > 0 and rsiValue < 80

//set the stop loss percentage
stopLossPercent = 2

//set the take profit percentage
takeProfitPercent = 5

//calculate the stop loss price
stopLossPrice = close * (1 - stopLossPercent/100)

//calculate the take profit price
takeProfitPrice = close * (1 + takeProfitPercent/100)

//enter a long position when the entry rule is triggered
if entry
strategy.entry("Long", strategy.long)

//exit the long position when the stop loss is triggered
if close < stopLossPrice
strategy.close("Long")

//exit the long position when the take profit is triggered
if close > takeProfitPrice
strategy.close("Long")

//exit the long position when the exit rule is triggered
if close < sma(close,200)
strategy.close("Long")

I tried rewriting the stoploss and take profit various ways, with the same result


问:
Facebook Open Graph - Link post without title and description with big size of image
can someone explain how to do this:

Link post without title and description with big size of image
Its some custom code or?

Thanks.

Im trying to get link post on facebook like on photo, without link title and link description


问:
remove repeated users from rank with group by
I am trying to rank from a table users. This table contains a log of all results. I already can rank the elements depending on the result ASC, but I have repeated users ID that I want to group by but I can't.

```<code>ID_competitionLog   ID_event    ID_athlete  result  wind    rank
4                        19                2            49.12   NULL     1
6                        19                11           49.56   NULL     2
13                       19                1            50.12   NULL     4
17                       4                 1            49.8    NULL     3
</code>```
```<code>SELECT *, FIND_IN_SET( result, ( SELECT GROUP_CONCAT( result ORDER BY result ASC )
FROM competitionlog where (ID_event = 19 or ID_event = 4) and (result <> 0.0125 and result <> 0.00125 and result <> 0.000125))) AS rank
FROM competitionlog where (ID_event = 19 or ID_event = 4) and (result <> 0.0125 and result <> 0.00125 and result <> 0.000125);
</code>```

I try to group by the repeated users and get only theirs best result to compare in the ranking

Body:
I am trying to rank from a table users. This table contains a log of all results. I already can rank the elements depending on the result ASC, but I have repeated users ID that I want to group by but I can't.

ID_competitionLog   ID_event    ID_athlete  result  wind    rank
4                        19                2            49.12   NULL     1
6                        19                11           49.56   NULL     2
13                       19                1            50.12   NULL     4
17                       4                 1            49.8    NULL     3

SELECT *, FIND_IN_SET( result, ( SELECT GROUP_CONCAT( result ORDER BY result ASC )
FROM competitionlog where (ID_event = 19 or ID_event = 4) and (result <> 0.0125 and result <> 0.00125 and result <> 0.000125))) AS rank
FROM competitionlog where (ID_event = 19 or ID_event = 4) and (result <> 0.0125 and result <> 0.00125 and result <> 0.000125);

I try to group by the repeated users and get only theirs best result to compare in the ranking


问:
Sphinx typehinting shows full path to classes ant not links
I am currently working on a python project and want to automatically generate the documentation for my project

In order to automatically generate my documentation, I do:

```<code> sphinx-apidoc -f -o source ../modules
 make html
</code>```

But When I try to generate documentation via sphinx, the typehints are not shown properly, instead the full path to the class is shown:

In intelj it works perfectly fine though, here is the code:

from src.ConfiguratorOSMData.model import CalculationPhase, ConfigurationManager

class CalculationManager:
    """
    The CalculationManager manages Calculation of the Project.
    """

    def __init__(self, starting_point: CalculationPhase, configuration_manager: ConfigurationManager):
        """
        Gets called when we first create an object of this class, it saves all information it needs for
        starting a calculation.

        Args:
            starting_point: Describes in which calculation-phase we want to start the calculation.
            configuration_manager: Saves all information required to configure the calculation.
        """
        pass

    def cancel_calculation(self):
        """
        This method is used when we want to cancel an ongoing calculation.
        """
        pass

    def _validate_starting_point(self) -> bool:
        """
        Validates the correctness of the Staring Point.

        Returns:
            bool: If true then the starting_point is valid, this means every calculation up to this point exist
            and are saved in the project.
        """
        pass

    def _start_calculation(self):
        """
        Starts the calculation.
        """
        pass

```
<p>I already added:</p>
```autodoc_typehints = "description"
add_module_names = False
```
<p>and</p>
```extensions = [
    "sphinx.ext.autodoc",
    "sphinx.ext.autosummary",
    'sphinx.ext.napoleon', # support for google docstring style
    "sphinx_autodoc_typehints"
]
```

to the conf.py.
Can somebody help me, what am I doing wrong?

Body:
I am currently working on a python project and want to automatically generate the documentation for my project

In order to automatically generate my documentation, I do:

 sphinx-apidoc -f -o source ../modules
 make html

But When I try to generate documentation via sphinx, the typehints are not shown properly, instead the full path to the class is shown:

In intelj it works perfectly fine though, here is the code:

from src.ConfiguratorOSMData.model import CalculationPhase, ConfigurationManager

class CalculationManager:
    """
    The CalculationManager manages Calculation of the Project.
    """

    def __init__(self, starting_point: CalculationPhase, configuration_manager: ConfigurationManager):
        """
        Gets called when we first create an object of this class, it saves all information it needs for
        starting a calculation.

        Args:
            starting_point: Describes in which calculation-phase we want to start the calculation.
            configuration_manager: Saves all information required to configure the calculation.
        """
        pass

    def cancel_calculation(self):
        """
        This method is used when we want to cancel an ongoing calculation.
        """
        pass

    def _validate_starting_point(self) -> bool:
        """
        Validates the correctness of the Staring Point.

        Returns:
            bool: If true then the starting_point is valid, this means every calculation up to this point exist
            and are saved in the project.
        """
        pass

    def _start_calculation(self):
        """
        Starts the calculation.
        """
        pass

I already added:

autodoc_typehints = "description"
add_module_names = False

and

extensions = [
    "sphinx.ext.autodoc",
    "sphinx.ext.autosummary",
    'sphinx.ext.napoleon', # support for google docstring style
    "sphinx_autodoc_typehints"
]

to the conf.py.
Can somebody help me, what am I doing wrong?


问:
Spark shell error while running num executors. YARN application has exited unexpectedly with state FAILED
I have just installed spark-3.3.1 and am trying to run the num executors but the job is getting failed.

I am doing it for the first time. I am unable to identify the cause of job failure here.

```<code>adminn@master:~$ spark-shell --master yarn --num-executors 1

Setting default log level to "WARN".
To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel).
23/01/07 07:13:36 WARN NativeCodeLoader: Unable to load native-hadoop library for your latform... using builtin-java classes where applicable
23/01/07 07:13:40 WARN Client: Neither spark.yarn.jars nor spark.yarn.archive is set, falling back to uploading libraries under SPARK_HOME.
Spark context Web UI available at http://localhost:4040
Spark context available as 'sc' (master = yarn, app id = application_1673055142624_0003).
Spark session available as 'spark'.
23/01/07 07:14:17 ERROR YarnClientSchedulerBackend: YARN application has exited unexpectedly with state FAILED! Check the YARN application logs for more details.
23/01/07 07:14:17 ERROR YarnClientSchedulerBackend: Diagnostics message: Uncaught exception: org.apache.spark.SparkException: Exception thrown in awaitResult:
    at org.apache.spark.util.ThreadUtils$.awaitResult(ThreadUtils.scala:301)
    at org.apache.spark.rpc.RpcTimeout.awaitResult(RpcTimeout.scala:75)
    at org.apache.spark.rpc.RpcEnv.setupEndpointRefByURI(RpcEnv.scala:102)
    at org.apache.spark.rpc.RpcEnv.setupEndpointRef(RpcEnv.scala:110)
    at org.apache.spark.deploy.yarn.ApplicationMaster.runExecutorLauncher(ApplicationMaster.scala:558)
    at org.apache.spark.deploy.yarn.ApplicationMaster.run(ApplicationMaster.scala:277)
    at org.apache.spark.deploy.yarn.ApplicationMaster$$anon$3.run(ApplicationMaster.scala:926)
    at org.apache.spark.deploy.yarn.ApplicationMaster$$anon$3.run(ApplicationMaster.scala:925)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.secrrity.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1878)
    at org.apache.spark.deploy.yarn.ApplicationMaster$.main(ApplicationMaster.scala:925)
    at org.apache.spark.deploy.yarn.ExecutorLauncher$.main(ApplicationMaster.scala:957)
    at org.apache.spark.deploy.yarn.ExecutorLauncher.main(ApplicationMaster.scala)
Caused by: java.io.IOException: Failed to connect to localhost/127.0.0.1:34213
    at org.apache.spark.network.client.TransportClientFactory.createClient(TransportClientFactory.java:288)
    at org.apache.spark.network.client.TransportClientFactory.createClient(TransportClientFactory.java:218)
    at org.apache.spark.network.client.TransportClientFactory.createClient(TransportClientFactory.java:230)
    at org.apache.spark.rpc.netty.NettyRpcEnv.createClient(NettyRpcEnv.scala:204)
    at org.apache.spark.rpc.netty.Outbox$$anon$1.call(Outbox.scala:202)
    at org.apache.spark.rpc.netty.Outbox$$anon$1.call(Outbox.scala:198)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:750)
Caused by: io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: localhost/127.0.0.1:34213
Caused by: java.net.ConnectException: Connection refused
    at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
    at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:716)
    at io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:330)
    at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:334)
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:710)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:658)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:584)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:496)
    at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:986)
    at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
    at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
    at java.lang.Thread.run(Thread.java:750)
23/01/07 07:14:17 WARN YarnSchedulerBackend$YarnSchedulerEndpoint: Attempted to send shutdown message before the AM has registered!
23/01/07 07:14:17 WARN YarnSchedulerBackend$YarnSchedulerEndpoint: Attempted to request executors before the AM has registered!

Welcome to
      ____              __
     / __/__  ___ _____/ /__
    _\ \/ _ \/ _ `/ __/  '_/
   /___/ .__/\_,_/_/ /_/\_\   version 3.3.1
      /_/

Using Scala version 2.12.15 (OpenJDK 64-Bit Server VM, Java 1.8.0_352)
Type in expressions to have them evaluated.
Type :help for more information.
scala>
</code>```

Body:
I have just installed spark-3.3.1 and am trying to run the num executors but the job is getting failed.

I am doing it for the first time. I am unable to identify the cause of job failure here.

adminn@master:~$ spark-shell --master yarn --num-executors 1

Setting default log level to "WARN".
To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel).
23/01/07 07:13:36 WARN NativeCodeLoader: Unable to load native-hadoop library for your latform... using builtin-java classes where applicable
23/01/07 07:13:40 WARN Client: Neither spark.yarn.jars nor spark.yarn.archive is set, falling back to uploading libraries under SPARK_HOME.
Spark context Web UI available at http://localhost:4040
Spark context available as 'sc' (master = yarn, app id = application_1673055142624_0003).
Spark session available as 'spark'.
23/01/07 07:14:17 ERROR YarnClientSchedulerBackend: YARN application has exited unexpectedly with state FAILED! Check the YARN application logs for more details.
23/01/07 07:14:17 ERROR YarnClientSchedulerBackend: Diagnostics message: Uncaught exception: org.apache.spark.SparkException: Exception thrown in awaitResult:
    at org.apache.spark.util.ThreadUtils$.awaitResult(ThreadUtils.scala:301)
    at org.apache.spark.rpc.RpcTimeout.awaitResult(RpcTimeout.scala:75)
    at org.apache.spark.rpc.RpcEnv.setupEndpointRefByURI(RpcEnv.scala:102)
    at org.apache.spark.rpc.RpcEnv.setupEndpointRef(RpcEnv.scala:110)
    at org.apache.spark.deploy.yarn.ApplicationMaster.runExecutorLauncher(ApplicationMaster.scala:558)
    at org.apache.spark.deploy.yarn.ApplicationMaster.run(ApplicationMaster.scala:277)
    at org.apache.spark.deploy.yarn.ApplicationMaster$$anon$3.run(ApplicationMaster.scala:926)
    at org.apache.spark.deploy.yarn.ApplicationMaster$$anon$3.run(ApplicationMaster.scala:925)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.secrrity.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1878)
    at org.apache.spark.deploy.yarn.ApplicationMaster$.main(ApplicationMaster.scala:925)
    at org.apache.spark.deploy.yarn.ExecutorLauncher$.main(ApplicationMaster.scala:957)
    at org.apache.spark.deploy.yarn.ExecutorLauncher.main(ApplicationMaster.scala)
Caused by: java.io.IOException: Failed to connect to localhost/127.0.0.1:34213
    at org.apache.spark.network.client.TransportClientFactory.createClient(TransportClientFactory.java:288)
    at org.apache.spark.network.client.TransportClientFactory.createClient(TransportClientFactory.java:218)
    at org.apache.spark.network.client.TransportClientFactory.createClient(TransportClientFactory.java:230)
    at org.apache.spark.rpc.netty.NettyRpcEnv.createClient(NettyRpcEnv.scala:204)
    at org.apache.spark.rpc.netty.Outbox$$anon$1.call(Outbox.scala:202)
    at org.apache.spark.rpc.netty.Outbox$$anon$1.call(Outbox.scala:198)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:750)
Caused by: io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: localhost/127.0.0.1:34213
Caused by: java.net.ConnectException: Connection refused
    at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
    at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:716)
    at io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:330)
    at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:334)
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:710)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:658)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:584)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:496)
    at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:986)
    at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
    at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
    at java.lang.Thread.run(Thread.java:750)
23/01/07 07:14:17 WARN YarnSchedulerBackend$YarnSchedulerEndpoint: Attempted to send shutdown message before the AM has registered!
23/01/07 07:14:17 WARN YarnSchedulerBackend$YarnSchedulerEndpoint: Attempted to request executors before the AM has registered!

Welcome to
      ____              __
     / __/__  ___ _____/ /__
    _\ \/ _ \/ _ `/ __/  '_/
   /___/ .__/\_,_/_/ /_/\_\   version 3.3.1
      /_/

Using Scala version 2.12.15 (OpenJDK 64-Bit Server VM, Java 1.8.0_352)
Type in expressions to have them evaluated.
Type :help for more information.
scala>


问:
JQTouch execute javascript when External page is loaded with Ajax
I'm using the built in JQtouch method of loading an external php page like this:

```<code><li class="arrow"><a href="get_products.php?eId='.$classCode_id.'&sName='.$sectionName.'">'.$sectionName.'</a> </li>
</code>```

This is working great. However I need to have some javascript run when get_product.php loads. I tried including it in the php page itself but it doesn't get executed.

Any ideas?

ContentLicense: CC BY-SA 3.0

Body:
I'm using the built in JQtouch method of loading an external php page like this:

'.$sectionName.'

This is working great. However I need to have some javascript run when get_product.php loads. I tried including it in the php page itself but it doesn't get executed.

Any ideas?


问:
ema5 ema21 ta lib not matching with tradingview
I tried below code

import yfinance as yf
import pandas_ta as ta

dfpl = yf.download('TCS.NS',start='2023-01-01',end='2023-01-05',interval='15m')

dfpl["EMA5"] = ta.ema(dfpl["Close"],5)
dfpl["EMA21"] = ta.ema(dfpl["Close"],21)

print(dfpl[20:])

It gave me these values

enter image description here

Tradingview values

enter image description here

Tradinview settings

enter image description here

What wrong I'm doing here ?


问:
Typescript "spread" interface in function call
I want to type some inputs of a function using an interface, is there a way to "spread" the interface to avoid passing an object in the function call?

interface GreetInputs {
    name: string;
    age: number;
}

const greet = ({ name, age }: GreetInputs) => {
    return `Hello ${name}, you are ${age} years old!`;
};

// this is annoying to pass as object
greet({name: 'Jack', age: 25})

const greet2 = (name: string, age: number) => {
    return `Hello ${name}, you are ${age} years old!`;
};

// this is nicer to call but inputs are not typed with GreetInputs
greet2('Jack', 25)
```
<p>Ideally I would have something like</p>
<pre class="lang-js prettyprint-override"><code>const greet3 = (...args: GreetInputs) => {
    return `Hello ${name}, you are ${age} years old!`;
};

// this is easy to call and inputs are typed with GreetInputs
greet3('Jack', 25)
</code>```

Body:
I want to type some inputs of a function using an interface, is there a way to "spread" the interface to avoid passing an object in the function call?

interface GreetInputs {
    name: string;
    age: number;
}

const greet = ({ name, age }: GreetInputs) => {
    return `Hello ${name}, you are ${age} years old!`;
};

// this is annoying to pass as object
greet({name: 'Jack', age: 25})

const greet2 = (name: string, age: number) => {
    return `Hello ${name}, you are ${age} years old!`;
};

// this is nicer to call but inputs are not typed with GreetInputs
greet2('Jack', 25)

Ideally I would have something like

const greet3 = (...args: GreetInputs) => {
    return `Hello ${name}, you are ${age} years old!`;
};

// this is easy to call and inputs are typed with GreetInputs
greet3('Jack', 25)


问:
Define a reference variable name in yaml list items
I am trying to define a reference variable name inside yaml list, and when i call the list item in the robotframework, the defined reference variable name should be replaced with the value in robot script.

```<code>${var}=  "Robot"

FOR  ${items}  IN  @{yaml_list}
    Log  ${items}
END
</code>```

Variables.yaml

```<code>yaml_list:
  - "My name is  ${var}"

</code>```

Expecting Logged Result -   My name is Robot

Body:
I am trying to define a reference variable name inside yaml list, and when i call the list item in the robotframework, the defined reference variable name should be replaced with the value in robot script.

${var}=  "Robot"

FOR  ${items}  IN  @{yaml_list}
    Log  ${items}
END

Variables.yaml

yaml_list:
  - "My name is  ${var}"

Expecting Logged Result -   My name is Robot


问:
If I close mover.io site does the file transfer process still runs in background?
I am using mover.io to copy all my google drive content (around 5 Tera and 200,000 files) to OneDrive.
I am using Microsoft mover.io.
The process is running now, but I anticipate that the copy process will take around one week.

The question is: if I log out of mover.io and switch off the computer, will the copy process in background still, so I can log in later?

I don't want to experiment now in the middle of the copying process.


问:
Calling members roles
I have this code:

guild.members.cache.filter(members => members.roles.cache.get('role_id'))

However, it only returns undefined!

Title: Calling members roles


问:
File i/o parsing in c giving garbage characters at end of string
I'm trying to parse my opengl .shader files into a string in c using the file i/o functions. For some reason, when the file size gets big enough (past 447 bytes exactly for some reason) there are garbage characters at the end of the string, preventing the shader from being compiled.

I've been trying to fix this all day and can't seem to figure out why it doesn't work.

There is another question similar to this: similar question
but I tried everything suggested and nothing worked

Here's the code:

```<code>static char* FileToString(const char* filePath)
{
    FILE* source = fopen(filePath, "r");
    if(source == NULL)
    {
        printf("Failed to open file!\n");
        return NULL;
    }

    char* buffer = 0;
    int length = 0;
    fseek(source, 0, SEEK_END);
    length = ftell(source);
    rewind(source);

    printf("Length: %d\n", length);
    buffer = (char*)malloc(length);

    if(buffer)
    {
        fread(buffer, 1, length, source);
    }

    fclose(source);

    return buffer;
}

shader ParseShader(const char* filePath)
{
    char* buffer = FileToString(filePath);

    //printf("%s\n", buffer);

    char *vertex = buffer + sizeof("#shader vertex") - 1;
    char *fragment = strstr(vertex, "#shader fragment");
    *fragment = '\0';
    fragment += sizeof("#shader fragment") - 1;

    //printf("VERTEX: \n %s", vertex);
    printf("FRAGMENT: \n %s", fragment);

    shader program = {vertex, fragment};

    return program;

}
</code>```

And here is the shader file:

```<code>#shader vertex
#version 330 core
layout(location = 0) in vec4 position;
layout(location = 1) in vec3 colors;
layout(location = 2) in vec2 texCoords;
out vec4 f_Color;
out vec2 f_texCoords;
void main()
{
    gl_Position = position;
    f_Color = vec4(colors, 1.0);
    f_texCoords = texCoords;
}

#shader fragment
#version 330 core
in vec2 f_texCoords;
in vec4 f_Color;
out vec4 color;
uniform sampler2D containerTexture;
void main()
{
    color = f_Color;
}
</code>```

I've tried making the last character '\0', setting the mode to rb, cutting off parts of the string, etc. but none of it worked

Body:
I'm trying to parse my opengl .shader files into a string in c using the file i/o functions. For some reason, when the file size gets big enough (past 447 bytes exactly for some reason) there are garbage characters at the end of the string, preventing the shader from being compiled.

I've been trying to fix this all day and can't seem to figure out why it doesn't work.

There is another question similar to this: similar question
but I tried everything suggested and nothing worked

Here's the code:

static char* FileToString(const char* filePath)
{
    FILE* source = fopen(filePath, "r");
    if(source == NULL)
    {
        printf("Failed to open file!\n");
        return NULL;
    }

    char* buffer = 0;
    int length = 0;
    fseek(source, 0, SEEK_END);
    length = ftell(source);
    rewind(source);

    printf("Length: %d\n", length);
    buffer = (char*)malloc(length);

    if(buffer)
    {
        fread(buffer, 1, length, source);
    }

    fclose(source);

    return buffer;
}

shader ParseShader(const char* filePath)
{
    char* buffer = FileToString(filePath);

    //printf("%s\n", buffer);

    char *vertex = buffer + sizeof("#shader vertex") - 1;
    char *fragment = strstr(vertex, "#shader fragment");
    *fragment = '\0';
    fragment += sizeof("#shader fragment") - 1;

    //printf("VERTEX: \n %s", vertex);
    printf("FRAGMENT: \n %s", fragment);

    shader program = {vertex, fragment};

    return program;

}

And here is the shader file:

#shader vertex
#version 330 core
layout(location = 0) in vec4 position;
layout(location = 1) in vec3 colors;
layout(location = 2) in vec2 texCoords;
out vec4 f_Color;
out vec2 f_texCoords;
void main()
{
    gl_Position = position;
    f_Color = vec4(colors, 1.0);
    f_texCoords = texCoords;
}

#shader fragment
#version 330 core
in vec2 f_texCoords;
in vec4 f_Color;
out vec4 color;
uniform sampler2D containerTexture;
void main()
{
    color = f_Color;
}

I've tried making the last character '\0', setting the mode to rb, cutting off parts of the string, etc. but none of it worked


问:
Validation code for Jquery datepicker when checking out
I have implemented a Jquery Datepicker on our site, but the customer can proceed to check out without choosing a date. can someone help me with a code?

should be like:
when the customer presses 'checkout' there should be an error that says 'please choose a date'.

this is the code in the snippet so far.

```<code>{{ '//code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css' | stylesheet_tag }}
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js" defer="defer"></script>

<div style="width:300px; clear:both;">
  <p>
    <label for="date">Kies uw bezorgdag:</label>
    <input id="date" type="text" name="datepicker" id="datepicker" readonly="readonly" value="{{ cart.attributes.date }}" />
    <span style="display:block" class="instructions"> Uw bestelling wordt in de avond tussen 17:30-22:00u bezorgd.</span>
  </p>
</div>

<script>
  if (window.jQuery) {
  let $ = window.jQuery;

  $(function() {
    // Dates to exclude
    var excludeDays = ['2021-09-04', '2021-09-12'];

    function disableSpecificDate(date) {
      // To disable specific day
      var dateArr = [String(date.getFullYear()), String(date.getMonth() + 1), String(date.getDate())];
      if (dateArr[1].length == 1) dateArr[1] = "0" + dateArr[1];
      if (dateArr[2].length == 1) dateArr[2] = "0" + dateArr[2];
      return excludeDays.indexOf(dateArr.join("-")) == -1;
    }
    $("#date").datepicker({
      dateFormat: 'dd/mm/yy',
      minDate: +1,
      maxDate: '+1M',
      beforeShow: function() {
        // To exclude next business day after 12 PM
        if (new Date().getHours() >= 12) {
          $(this).datepicker("option", "minDate", +2);
        }
      },
      beforeShowDay: function(date) {
        var day = date.getDay();
        return [((day == 0 || day == 2 |day == 3 || day == 5 || day == 6) ? false : disableSpecificDate(date)), ''];
      }
    });
  });
</code>```

i have searched on stack overflow but couldnt find anything.

Body:
I have implemented a Jquery Datepicker on our site, but the customer can proceed to check out without choosing a date. can someone help me with a code?

should be like:
when the customer presses 'checkout' there should be an error that says 'please choose a date'.

this is the code in the snippet so far.

{{ '//code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css' | stylesheet_tag }}

    Kies uw bezorgdag:
    <input id="date" type="text" name="datepicker" id="datepicker" readonly="readonly" value="{{ cart.attributes.date }}" />
     Uw bestelling wordt in de avond tussen 17:30-22:00u bezorgd.


问:
How to extract subcollections from documentsnapshots of firestore
I am working on a project on flutter where I am getting snapshots of documents by

```<code>final snapshot = FirebaseFirestore.instance.collection('revisableFlashcards').snapshots(),
</code>```

I want to know how I can extract my subcollections from the snapshot and get documents in subcollection from the firstsnapshot.

I have tried some way by which I am getting collection

```<code>CollectionReference subjects=db.collection('revisableFlashcards').doc('MBBS')
   .collection('First');
QuerySnapshot snapshot = await subjects.get();
</code>```

Body:
I am working on a project on flutter where I am getting snapshots of documents by

final snapshot = FirebaseFirestore.instance.collection('revisableFlashcards').snapshots(),

I want to know how I can extract my subcollections from the snapshot and get documents in subcollection from the firstsnapshot.

I have tried some way by which I am getting collection

CollectionReference subjects=db.collection('revisableFlashcards').doc('MBBS')
   .collection('First');
QuerySnapshot snapshot = await subjects.get();


问:
My Node server crash as soon as my N-API object called a function
I am building an online browser game where I used Node.js as the server backend and socket.io to handle all the networking connections. However, for the game backend itself, I actually write it in C++ and used node-addon-api to wrap around that backend. I do this because:

I think that the C++ game backend will be a little bit faster than a JS game backend. Plus, this is also the language I used in my work.

I want to leave the possibility of building the server in C++ in the future. Having the backend code in C++ would make the transition more seemless in the future.

The server.js code currently looks like the following.

```<code>// Server code
const express = require('express')
const app = express()
const PORT = process.env.PORT || 3000;
app.use(express.static('public'));

const http = require('http').Server(app);
const io = require("socket.io")(http, {
  cors: {
    origin: "*",
  }
});

app.get('/', (req, res) => res.sendFile(__dirname + '/index.html'));
http.listen(PORT, function() {
    console.log(`Listening on ${PORT}`)
})

io.on('connection', connected);

// Move data
class MoveData {
  constructor(playerId, x, y) {
    this.playerId = playerId;
    this.x = x;
    this.y = y;
  }
}

// Backend initialization
const game_wrapper = require('./build/Release/game_wrapper.node')
var gameInstance = new game_wrapper.GameWrapper(4.3);
gameInstance.AddNewPlayer("aloha");
gameInstance.RemovePlayer("aloha");

var playerCreations = [];
var playerDestructions = [];
var playerMoves = []
var objectPositions = {};

function connected(socket) {
  socket.on('newPlayer', data => {
    console.log("New player coming at id " + socket.id);
    playerCreations.push(socket.id);
  });

  socket.on('disconnect', () => {
    playerDestructions.push(socket.id);

    delete objectPositions[socket.id];
    io.emit('updatePlayers', objectPositions);
  });

  socket.on('move', moveData => {
    playerMoves.push(
      new MoveData(socket.id, moveData.x, moveData.y)
    );
  });
}

// Server loop
var lastTime = Date.now();
function serverLoop() {
  // Player update
  for (let playerId in playerCreations) {
    gameInstance.AddNewPlayer(playerId);
  }
  playerCreations = [];
  for (let playerId in playerDestructions) {
    gameInstance.RemovePlayer(playerId);
  }
  playerDestructions = [];
  for (let moveData in playerMoves) {
    gameInstance.Move(moveData.playerId, moveData.x, moveData.y);
  }
  playerMoves = [];

  // Game update
  currTime = Date.now();
  timeDelta = (currTime - lastTime) / 1000;
  gameInstance.Update(timeDelta);
  for (let playerId in objectPositions) {
    let point_array = gameInstance.GetPlayerPosition(playerId);
    objectPositions[playerId] = { x: point_array[0], y: point_array[1]};
  }
  console.log("Before");
  io.emit('updatePlayers', objectPositions);
  console.log("After");
  lastTime = currTime;
}
setInterval(serverLoop, 1000/60);
</code>```

Here, the game_wrapper comes from the Node C++ addon. I created a gameInstance from the library, which creates an instance of the game. New player can join in by connecting to the server, which triggers a creation of a new player in the game backend, identified by the socket ID.

When I called AddNewPlayer and RemovePlayer outside, they seem to work fine. However, when I called AddNewPlayer inside the serverLoop, the server either crashed immediately, or eventually crashed.

Does anyone have a suggestion of what is going on? I am suspecting that the serverLoop is actually a callback function that spawns a new thread. This creates some memory management issue if gameInstance does not handle memory properly, causing crashes. However, I would love to hear from node.js expert or socket.io expert here. Happy to provide further code to help debug this issue. Thanks!

I tried several things such as constructing the function the different way, or changing the way the function works on the backend. But I still have the same issues. It seems that Node Addon C++ doesn't like any object where memory might be dynamically allocated.

Body:
I am building an online browser game where I used Node.js as the server backend and socket.io to handle all the networking connections. However, for the game backend itself, I actually write it in C++ and used node-addon-api to wrap around that backend. I do this because:

I think that the C++ game backend will be a little bit faster than a JS game backend. Plus, this is also the language I used in my work.

I want to leave the possibility of building the server in C++ in the future. Having the backend code in C++ would make the transition more seemless in the future.

The server.js code currently looks like the following.

// Server code
const express = require('express')
const app = express()
const PORT = process.env.PORT || 3000;
app.use(express.static('public'));

const http = require('http').Server(app);
const io = require("socket.io")(http, {
  cors: {
    origin: "*",
  }
});

app.get('/', (req, res) => res.sendFile(__dirname + '/index.html'));
http.listen(PORT, function() {
    console.log(`Listening on ${PORT}`)
})

io.on('connection', connected);

// Move data
class MoveData {
  constructor(playerId, x, y) {
    this.playerId = playerId;
    this.x = x;
    this.y = y;
  }
}

// Backend initialization
const game_wrapper = require('./build/Release/game_wrapper.node')
var gameInstance = new game_wrapper.GameWrapper(4.3);
gameInstance.AddNewPlayer("aloha");
gameInstance.RemovePlayer("aloha");

var playerCreations = [];
var playerDestructions = [];
var playerMoves = []
var objectPositions = {};

function connected(socket) {
  socket.on('newPlayer', data => {
    console.log("New player coming at id " + socket.id);
    playerCreations.push(socket.id);
  });

  socket.on('disconnect', () => {
    playerDestructions.push(socket.id);

    delete objectPositions[socket.id];
    io.emit('updatePlayers', objectPositions);
  });

  socket.on('move', moveData => {
    playerMoves.push(
      new MoveData(socket.id, moveData.x, moveData.y)
    );
  });
}

// Server loop
var lastTime = Date.now();
function serverLoop() {
  // Player update
  for (let playerId in playerCreations) {
    gameInstance.AddNewPlayer(playerId);
  }
  playerCreations = [];
  for (let playerId in playerDestructions) {
    gameInstance.RemovePlayer(playerId);
  }
  playerDestructions = [];
  for (let moveData in playerMoves) {
    gameInstance.Move(moveData.playerId, moveData.x, moveData.y);
  }
  playerMoves = [];

  // Game update
  currTime = Date.now();
  timeDelta = (currTime - lastTime) / 1000;
  gameInstance.Update(timeDelta);
  for (let playerId in objectPositions) {
    let point_array = gameInstance.GetPlayerPosition(playerId);
    objectPositions[playerId] = { x: point_array[0], y: point_array[1]};
  }
  console.log("Before");
  io.emit('updatePlayers', objectPositions);
  console.log("After");
  lastTime = currTime;
}
setInterval(serverLoop, 1000/60);

Here, the game_wrapper comes from the Node C++ addon. I created a gameInstance from the library, which creates an instance of the game. New player can join in by connecting to the server, which triggers a creation of a new player in the game backend, identified by the socket ID.

When I called AddNewPlayer and RemovePlayer outside, they seem to work fine. However, when I called AddNewPlayer inside the serverLoop, the server either crashed immediately, or eventually crashed.

Does anyone have a suggestion of what is going on? I am suspecting that the serverLoop is actually a callback function that spawns a new thread. This creates some memory management issue if gameInstance does not handle memory properly, causing crashes. However, I would love to hear from node.js expert or socket.io expert here. Happy to provide further code to help debug this issue. Thanks!

I tried several things such as constructing the function the different way, or changing the way the function works on the backend. But I still have the same issues. It seems that Node Addon C++ doesn't like any object where memory might be dynamically allocated.


问:
Weird error when summing across columns. This function doesn't seem to exist
Here is my data:

```<code>> factors.table
# A tibble: 10 x 7
   var          nfacts   corr corrAbs   l50   l70   l75
   <chr>        <chr>   <dbl>   <dbl> <dbl> <dbl> <dbl>
 1 mpg          127     0.837   0.837     1     1     1
 2 cylinders    5      -0.759   0.759     1     1     1
 3 displacement 81     -0.753   0.753     1     1     1
 4 horsepower   93     -0.667   0.667     1     0     0
 5 weight       346    -0.758   0.758     1     1     1
 6 acceleration 95      0.347   0.347     0     0     0
 7 year         13      0.430   0.430     0     0     0
 8 origin       3       0.514   0.514     1     0     0
 9 name         301     0.264   0.264     0     0     0
10 mpg01        2       1       1         1     1     1
</code>```

I am trying to compute the sums of rows 5-7 as suggested here (Efficiently sum across multiple columns in R) but I am getting this error:

```<code>> rowSums(factors.table[,5:7])
Error in weekSum(dat, start, end, c) :
argument "start" is missing, with no default
</code>```

I have never seen weekSum before and it doesn't appear in R when I search help(weekSum).

Body:
Here is my data:

> factors.table
# A tibble: 10 x 7
   var          nfacts   corr corrAbs   l50   l70   l75
   <chr>        <chr>   <dbl>   <dbl> <dbl> <dbl> <dbl>
 1 mpg          127     0.837   0.837     1     1     1
 2 cylinders    5      -0.759   0.759     1     1     1
 3 displacement 81     -0.753   0.753     1     1     1
 4 horsepower   93     -0.667   0.667     1     0     0
 5 weight       346    -0.758   0.758     1     1     1
 6 acceleration 95      0.347   0.347     0     0     0
 7 year         13      0.430   0.430     0     0     0
 8 origin       3       0.514   0.514     1     0     0
 9 name         301     0.264   0.264     0     0     0
10 mpg01        2       1       1         1     1     1

I am trying to compute the sums of rows 5-7 as suggested here (Efficiently sum across multiple columns in R) but I am getting this error:

> rowSums(factors.table[,5:7])
Error in weekSum(dat, start, end, c) :
argument "start" is missing, with no default

I have never seen weekSum before and it doesn't appear in R when I search help(weekSum).


问:
R Shiny Run a independent process when app is closed
I have a button that initiates a long process (say a couple of hours) of creating a data pipeline. Is there a way that the user can close the R Shiny app & the process continues to execute.
If needed, i can have a different R script or Python script to run the process

I couldn't think of any ways how this can be done. I'm relatively new to R Shiny


问:
SPSS Statistics 27 Cluster Slihouette throwing Python error
I am trying to use SPSS to do a cluster silhouette analysis like so:

```<code>STATS CLUS SIL CLUSTER=QCL_1 VARIABLES=V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18
    V19 V20 V21 V22 V23 V24 V25 V26 V27 V28 V29 V30 V31 V32 V33 V34 V35 V36 V37 V38 V39 V40 V41 V42 V43
    V44 V45 V46 V47 V48 V49 V50 V51 V52 V53 V54 V55 V56 V57 V58 V59 V60 V61 V62 V63 V64 V65 V66 V67 V68
    V69 V70 V71 V72 V73 V74 V75 V76 V77 V78 V79 V80 V81 V82 V83 V84 V85 V86 V87 V88 V89 V90 V91 V92 V93
    V94 V95 V96 V97 V98 V99 V100
NEXTBEST=nbc SILHOUETTE=sil DISSIMILARITY=EUCLID MINKOWSKIPOWER=2
/OPTIONS MISSING=IGNORE RENUMBERORDINAL=NO
/OUTPUT HISTOGRAM=YES ORIENTATION=HORIZONTAL THREEDBAR=YES THREEDCOUNTS=NO.
</code>```

When I run this I get an error

```<code>'>' not supported between instances of 'float' and 'None Type'
</code>```

Based on searchers I ran this is a Python error, but of course I can't fix Python errors in SPSS.  Anyone know how deal with this?

Body:
I am trying to use SPSS to do a cluster silhouette analysis like so:

STATS CLUS SIL CLUSTER=QCL_1 VARIABLES=V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18
    V19 V20 V21 V22 V23 V24 V25 V26 V27 V28 V29 V30 V31 V32 V33 V34 V35 V36 V37 V38 V39 V40 V41 V42 V43
    V44 V45 V46 V47 V48 V49 V50 V51 V52 V53 V54 V55 V56 V57 V58 V59 V60 V61 V62 V63 V64 V65 V66 V67 V68
    V69 V70 V71 V72 V73 V74 V75 V76 V77 V78 V79 V80 V81 V82 V83 V84 V85 V86 V87 V88 V89 V90 V91 V92 V93
    V94 V95 V96 V97 V98 V99 V100
NEXTBEST=nbc SILHOUETTE=sil DISSIMILARITY=EUCLID MINKOWSKIPOWER=2
/OPTIONS MISSING=IGNORE RENUMBERORDINAL=NO
/OUTPUT HISTOGRAM=YES ORIENTATION=HORIZONTAL THREEDBAR=YES THREEDCOUNTS=NO.

When I run this I get an error

'>' not supported between instances of 'float' and 'None Type'

Based on searchers I ran this is a Python error, but of course I can't fix Python errors in SPSS.  Anyone know how deal with this?


问:
Google colab blocking requests.get, causing 403 error
I'm trying to scrape web reviews from the appstore through rss and when I run my code on a local environment, it runs just fine and it gets all the requests 200 without issue. but if i run my code in google colab, it eventually fails after a while and google seems to block it, giving a 403 error.

i've tried adding headers, putting a time sleep, and adding a proxy to the request but nothing seems to work.

does anyone know how to fix this? thank you very much.

Here is a link to an example of my code: https://colab.research.google.com/drive/1gVCpIA3t0h05lPo670hp5i9jZxXRnsN9?usp=sharing

The following below is a simplified version of my code

```<code>import re
import glob
import requests
import time

countries = ["us", "dz", "ao", "ai", "ag"]

# proxy. get one from https://spys.one/en/ of type HTTP (not HTTPS)
proxy = {
    # "https": 'http://95.154.76.20:3128 ',
    "http": 'http://66.11.117.253:9999'
}

failed_try = 0

def requesturl(url):
  global failed_try
  global proxy

  headers = {
      'User-Agent': ('Mozilla/6.0 (Windows NT 10.0; Win64; x64; rv:61.0) '
                    'Gecko/20100101 Firefox/61.0'),
      'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
      "Content-Type": "application/json"
  }

  while True:

    response = requests.get(url, headers=headers, proxies=proxy)
    if response.status_code == 403:
      print(response, "  Retrying request...")
      failed_try += 1
      if failed_try >= 5:
        time.sleep(2)
      continue
    failed_try = 0
    return response

# downloads reviews by county
def download(country):
  global total_review_count
  # list of target genres
  genres = {
    "action": "7001",
    "strategy": "7017",
    "sports": "7016",
  }

  # shows current country progress
  country_pos = f"{countries.index(country)+1}/{len(countries)}"
  print(f"\n\n\n================Scraping Country {country_pos}================")

  # iterate through mode of payment
  for payment in ["topfreeapplications", "toppaidapplications"]:
    print(f"\n\n================Scraping {payment} [{country_pos}]================")
    # loop through every genre
    for genre in genres:
      print(f"\n     Getting {genre} list...")
      # get list of games per genre and type of payment
      genre_link = f"https://itunes.apple.com/{country}/rss/{payment}/limit=200/genre={genres[genre]}/json"

      dict_genre_resp = requesturl(genre_link)
      print("this>", dict_genre_resp, genre_link)
      dict_genre_response = dict_genre_resp.json()

      # number o
      review_count = 0

      # iterates through every game in a genre
      for game in dict_genre_response["feed"]["entry"]:
        # get relevant data from response
        game_id = game["id"]["attributes"]["im:id"]
        game_name = game["title"]['label']

        # Loop through the game's reviews per pages
        for n in range(1,10+1):
          # get review

          reviews_response = requesturl(f"https://itunes.apple.com/us/rss/customerreviews/page={n}/id={game_id}/sortBy=mostRecent/json")
          print(game_name, reviews_response)
        print()

def main():
  for country in countries:
    download(country)

if __name__ == "__main__":
  main()```
```

Body:
I'm trying to scrape web reviews from the appstore through rss and when I run my code on a local environment, it runs just fine and it gets all the requests 200 without issue. but if i run my code in google colab, it eventually fails after a while and google seems to block it, giving a 403 error.

i've tried adding headers, putting a time sleep, and adding a proxy to the request but nothing seems to work.

does anyone know how to fix this? thank you very much.

Here is a link to an example of my code: https://colab.research.google.com/drive/1gVCpIA3t0h05lPo670hp5i9jZxXRnsN9?usp=sharing

The following below is a simplified version of my code

import re
import glob
import requests
import time

countries = ["us", "dz", "ao", "ai", "ag"]

# proxy. get one from https://spys.one/en/ of type HTTP (not HTTPS)
proxy = {
    # "https": 'http://95.154.76.20:3128 ',
    "http": 'http://66.11.117.253:9999'
}

failed_try = 0

def requesturl(url):
  global failed_try
  global proxy

  headers = {
      'User-Agent': ('Mozilla/6.0 (Windows NT 10.0; Win64; x64; rv:61.0) '
                    'Gecko/20100101 Firefox/61.0'),
      'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
      "Content-Type": "application/json"
  }

  while True:

    response = requests.get(url, headers=headers, proxies=proxy)
    if response.status_code == 403:
      print(response, "  Retrying request...")
      failed_try += 1
      if failed_try >= 5:
        time.sleep(2)
      continue
    failed_try = 0
    return response

# downloads reviews by county
def download(country):
  global total_review_count
  # list of target genres
  genres = {
    "action": "7001",
    "strategy": "7017",
    "sports": "7016",
  }

  # shows current country progress
  country_pos = f"{countries.index(country)+1}/{len(countries)}"
  print(f"\n\n\n================Scraping Country {country_pos}================")

  # iterate through mode of payment
  for payment in ["topfreeapplications", "toppaidapplications"]:
    print(f"\n\n================Scraping {payment} [{country_pos}]================")
    # loop through every genre
    for genre in genres:
      print(f"\n     Getting {genre} list...")
      # get list of games per genre and type of payment
      genre_link = f"https://itunes.apple.com/{country}/rss/{payment}/limit=200/genre={genres[genre]}/json"

      dict_genre_resp = requesturl(genre_link)
      print("this>", dict_genre_resp, genre_link)
      dict_genre_response = dict_genre_resp.json()

      # number o
      review_count = 0

      # iterates through every game in a genre
      for game in dict_genre_response["feed"]["entry"]:
        # get relevant data from response
        game_id = game["id"]["attributes"]["im:id"]
        game_name = game["title"]['label']

        # Loop through the game's reviews per pages
        for n in range(1,10+1):
          # get review

          reviews_response = requesturl(f"https://itunes.apple.com/us/rss/customerreviews/page={n}/id={game_id}/sortBy=mostRecent/json")
          print(game_name, reviews_response)
        print()

def main():
  for country in countries:
    download(country)

if __name__ == "__main__":
  main()```


问:
How to get the number of current UObjects in scene UE4?
How do I get the number of UObjects in the scene using  TObjectIterator?

I tried the following , but  I get an unresolved external error for Count++.

```<code>float Count = 0;

    for(TObjectIterator<UObject> UObjectIt; UObjectIt; ++UObjectIt)
    {
        if(UObjectIt->GetWorld() == currentGameWorld)
        {
            UObject* ObjectModel = *UObjectIt;
            Count++;
        }
    }
</code>```

Body:
How do I get the number of UObjects in the scene using  TObjectIterator?

I tried the following , but  I get an unresolved external error for Count++.

float Count = 0;

    for(TObjectIterator<UObject> UObjectIt; UObjectIt; ++UObjectIt)
    {
        if(UObjectIt->GetWorld() == currentGameWorld)
        {
            UObject* ObjectModel = *UObjectIt;
            Count++;
        }
    }


问:
Assistance with XIRR Formula
When using XIRR to calculate the performance of a stock trading account, do you need to have a beginning cash flow equal to the starting balance of the account (seed money) ?

When I do that, it throws the formula completely for a loop and I either get errors because it can't calculate the return, or the return is very, very negative despite the account actually increasing in value over the year.

```<code>$7,000 starting balance/seed money, entered as a negative, January 1st
$6,800 invested in a trade, January 2nd
$8,000 deposited from closing the trade, December 22nd.
</code>```

The ROIC on the trade would be 17.6%, and the MWRR should be about 17.1%, +/- 1% since the investment period was slightly less than a full year.

But XIRR is returning -43%?! If I tell XIRR to ignore the seed money, and only look at the amount invested in the trade and the amount received when closing the trade, I get just over 18%, which seems right.

What am I not understanding about XIRR? I thought all IRR needed to include the seed money?

Title: Assistance with XIRR Formula

Body:
When using XIRR to calculate the performance of a stock trading account, do you need to have a beginning cash flow equal to the starting balance of the account (seed money) ?

When I do that, it throws the formula completely for a loop and I either get errors because it can't calculate the return, or the return is very, very negative despite the account actually increasing in value over the year.

$7,000 starting balance/seed money, entered as a negative, January 1st
$6,800 invested in a trade, January 2nd
$8,000 deposited from closing the trade, December 22nd.

The ROIC on the trade would be 17.6%, and the MWRR should be about 17.1%, +/- 1% since the investment period was slightly less than a full year.

But XIRR is returning -43%?! If I tell XIRR to ignore the seed money, and only look at the amount invested in the trade and the amount received when closing the trade, I get just over 18%, which seems right.

What am I not understanding about XIRR? I thought all IRR needed to include the seed money?