问:
Restructure Nested JSON Data And Removing Some Keys
I need to restructure a nested JSON data.
Here is how it looks like:

{
  "MainKey1": [
    {
      "Section1": {
        "ParentTag1 Mapped Label": {
          "ParentTag1": {
            "Tag1 Mapped Label": {
              "Tag1": "1234567890"
            }
          }
        }
      }
    },
    {
      "Section2": {
        "ParentTag1 Mapped Label": {
          "ParentTag1": {
            "Tag1 Label": {
              "Tag1": "111222333444"
            },
            "Tag2 Label": {
              "Tag2": "121212"
            },
            "Tag3 Label": {
              "Tag3": "0987654321"
            }
          }
        }
      }
    }
  ],
  "MainKey2": [
    {
      "Section1": {
        "ParentTag1 Mapped Label": {
          "ParentTag1": {
            "Tag1 Mapped Label": {
              "Tag1": "1234567890"
            }
          }
        }
      }
    }
  ]
}
```
<p>And this is a sample of the converted JSON:</p>
<pre class="lang-json prettyprint-override"><code>{
    MainKey: [
    {
      Section1: [
        {
          ParentTag1: [
            { Tag1: "1234567890" }
          ]
        }
      ]
    },
    {
      Section2: [
         {
           ParentTag1: [
              { Tag1: "111222333444" },
              { Tag2: "121212" },
              { Tag3: "0987654321" }
            ]
         }
      ]
    }
  ],
  MainKey2: [
    {
        Section1: [
        {
            ParentTag1 : [
                { Tag1: "1234567890" }
            ]
        }
      ]
    }
  ]
}
</code>```

Rules:

Everything inside a MainKey (outermost keys, could be any name) should be an array

All labels should be stripped (as the label could be any name, without the actual word "Label", we can determine if it is a label based on the depth level. Since the JSON will have the label as the parent and the actual "tag" as a child.

Here is what I currently have (it is a mess, sorry!)

function convertJson (jsonObj) {
    const mainKeys = Object.keys(jsonObj)
    let output = {}

    for (let i = 0; i < mainKeys.length; i++) {
      const mainKey = mainKeys[i]
      let result = []
      output[mainKey] = result

      for (let j = 0; j < jsonObj[mainKey].length; j++) {
        const innerObj = {...jsonObj[mainKey][j]}
        const sectionName = Object.keys(innerObj)[0]
        const sectionObj = {}
        sectionObj[sectionName] = []
        const index = result.push(sectionObj) - 1
        parseObj(innerObj[sectionName], result[index], 0)   // if I change 2nd param to: result, it generates incorrect output
      }
    }
    console.log(output)
}

function parseObj (innerObj, result, depthCount) {
    for (var key in innerObj) {
        if (typeof innerObj[key] === "object") {
          if (depthCount % 2 === 1) {
          const parentObj = {}
          parentObj[key] = []
          result.push(parentObj)
          depthCount++

          parseObj(innerObj[key], parentObj[key], depthCount)
        } else {
          depthCount++
          parseObj(innerObj[key], result, depthCount)
        }
      } else {
        const keyValuePairObj = {}
        keyValuePairObj[key] = innerObj[key]
        result.push(keyValuePairObj)
      }
    }
    return result
}
convertJson(json)
```
<p>But it generates an error:</p>
```Uncaught TypeError: result.push is not a function
```
<p>Now if I change line 90 from:</p>
<pre class="lang-js prettyprint-override"><code>parseObj(innerObj[sectionName], result[index], 0)
</code>```

to:

parseObj(innerObj[sectionName], result, 0)
```
<p>Here is incorrect output:</p>
<pre class="lang-json prettyprint-override"><code>{
  "MainKey1": [
    {
      "Section1": []
    },
    {
      "ParentTag1": [
        {
          "Tag1": "1234567890"
        }
      ]
    },
    {
      "Section2": []
    },
    {
      "ParentTag1": [
        {
          "Tag1": "111222333444"
        },
        {
          "Tag2 Label": [
            {
              "Tag2": "121212"
            }
          ]
        },
        {
          "Tag3": "0987654321"
        }
      ]
    }
  ],
  "MainKey2": [
    {
      "Section1": []
    },
    {
      "Tag1": "1234567890"
    }
  ]
}
</code>```

And here is my fiddle:
https://jsfiddle.net/kzaiwo/L4avxmyd/36/

Thanks a lot! Appreciate any help!

Body:
I need to restructure a nested JSON data.
Here is how it looks like:

{
  "MainKey1": [
    {
      "Section1": {
        "ParentTag1 Mapped Label": {
          "ParentTag1": {
            "Tag1 Mapped Label": {
              "Tag1": "1234567890"
            }
          }
        }
      }
    },
    {
      "Section2": {
        "ParentTag1 Mapped Label": {
          "ParentTag1": {
            "Tag1 Label": {
              "Tag1": "111222333444"
            },
            "Tag2 Label": {
              "Tag2": "121212"
            },
            "Tag3 Label": {
              "Tag3": "0987654321"
            }
          }
        }
      }
    }
  ],
  "MainKey2": [
    {
      "Section1": {
        "ParentTag1 Mapped Label": {
          "ParentTag1": {
            "Tag1 Mapped Label": {
              "Tag1": "1234567890"
            }
          }
        }
      }
    }
  ]
}

And this is a sample of the converted JSON:

{
    MainKey: [
    {
      Section1: [
        {
          ParentTag1: [
            { Tag1: "1234567890" }
          ]
        }
      ]
    },
    {
      Section2: [
         {
           ParentTag1: [
              { Tag1: "111222333444" },
              { Tag2: "121212" },
              { Tag3: "0987654321" }
            ]
         }
      ]
    }
  ],
  MainKey2: [
    {
        Section1: [
        {
            ParentTag1 : [
                { Tag1: "1234567890" }
            ]
        }
      ]
    }
  ]
}

Rules:

Everything inside a MainKey (outermost keys, could be any name) should be an array

All labels should be stripped (as the label could be any name, without the actual word "Label", we can determine if it is a label based on the depth level. Since the JSON will have the label as the parent and the actual "tag" as a child.

Here is what I currently have (it is a mess, sorry!)

function convertJson (jsonObj) {
    const mainKeys = Object.keys(jsonObj)
    let output = {}

    for (let i = 0; i < mainKeys.length; i++) {
      const mainKey = mainKeys[i]
      let result = []
      output[mainKey] = result

      for (let j = 0; j < jsonObj[mainKey].length; j++) {
        const innerObj = {...jsonObj[mainKey][j]}
        const sectionName = Object.keys(innerObj)[0]
        const sectionObj = {}
        sectionObj[sectionName] = []
        const index = result.push(sectionObj) - 1
        parseObj(innerObj[sectionName], result[index], 0)   // if I change 2nd param to: result, it generates incorrect output
      }
    }
    console.log(output)
}

function parseObj (innerObj, result, depthCount) {
    for (var key in innerObj) {
        if (typeof innerObj[key] === "object") {
          if (depthCount % 2 === 1) {
          const parentObj = {}
          parentObj[key] = []
          result.push(parentObj)
          depthCount++

          parseObj(innerObj[key], parentObj[key], depthCount)
        } else {
          depthCount++
          parseObj(innerObj[key], result, depthCount)
        }
      } else {
        const keyValuePairObj = {}
        keyValuePairObj[key] = innerObj[key]
        result.push(keyValuePairObj)
      }
    }
    return result
}
convertJson(json)

But it generates an error:

Uncaught TypeError: result.push is not a function

Now if I change line 90 from:

parseObj(innerObj[sectionName], result[index], 0)

to:

parseObj(innerObj[sectionName], result, 0)

Here is incorrect output:

{
  "MainKey1": [
    {
      "Section1": []
    },
    {
      "ParentTag1": [
        {
          "Tag1": "1234567890"
        }
      ]
    },
    {
      "Section2": []
    },
    {
      "ParentTag1": [
        {
          "Tag1": "111222333444"
        },
        {
          "Tag2 Label": [
            {
              "Tag2": "121212"
            }
          ]
        },
        {
          "Tag3": "0987654321"
        }
      ]
    }
  ],
  "MainKey2": [
    {
      "Section1": []
    },
    {
      "Tag1": "1234567890"
    }
  ]
}

And here is my fiddle:
https://jsfiddle.net/kzaiwo/L4avxmyd/36/

Thanks a lot! Appreciate any help!


来源: stackexchange

问:
How to properly pass a string to a tflite model?
I have build a model for text classification (the input is a string, the output is a scalar) that I would like to quantize and deploy as a tensorflow lite model. I successfully converted the model to tflite and quantized it, but I'm unable to pass a string to the model for inference.

What I'm attempting to do, is create a minimally reproducible example of inference with the tflite model, which I can then provide to my company's engineering group so they can deploy it.

The following code works:

```<code>original_keras_model(tf.convert_to_tensor([testgood, testbad]))
</code>```

It correctly outputs two scalars.

The following code does not work:

```<code>interpreter = tf.lite.Interpreter(model_path="./final_model.tflite")
interpreter.allocate_tensors()

input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

input_shape = input_details[0]['shape']
input_data = tf.convert_to_tensor([testgood, testbad])
#input_data2 = tf.reshape(input_data[0], input_shape)
interpreter.set_tensor(input_details[0]['index'], input_data)
</code>```

In particular, set_tensor returns this error: ValueError: Cannot set tensor: Dimension mismatch. Got 2 but expected 1 for dimension 0 of input 0.

I have tried passing only one example instead of two. In that case I get the error: ValueError: Cannot set tensor: Dimension mismatch. Got 0 but expected 1 for input 0.

The input details are:

```<code>[{'name': 'serving_default_text_vectorization_input:0',
  'index': 0,
  'shape': array([1], dtype=int32),
  'shape_signature': array([-1], dtype=int32),
  'dtype': numpy.bytes_,
  'quantization': (0.0, 0),
  'quantization_parameters': {'scales': array([], dtype=float32),
   'zero_points': array([], dtype=int32),
   'quantized_dimension': 0},
  'sparsity_parameters': {}}]
</code>```

Any help is appreciated.

ContentLicense: CC BY-SA 4.0

Body:
I have build a model for text classification (the input is a string, the output is a scalar) that I would like to quantize and deploy as a tensorflow lite model. I successfully converted the model to tflite and quantized it, but I'm unable to pass a string to the model for inference.

What I'm attempting to do, is create a minimally reproducible example of inference with the tflite model, which I can then provide to my company's engineering group so they can deploy it.

The following code works:

original_keras_model(tf.convert_to_tensor([testgood, testbad]))

It correctly outputs two scalars.

The following code does not work:

interpreter = tf.lite.Interpreter(model_path="./final_model.tflite")
interpreter.allocate_tensors()

input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

input_shape = input_details[0]['shape']
input_data = tf.convert_to_tensor([testgood, testbad])
#input_data2 = tf.reshape(input_data[0], input_shape)
interpreter.set_tensor(input_details[0]['index'], input_data)

In particular, set_tensor returns this error: ValueError: Cannot set tensor: Dimension mismatch. Got 2 but expected 1 for dimension 0 of input 0.

I have tried passing only one example instead of two. In that case I get the error: ValueError: Cannot set tensor: Dimension mismatch. Got 0 but expected 1 for input 0.

The input details are:

[{'name': 'serving_default_text_vectorization_input:0',
  'index': 0,
  'shape': array([1], dtype=int32),
  'shape_signature': array([-1], dtype=int32),
  'dtype': numpy.bytes_,
  'quantization': (0.0, 0),
  'quantization_parameters': {'scales': array([], dtype=float32),
   'zero_points': array([], dtype=int32),
   'quantized_dimension': 0},
  'sparsity_parameters': {}}]

Any help is appreciated.


问:
nunjucks equivalent to liquid capture in this loop?
Current liquid capture loop

```<code>{% if page.related %}
{% capture results %}
[ {% for category in page.categories %}
{% for post in site.categories[category] %}
{% if post.url != page.url %}"{{ post.url | relative_url | prepend: site.url }}"{% unless forloop.last %},{% endunless %}{% endif %}{% if forloop.last %}],{% endif %}{% endfor %}{% endfor %}
{% endcapture %}
    "relatedLink":{{ results }}
    {% else %}{% endif %}
</code>```

I read about nunjucks set filter. I'm just not sure what would be the equivalent?

Body:
Current liquid capture loop

{% if page.related %}
{% capture results %}
[ {% for category in page.categories %}
{% for post in site.categories[category] %}
{% if post.url != page.url %}"{{ post.url | relative_url | prepend: site.url }}"{% unless forloop.last %},{% endunless %}{% endif %}{% if forloop.last %}],{% endif %}{% endfor %}{% endfor %}
{% endcapture %}
    "relatedLink":{{ results }}
    {% else %}{% endif %}

I read about nunjucks set filter. I'm just not sure what would be the equivalent?


问:
No details in KqlError when I try to use KqlMagic
I'm trying to connect to an azure data explorer but I keep getting a non descriptive error. I'm following this tutorial.
https://learn.microsoft.com/en-us/sql/azure-data-studio/notebooks/notebooks-kqlmagic?view=sql-server-ver16.
Has anyone seen this?
click here for screenshot

I was trying to connect to azure data explorer from Azure Machine Learning Studio notebooks. I also tried it in Jupyter notebooks with an anaconda environment and I got the same error.
However, the command %reload_ext Kqlmagic worked for me

Maybe its because that Azure login has multiple directories?


问:
File Browse in Alteryx - New File Selected when it is run
I'm somewhat new to Alteryx, and I'm stuck on inputting excel files correctly. My goal is to utilize the File Browse tool so that the user of the app/workflow can select/input a new file when it is run. While the files inputted may differ each time, the format will always be the same. This file will have multiple tabs, but I only want to read in two tabs (the name of these 2 tabs will always be the same no matter which file is selected, let's say the two tabs are named X1 and X2). The goal is to take each tab and perform cleansing and manipulation on the two tabs separately, and then union them back in the end. How can I set up the File Browse -> Input Data (or Dynamic Input) to take in a new file each time, connect them to an input tool, and take the same two tabs to clean/manipulate them?

I am using Alteryx Version 2020.6.4


问:
Why I am getting Kestrel binding permission denied error over port 443 while container running as non root user
I am running .Net 6 api app as a non-root user and trying to set ASPNETCORE_HTTPS_PORT = 443.

```<code>FROM mcr.microsoft.com/dotnet/aspnet:6.0-alpine AS final
ENV ASPNETCORE_URLS=https://+:443
ENV ASPNETCORE_HTTPS_PORT=443

RUN adduser --disabled-password --home /app --gecos '' nonroot && chown -R nonroot /app
USER nonroot
</code>```

While container is running I am getting Kestrel binding permission denied error, why I am getting this error?

Unhandled exception. System.Net.Sockets.SocketException (13): Permission denied
at System.Net.Sockets.Socket.UpdateStatusAfterSocketErrorAndThrowException(SocketError error, String callerName)
at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.Sockets.Socket.Bind(EndPoint localEP)
at Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.SocketTransportOptions.CreateDefaultBoundListenSocket(EndPoint endpoint)
at Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.SocketConnectionListener.Bind()
at Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.SocketTransportFactory.BindAsync(EndPoint endpoint, CancellationToken cancellationToken)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure.TransportManager.BindAsync(EndPoint endPoint, ConnectionDelegate connectionDelegate, EndpointConfig endpointConfig, CancellationToken cancellationToken)
at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerImpl.<>c__DisplayClass30_0`1.<g__OnBind|0>d.MoveNext()

I am seeing while I am setting ports other than 443, then it's working. (ENV ASPNETCORE_URLS=https://+:5080    ENV ASPNETCORE_HTTPS_PORT=5080)

Body:
I am running .Net 6 api app as a non-root user and trying to set ASPNETCORE_HTTPS_PORT = 443.

FROM mcr.microsoft.com/dotnet/aspnet:6.0-alpine AS final
ENV ASPNETCORE_URLS=https://+:443
ENV ASPNETCORE_HTTPS_PORT=443

RUN adduser --disabled-password --home /app --gecos '' nonroot && chown -R nonroot /app
USER nonroot

While container is running I am getting Kestrel binding permission denied error, why I am getting this error?

Unhandled exception. System.Net.Sockets.SocketException (13): Permission denied
at System.Net.Sockets.Socket.UpdateStatusAfterSocketErrorAndThrowException(SocketError error, String callerName)
at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.Sockets.Socket.Bind(EndPoint localEP)
at Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.SocketTransportOptions.CreateDefaultBoundListenSocket(EndPoint endpoint)
at Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.SocketConnectionListener.Bind()
at Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.SocketTransportFactory.BindAsync(EndPoint endpoint, CancellationToken cancellationToken)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure.TransportManager.BindAsync(EndPoint endPoint, ConnectionDelegate connectionDelegate, EndpointConfig endpointConfig, CancellationToken cancellationToken)
at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerImpl.<>c__DisplayClass30_0`1.<g__OnBind|0>d.MoveNext()

I am seeing while I am setting ports other than 443, then it's working. (ENV ASPNETCORE_URLS=https://+:5080    ENV ASPNETCORE_HTTPS_PORT=5080)


问:
Variable substitution is not happening inside Containerfile

Building a docker container

Using alpine as build image

The Containerfile receives VERSION as argument

It is set as image version

The same version is passed to dotnet publish command.

The passed version (which is a variable) in current context never gets substituted. Instead of substituted variable ${VARIABLE} is passed to dotnet publish command.

```<code>    ARG VERSION

    FROM mcr.microsoft.com/dotnet/sdk:6.0-alpine as build
    ARG VERSION
    RUN echo ${VERSION}
    RUN echo ${VERSION} > image_version
    WORKDIR /app
    COPY . .
    RUN dotnet restore
    # TODO Pass the version as build command below.
    RUN dotnet publish --version-suffix ${VERSION} --output /app/published-app
</code>```

I tried different ways to do the variable substitution like below:

"$VERSION"

"$(VERSION)"

$VERSION ..... and many other ways I found in the internet. None of them worked. The argument passed is exactly what it is before the variable is substituted.

Thoughts on what may be causing this?

Body:
Building a docker container

Using alpine as build image

The Containerfile receives VERSION as argument

It is set as image version

The same version is passed to dotnet publish command.

The passed version (which is a variable) in current context never gets substituted. Instead of substituted variable ${VARIABLE} is passed to dotnet publish command.

    ARG VERSION

    FROM mcr.microsoft.com/dotnet/sdk:6.0-alpine as build
    ARG VERSION
    RUN echo ${VERSION}
    RUN echo ${VERSION} > image_version
    WORKDIR /app
    COPY . .
    RUN dotnet restore
    # TODO Pass the version as build command below.
    RUN dotnet publish --version-suffix ${VERSION} --output /app/published-app

I tried different ways to do the variable substitution like below:

"$VERSION"

"$(VERSION)"

$VERSION ..... and many other ways I found in the internet. None of them worked. The argument passed is exactly what it is before the variable is substituted.

Thoughts on what may be causing this?


问:
how to set fixed height in reactimagemagnify
Currently I am using reactimagemagnify library in my next js project. But can't set specific height. I'm getting unexpected behavior when I'm going to set a specific height. Entering the cursor on a small image gives a blank space below the image

```<code> <Grid item xs={12} md={6}>
<Stack
          maxWidth="440px"
          width="100%"
          height="440px"

        >
          <ReactImageMagnify
            {...{
              smallImage: {
                alt: "image",
                isFluidWidth: true,
                src: preViewImage,
                              },
              largeImage: {
                src: preViewImage,
                width: 1200,
                height: 1800,
              },
              enlargedImageContainerStyle: {
                zIndex: "1500",
              },
              enlargedImageContainerDimensions: {
                width: "100%",
                height: "100%",
              },
              enlargedImagePosition: isSmall ? "over" : "beside",
            }}
          />
        </Stack>
</Grid>
</code>```

i want a fixed height for small image.

Body:
Currently I am using reactimagemagnify library in my next js project. But can't set specific height. I'm getting unexpected behavior when I'm going to set a specific height. Entering the cursor on a small image gives a blank space below the image

 <Grid item xs={12} md={6}>
<Stack
          maxWidth="440px"
          width="100%"
          height="440px"

        >
          <ReactImageMagnify
            {...{
              smallImage: {
                alt: "image",
                isFluidWidth: true,
                src: preViewImage,
                              },
              largeImage: {
                src: preViewImage,
                width: 1200,
                height: 1800,
              },
              enlargedImageContainerStyle: {
                zIndex: "1500",
              },
              enlargedImageContainerDimensions: {
                width: "100%",
                height: "100%",
              },
              enlargedImagePosition: isSmall ? "over" : "beside",
            }}
          />
        </Stack>
</Grid>

i want a fixed height for small image.


问:
ModuleNotFoundError: No module named '_bz2' in Google Cloud Workstation
I launched a new Google Cloud Workstation and create a single python file with these contents:

```<code>import bz2
import binascii

original_data = 'This is the original text.'
print ('Original     :', len(original_data), original_data)

compressed = bz2.compress(original_data)
print ('Compressed   :', len(compressed), binascii.hexlify(compressed))

decompressed = bz2.decompress(compressed)
print ('Decompressed :', len(decompressed), decompressed)
</code>```

When I tried to run this code I received this error:

```<code>Traceback (most recent call last):
  File "/home/user/01/app.py", line 1, in <module>
    import bz2
  File "/usr/local/lib/python3.10/bz2.py", line 17, in <module>
    from _bz2 import BZ2Compressor, BZ2Decompressor
ModuleNotFoundError: No module named '_bz2'
</code>```

What am I doing wrong?

Body:
I launched a new Google Cloud Workstation and create a single python file with these contents:

import bz2
import binascii

original_data = 'This is the original text.'
print ('Original     :', len(original_data), original_data)

compressed = bz2.compress(original_data)
print ('Compressed   :', len(compressed), binascii.hexlify(compressed))

decompressed = bz2.decompress(compressed)
print ('Decompressed :', len(decompressed), decompressed)

When I tried to run this code I received this error:

Traceback (most recent call last):
  File "/home/user/01/app.py", line 1, in <module>
    import bz2
  File "/usr/local/lib/python3.10/bz2.py", line 17, in <module>
    from _bz2 import BZ2Compressor, BZ2Decompressor
ModuleNotFoundError: No module named '_bz2'

What am I doing wrong?


问:
How can I fix my collision detection code in my pygame platformer game?
I have this collision detection code but I have problem when i try to call this function later in my program it works, but I don't get any collision.</p>
```<code>def collisionTest(rect, tiles):
    collisionList = []
    for tile in tiles:
        if rect.colliderect(tile):
            collisionList.append(tile)
    return collisionList

def move(rect, movement, tiles):
    collisionAreas = {'top': False, 'bottom': False, 'right': False, 'left': False} # all the areas we are trying to find collision for
    rect.x += movement[0] # collision on the x axis
    collisionList = collisionTest(rect, tiles)
    for tile in collisionList:
        if movement[0] > 0:
            rect.right = tile.left # player on the right tile on the left
            collisionAreas['right'] = True # there is collision on the right of the player

        elif movement[0] < 0:
            rect.left = tile.right # player on the left tile on the right
            collisionAreas['left'] = True # there is collision on the right of the player
    rect.y += movement[1] # collision on the y axis
    collisionList = collisionTest(rect, tiles)

    for tile in collisionList:
        if movement[1] > 0:
            rect.bottom = tile.top # bottom of the player collides with the top of the tile
            collisionAreas['bottom'] = True # there is collision on the bottom of the player

        elif movement[1] < 0:
            rect.top = tile.bottom # top of the player is colliding with the bottom of the tile
            collisionAreas['top'] = True # there is collision on the top of the player

    return rect, collisionAreas #return the player that's moving and the list of collisions that accured

  playerRect, collisions = move(playerRect, playerPos, tileRects) # calling the function
  display.blit(spriteSheet, (playerRect.x-scroll[0], playerRect.y-scroll[1]), playerIdle_Rect) # displaying my character
</code>```

Body:
I have this collision detection code but I have problem when i try to call this function later in my program it works, but I don't get any collision.

def collisionTest(rect, tiles):
    collisionList = []
    for tile in tiles:
        if rect.colliderect(tile):
            collisionList.append(tile)
    return collisionList

def move(rect, movement, tiles):
    collisionAreas = {'top': False, 'bottom': False, 'right': False, 'left': False} # all the areas we are trying to find collision for
    rect.x += movement[0] # collision on the x axis
    collisionList = collisionTest(rect, tiles)
    for tile in collisionList:
        if movement[0] > 0:
            rect.right = tile.left # player on the right tile on the left
            collisionAreas['right'] = True # there is collision on the right of the player

        elif movement[0] < 0:
            rect.left = tile.right # player on the left tile on the right
            collisionAreas['left'] = True # there is collision on the right of the player
    rect.y += movement[1] # collision on the y axis
    collisionList = collisionTest(rect, tiles)

    for tile in collisionList:
        if movement[1] > 0:
            rect.bottom = tile.top # bottom of the player collides with the top of the tile
            collisionAreas['bottom'] = True # there is collision on the bottom of the player

        elif movement[1] < 0:
            rect.top = tile.bottom # top of the player is colliding with the bottom of the tile
            collisionAreas['top'] = True # there is collision on the top of the player

    return rect, collisionAreas #return the player that's moving and the list of collisions that accured

  playerRect, collisions = move(playerRect, playerPos, tileRects) # calling the function
  display.blit(spriteSheet, (playerRect.x-scroll[0], playerRect.y-scroll[1]), playerIdle_Rect) # displaying my character


问:
Downloading pytorch3d installtion no c++ compiler
I have been trying to download pytorch3d on my PC however it keeps failing. I believe its because of the c++ compiler but I am not sure.

```<code>FAILED: C:/Users/Virtual Machine/AppData/Local/Temp/pip-req-build-fu0xd6su/build/temp.win-amd64-cpython-310/Release/Users/Virtual Machine/AppData/Local/Temp/pip-req-build-fu0xd6su/pytorch3d/csrc/point_mesh/point_mesh_cpu.obj
      cl /showIncludes /nologo /O2 /W3 /GL /DNDEBUG /MD /MD /wd4819 /wd4251 /wd4244 /wd4267 /wd4275 /wd4018 /wd4190 /EHsc "-IC:\Users\Virtual Machine\AppData\Local\Temp\pip-req-build-fu0xd6su\pytorch3d\csrc" "-IC:\Users\Virtual Machine\AppData\Local\Programs\Python\Python310\lib\site-packages\torch\include" "-IC:\Users\Virtual Machine\AppData\Local\Programs\Python\Python310\lib\site-packages\torch\include\torch\csrc\api\include" "-IC:\Users\Virtual Machine\AppData\Local\Programs\Python\Python310\lib\site-packages\torch\include\TH" "-IC:\Users\Virtual Machine\AppData\Local\Programs\Python\Python310\lib\site-packages\torch\include\THC" "-IC:\Users\Virtual Machine\AppData\Local\Programs\Python\Python310\include" "-IC:\Users\Virtual Machine\AppData\Local\Programs\Python\Python310\Include" -c "C:\Users\Virtual Machine\AppData\Local\Temp\pip-req-build-fu0xd6su\pytorch3d\csrc\point_mesh\point_mesh_cpu.cpp" /Fo"C:\Users\Virtual Machine\AppData\Local\Temp\pip-req-build-fu0xd6su\build\temp.win-amd64-cpython-310\Release\Users\Virtual Machine\AppData\Local\Temp\pip-req-build-fu0xd6su\pytorch3d\csrc\point_mesh\point_mesh_cpu.obj" -std=c++14 -DTORCH_API_INCLUDE_EXTENSION_H -DTORCH_EXTENSION_NAME=_C -D_GLIBCXX_USE_CXX11_ABI=0 /std:c++14
      cl : Command line warning D9002 : ignoring unknown option '-std=c++14'
      C:\Users\Virtual Machine\AppData\Local\Programs\Python\Python310\lib\site-packages\torch\include\c10/macros/Macros.h(3): fatal error C1083: Cannot open include file: 'cassert': No such file or directory
      ninja: build stopped: subcommand failed.'''
</code>```

Also I am trying to use ninja but I get this error

```<code>        File "C:\Users\Virtual Machine\AppData\Local\Programs\Python\Python310\lib\site-packages\setuptools\command\build_ext.py", line 246, in build_extension
          _build_ext.build_extension(self, ext)
        File "C:\Users\Virtual Machine\AppData\Local\Programs\Python\Python310\lib\site-packages\setuptools\_distutils\command\build_ext.py", line 547, in build_extension
          objects = self.compiler.compile(
        File "C:\Users\Virtual Machine\AppData\Local\Programs\Python\Python310\lib\site-packages\torch\utils\cpp_extension.py", line 815, in win_wrap_ninja_compile
          _write_ninja_file_and_compile_objects(
        File "C:\Users\Virtual Machine\AppData\Local\Programs\Python\Python310\lib\site-packages\torch\utils\cpp_extension.py", line 1573, in _write_ninja_file_and_compile_objects
          _run_ninja_build(
        File "C:\Users\Virtual Machine\AppData\Local\Programs\Python\Python310\lib\site-packages\torch\utils\cpp_extension.py", line 1916, in _run_ninja_build
          raise RuntimeError(message) from e
      RuntimeError: Error compiling objects for extension
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: legacy-install-failure

× Encountered error while trying to install package.
╰─> pytorch3d
</code>```

Body:
I have been trying to download pytorch3d on my PC however it keeps failing. I believe its because of the c++ compiler but I am not sure.

FAILED: C:/Users/Virtual Machine/AppData/Local/Temp/pip-req-build-fu0xd6su/build/temp.win-amd64-cpython-310/Release/Users/Virtual Machine/AppData/Local/Temp/pip-req-build-fu0xd6su/pytorch3d/csrc/point_mesh/point_mesh_cpu.obj
      cl /showIncludes /nologo /O2 /W3 /GL /DNDEBUG /MD /MD /wd4819 /wd4251 /wd4244 /wd4267 /wd4275 /wd4018 /wd4190 /EHsc "-IC:\Users\Virtual Machine\AppData\Local\Temp\pip-req-build-fu0xd6su\pytorch3d\csrc" "-IC:\Users\Virtual Machine\AppData\Local\Programs\Python\Python310\lib\site-packages\torch\include" "-IC:\Users\Virtual Machine\AppData\Local\Programs\Python\Python310\lib\site-packages\torch\include\torch\csrc\api\include" "-IC:\Users\Virtual Machine\AppData\Local\Programs\Python\Python310\lib\site-packages\torch\include\TH" "-IC:\Users\Virtual Machine\AppData\Local\Programs\Python\Python310\lib\site-packages\torch\include\THC" "-IC:\Users\Virtual Machine\AppData\Local\Programs\Python\Python310\include" "-IC:\Users\Virtual Machine\AppData\Local\Programs\Python\Python310\Include" -c "C:\Users\Virtual Machine\AppData\Local\Temp\pip-req-build-fu0xd6su\pytorch3d\csrc\point_mesh\point_mesh_cpu.cpp" /Fo"C:\Users\Virtual Machine\AppData\Local\Temp\pip-req-build-fu0xd6su\build\temp.win-amd64-cpython-310\Release\Users\Virtual Machine\AppData\Local\Temp\pip-req-build-fu0xd6su\pytorch3d\csrc\point_mesh\point_mesh_cpu.obj" -std=c++14 -DTORCH_API_INCLUDE_EXTENSION_H -DTORCH_EXTENSION_NAME=_C -D_GLIBCXX_USE_CXX11_ABI=0 /std:c++14
      cl : Command line warning D9002 : ignoring unknown option '-std=c++14'
      C:\Users\Virtual Machine\AppData\Local\Programs\Python\Python310\lib\site-packages\torch\include\c10/macros/Macros.h(3): fatal error C1083: Cannot open include file: 'cassert': No such file or directory
      ninja: build stopped: subcommand failed.'''

Also I am trying to use ninja but I get this error

        File "C:\Users\Virtual Machine\AppData\Local\Programs\Python\Python310\lib\site-packages\setuptools\command\build_ext.py", line 246, in build_extension
          _build_ext.build_extension(self, ext)
        File "C:\Users\Virtual Machine\AppData\Local\Programs\Python\Python310\lib\site-packages\setuptools\_distutils\command\build_ext.py", line 547, in build_extension
          objects = self.compiler.compile(
        File "C:\Users\Virtual Machine\AppData\Local\Programs\Python\Python310\lib\site-packages\torch\utils\cpp_extension.py", line 815, in win_wrap_ninja_compile
          _write_ninja_file_and_compile_objects(
        File "C:\Users\Virtual Machine\AppData\Local\Programs\Python\Python310\lib\site-packages\torch\utils\cpp_extension.py", line 1573, in _write_ninja_file_and_compile_objects
          _run_ninja_build(
        File "C:\Users\Virtual Machine\AppData\Local\Programs\Python\Python310\lib\site-packages\torch\utils\cpp_extension.py", line 1916, in _run_ninja_build
          raise RuntimeError(message) from e
      RuntimeError: Error compiling objects for extension
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: legacy-install-failure

× Encountered error while trying to install package.
╰─> pytorch3d


问:
Dagger dependencies not getting in AndroidTest package
I am trying to get dagger component dependency in my AndroidTest package

Dependencies

implementation "com.google.dagger:dagger:$dagger_version"

kapt "com.google.dagger:dagger-compiler:$dagger_version"

debugImplementation 'androidx.test:runner:1.5.1'

debugImplementation 'androidx.test:rules:1.5.0'

debugImplementation "androidx.test:core-ktx:1.5.0"

kaptAndroidTest "com.google.dagger:dagger-compiler:$dagger_version"

Code in AndroidTest package

Component

@Singleton
@Component
interface TestUserComponent{
fun inject(myActivityTest: MyActivityTest)
}

Test file

class MyActivityTest {

lateinit var mTestUserComponent: TestUserComponent

@Before
fun setUp() {
mTestUserComponent = DaggerTestUserComponent.builder().build()
}

}

From above code I am not getting autogenerated file "DaggerTestUserComponent"


问:
SnowFlake DB deployment with GitLab-CI
I have multiple Snowflake accounts, having the DB creations and Stored procedures available on GitLab repo. Is there a right approach available to deploy the same using GitLab-CI where DB deploy versions can also be tracked and DB-RollBack also will be feasible.

As of now I am trying with Python on pipeline to connect snowflake and to execute SQL-Script files, and to rollback as well specific SQL are needed for clean-ups and rollback where on-demand rollback becomes a challenge.

Looking for a right approach or sample to refer.

Title: SnowFlake DB deployment with GitLab-CI


问:
Getting ndb debugger error to display the webpage
I've installed ndb on my linux machine globaly. While running the script with npm command npm run debug for ndb server.js. I'm getting an chrome window with error as shown in the screenshot.


问:
ImportError: cannot import name 'walk' from 'puresnmp' (/home/rojin/.local/lib/python3.10/site-packages/puresnmp/__init__.py)
I am trying to import walk from pure snmp but I am getting this import error. Most likely due to circular import? but I cannot seem to fix it. I am using python 3.10.6 on ubuntu 22.04.1 LTS. I tried reinstalling and import in various ways but I always get the same error. I am thinking of downgrading the python version maybe but I do not if it is the right way.</p>
```<code>from pysnmp.hlapi import *

from puresnmp import walk

IP = "10.10.10.254"
COMMUNITY = 'public'
OID = '1.3.6.1.2.1.2.2.1.2'

for row in walk(IP, COMMUNITY, OID):
    print(row)

IP = "10.10.10.254"
COMMUNITY = 'public'
OID = '1.3.6.1.2.1.2.2.1.8'

for row in walk(IP, COMMUNITY, OID):
    print(row)

#Indiviaual Reason on Switch/Router

g = getCmd(
    SnmpEngine(), CommunityData('public'), UdpTransportTarget(
        ('10.10.10.254', 161)), ContextData(), ObjectType(
            ObjectIdentity('1.3.6.1.2.1.2.2.1.2.10113')))
errorIndication, errorStatus, errorIndex, varBinds = next(g)
for varBind in varBinds:
    print(' = '.join([x.prettyPrint() for x in varBind]))

#Indiviaual Reason on Switch/Router

g = getCmd(
    SnmpEngine(), CommunityData('public'), UdpTransportTarget(
        ('10.10.10.254', 161)), ContextData(), ObjectType(
            ObjectIdentity('1.3.6.1.2.1.2.2.1.2.10113')))
errorIndication, errorStatus, errorIndex, varBinds = next(g)
for varBind in varBinds:
    print(' = '.join([x.prettyPrint() for x in varBind]))

#Reboot Reason on Switch/Router
g = getCmd(
    SnmpEngine(), CommunityData('public'), UdpTransportTarget(
        ('10.10.10.254', 161)), ContextData(), ObjectType(
            ObjectIdentity('1.3.6.1.4.1.9.2.1.2.0')))
errorIndication, errorStatus, errorIndex, varBinds = next(g)
for varBind in varBinds:
    print(' = '.join([x.prettyPrint() for x in varBind]))

#System Uptime on Switch/Router
g = getCmd(
    SnmpEngine(), CommunityData('public'), UdpTransportTarget(
        ('10.10.10.254', 161)), ContextData(), ObjectType(
            ObjectIdentity('1.3.6.1.2.1.1.3.0')))
errorIndication, errorStatus, errorIndex, varBinds = next(g)
for varBind in varBinds:
    print(' = '.join([x.prettyPrint() for x in varBind]))

#Power Value
g = getCmd(
    SnmpEngine(), CommunityData('public'), UdpTransportTarget(
        ('10.10.10.254', 161)), ContextData(), ObjectType(
            ObjectIdentity('1.3.6.1.4.1.9.9.13.1.5.1.3.1006')))
errorIndication, errorStatus, errorIndex, varBinds = next(g)
for varBind in varBinds:
    print(' = '.join([x.prettyPrint() for x in varBind]))

#FAN Value
g = getCmd(
    SnmpEngine(), CommunityData('public'), UdpTransportTarget(
        ('10.10.10.254', 161)), ContextData(), ObjectType(
            ObjectIdentity('1.3.6.1.4.1.9.9.13.1.4.1.3.1007')))
errorIndication, errorStatus, errorIndex, varBinds = next(g)
for varBind in varBinds:
    print(' = '.join([x.prettyPrint() for x in varBind]))

#System Temperature Value
g = getCmd(
    SnmpEngine(), CommunityData('public'), UdpTransportTarget(
        ('10.10.10.254', 161)), ContextData(), ObjectType(
            ObjectIdentity('1.3.6.1.4.1.9.9.13.1.3.1.3.1008')))
errorIndication, errorStatus, errorIndex, varBinds = next(g)
for varBind in varBinds:
    print(' = '.join([x.prettyPrint() for x in varBind]))

#Monitoring CPU on Switch/Router
g = getCmd(
    SnmpEngine(), CommunityData('public'), UdpTransportTarget(
        ('10.10.10.254', 161)), ContextData(), ObjectType(
            ObjectIdentity('1.3.6.1.4.1.9.2.1.58.0')))
errorIndication, errorStatus, errorIndex, varBinds = next(g)
for varBind in varBinds:
    print(' = '.join([x.prettyPrint() for x in varBind]))

#Monitoring Memory on Switch/Router
g = getCmd(
    SnmpEngine(), CommunityData('public'), UdpTransportTarget(
        ('10.10.10.254', 161)), ContextData(), ObjectType(
            ObjectIdentity('1.3.6.1.4.1.9.9.48.1.1.1.6.1')))
errorIndication, errorStatus, errorIndex, varBinds = next(g)
for varBind in varBinds:
    print(' = '.join([x.prettyPrint() for x in varBind]))

#Version Detail of Switch/Router
g = getCmd(
    SnmpEngine(), CommunityData('public'), UdpTransportTarget(
        ('10.10.10.254', 161)), ContextData(), ObjectType(
            ObjectIdentity('1.3.6.1.2.1.1.1.0')))
errorIndication, errorStatus, errorIndex, varBinds = next(g)
for varBind in varBinds:
    print(' = '.join([x.prettyPrint() for x in varBind]))

#Total Number of Interfaces/Vlan
g = getCmd(
    SnmpEngine(), CommunityData('public'), UdpTransportTarget(
        ('10.10.10.254', 161)), ContextData(), ObjectType(
            ObjectIdentity('1.3.6.1.2.1.2.1.0')))
errorIndication, errorStatus, errorIndex, varBinds = next(g)
for varBind in varBinds:
    print(' = '.join([x.prettyPrint() for x in varBind]))
</code>```

Body:
I am trying to import walk from pure snmp but I am getting this import error. Most likely due to circular import? but I cannot seem to fix it. I am using python 3.10.6 on ubuntu 22.04.1 LTS. I tried reinstalling and import in various ways but I always get the same error. I am thinking of downgrading the python version maybe but I do not if it is the right way.

from pysnmp.hlapi import *

from puresnmp import walk

IP = "10.10.10.254"
COMMUNITY = 'public'
OID = '1.3.6.1.2.1.2.2.1.2'

for row in walk(IP, COMMUNITY, OID):
    print(row)

IP = "10.10.10.254"
COMMUNITY = 'public'
OID = '1.3.6.1.2.1.2.2.1.8'

for row in walk(IP, COMMUNITY, OID):
    print(row)

#Indiviaual Reason on Switch/Router

g = getCmd(
    SnmpEngine(), CommunityData('public'), UdpTransportTarget(
        ('10.10.10.254', 161)), ContextData(), ObjectType(
            ObjectIdentity('1.3.6.1.2.1.2.2.1.2.10113')))
errorIndication, errorStatus, errorIndex, varBinds = next(g)
for varBind in varBinds:
    print(' = '.join([x.prettyPrint() for x in varBind]))

#Indiviaual Reason on Switch/Router

g = getCmd(
    SnmpEngine(), CommunityData('public'), UdpTransportTarget(
        ('10.10.10.254', 161)), ContextData(), ObjectType(
            ObjectIdentity('1.3.6.1.2.1.2.2.1.2.10113')))
errorIndication, errorStatus, errorIndex, varBinds = next(g)
for varBind in varBinds:
    print(' = '.join([x.prettyPrint() for x in varBind]))

#Reboot Reason on Switch/Router
g = getCmd(
    SnmpEngine(), CommunityData('public'), UdpTransportTarget(
        ('10.10.10.254', 161)), ContextData(), ObjectType(
            ObjectIdentity('1.3.6.1.4.1.9.2.1.2.0')))
errorIndication, errorStatus, errorIndex, varBinds = next(g)
for varBind in varBinds:
    print(' = '.join([x.prettyPrint() for x in varBind]))

#System Uptime on Switch/Router
g = getCmd(
    SnmpEngine(), CommunityData('public'), UdpTransportTarget(
        ('10.10.10.254', 161)), ContextData(), ObjectType(
            ObjectIdentity('1.3.6.1.2.1.1.3.0')))
errorIndication, errorStatus, errorIndex, varBinds = next(g)
for varBind in varBinds:
    print(' = '.join([x.prettyPrint() for x in varBind]))

#Power Value
g = getCmd(
    SnmpEngine(), CommunityData('public'), UdpTransportTarget(
        ('10.10.10.254', 161)), ContextData(), ObjectType(
            ObjectIdentity('1.3.6.1.4.1.9.9.13.1.5.1.3.1006')))
errorIndication, errorStatus, errorIndex, varBinds = next(g)
for varBind in varBinds:
    print(' = '.join([x.prettyPrint() for x in varBind]))

#FAN Value
g = getCmd(
    SnmpEngine(), CommunityData('public'), UdpTransportTarget(
        ('10.10.10.254', 161)), ContextData(), ObjectType(
            ObjectIdentity('1.3.6.1.4.1.9.9.13.1.4.1.3.1007')))
errorIndication, errorStatus, errorIndex, varBinds = next(g)
for varBind in varBinds:
    print(' = '.join([x.prettyPrint() for x in varBind]))

#System Temperature Value
g = getCmd(
    SnmpEngine(), CommunityData('public'), UdpTransportTarget(
        ('10.10.10.254', 161)), ContextData(), ObjectType(
            ObjectIdentity('1.3.6.1.4.1.9.9.13.1.3.1.3.1008')))
errorIndication, errorStatus, errorIndex, varBinds = next(g)
for varBind in varBinds:
    print(' = '.join([x.prettyPrint() for x in varBind]))

#Monitoring CPU on Switch/Router
g = getCmd(
    SnmpEngine(), CommunityData('public'), UdpTransportTarget(
        ('10.10.10.254', 161)), ContextData(), ObjectType(
            ObjectIdentity('1.3.6.1.4.1.9.2.1.58.0')))
errorIndication, errorStatus, errorIndex, varBinds = next(g)
for varBind in varBinds:
    print(' = '.join([x.prettyPrint() for x in varBind]))

#Monitoring Memory on Switch/Router
g = getCmd(
    SnmpEngine(), CommunityData('public'), UdpTransportTarget(
        ('10.10.10.254', 161)), ContextData(), ObjectType(
            ObjectIdentity('1.3.6.1.4.1.9.9.48.1.1.1.6.1')))
errorIndication, errorStatus, errorIndex, varBinds = next(g)
for varBind in varBinds:
    print(' = '.join([x.prettyPrint() for x in varBind]))

#Version Detail of Switch/Router
g = getCmd(
    SnmpEngine(), CommunityData('public'), UdpTransportTarget(
        ('10.10.10.254', 161)), ContextData(), ObjectType(
            ObjectIdentity('1.3.6.1.2.1.1.1.0')))
errorIndication, errorStatus, errorIndex, varBinds = next(g)
for varBind in varBinds:
    print(' = '.join([x.prettyPrint() for x in varBind]))

#Total Number of Interfaces/Vlan
g = getCmd(
    SnmpEngine(), CommunityData('public'), UdpTransportTarget(
        ('10.10.10.254', 161)), ContextData(), ObjectType(
            ObjectIdentity('1.3.6.1.2.1.2.1.0')))
errorIndication, errorStatus, errorIndex, varBinds = next(g)
for varBind in varBinds:
    print(' = '.join([x.prettyPrint() for x in varBind]))


问:
FileNotFoundError: [Errno 2] No such file or directory: 'Users/apple/Desktop/Employee+Sample+Data/Employee\\ Sample\\ Data.csv'
I know this question has been asked before, but I am unable to solve this problem
I also know this happens when my python file is not in the same directory has my data file.
when I do

```<code>     import os
     os.getcwd()
</code>```

it gives file path as:-

```<code>/Users/apple/PycharmProjects/pythonProject4/venv/bin/python /Users/apple/PycharmProjects/pythonProject4/main.py
</code>```

now when I do:-

```<code>      os.chdir("Users/apple/Desktop/Employee+Sample+Data/Employee\ Sample\ Data.csv")
</code>```

i.e. I try to change the directory of my python in the same directory as my file exists it shows error:-

```<code>  FileNotFoundError: [Errno 2] No such file or directory: 'Users/apple/Desktop/Employee+Sample+Data/Employee\\ Sample\\ Data.csv'
</code>```

I have been stuck with it for days. I tried everything on stackoverflow and other forums but no avail. I am using Pycharm. Please help me.

Body:
I know this question has been asked before, but I am unable to solve this problem
I also know this happens when my python file is not in the same directory has my data file.
when I do

     import os
     os.getcwd()

it gives file path as:-

/Users/apple/PycharmProjects/pythonProject4/venv/bin/python /Users/apple/PycharmProjects/pythonProject4/main.py

now when I do:-

      os.chdir("Users/apple/Desktop/Employee+Sample+Data/Employee\ Sample\ Data.csv")

i.e. I try to change the directory of my python in the same directory as my file exists it shows error:-

  FileNotFoundError: [Errno 2] No such file or directory: 'Users/apple/Desktop/Employee+Sample+Data/Employee\\ Sample\\ Data.csv'

I have been stuck with it for days. I tried everything on stackoverflow and other forums but no avail. I am using Pycharm. Please help me.


问:
RK4 in 2D gravity simulation probs
In actionscript 3.0, I have two objects (a central red star and a orbiting blue planet). I want to use RK4 to plot the orbit. I'm running the simulation once per frame, and drawing once per frame. I have to relate the position of the blue planet in x,y to the central planet so I may be getting lost in the conversion somewhere. This is just for the 1,1 quadrant.  I will be adjusting the gravity vector as the blue planet crosses from quadrant to quadrant.

PROBLEM: If I alter the time step, the orbit changes drastically.  At small time steps, the orbit becomes a straight line.  At large time steps, the orbit becomes tighter.  The cooefficients for computing the acceleration for each "K" are not being scaled by dt (except for it being passed through the previous velocity vector).

Here is the RK4 code snip:

http://pastebin.com/Ee6HzBQ2

ContentLicense: CC BY-SA 3.0

Title: RK4 in 2D gravity simulation probs


问:
Using nice command on gunicorn service workers
I have a service:

```<code>[Unit]
Description=tweetsift

After=network.target

[Service]
User=root
Group=root
WorkingDirectory=/var/www/html
ExecStart=sudo /usr/bin/nice -n -20 sudo -u root sudo gunicorn -w 4 -b 0.0.0.0:5000 endpoint:app

Restart=on-failure

[Install]
WantedBy=multi-user.target
</code>```

When I run sudo systemctl status tweet I see that I am using /usr/bin/nice for the main PID. However it is not taking on the workers.

```<code> tweetsift.service - tweet
     Loaded: loaded (/etc/systemd/system/tweet.service; enabled; preset: enabled)
     Active: active (running) since Mon 2023-01-09 04:36:08 UTC; 5min ago
   Main PID: 3124 (sudo)
      Tasks: 12 (limit: 4661)
     Memory: 702.8M
        CPU: 7.580s
     CGroup: /system.slice/tweet.service
             ├─3124 sudo /usr/bin/nice -n -20 sudo -u root sudo gunicorn -w 4 -b 0.0.0.0:5000 endpoint:app
             ├─3125 sudo -u root sudo gunicorn -w 4 -b 0.0.0.0:5000 endpoint:app
             ├─3126 sudo gunicorn -w 4 -b 0.0.0.0:5000 endpoint:app
             ├─3127 /usr/bin/python3 /usr/local/bin/gunicorn -w 4 -b 0.0.0.0:5000 endpoint:app
             ├─3128 /usr/bin/python3 /usr/local/bin/gunicorn -w 4 -b 0.0.0.0:5000 endpoint:app
             ├─3129 /usr/bin/python3 /usr/local/bin/gunicorn -w 4 -b 0.0.0.0:5000 endpoint:app
             ├─3130 /usr/bin/python3 /usr/local/bin/gunicorn -w 4 -b 0.0.0.0:5000 endpoint:app
             └─3131 /usr/bin/python3 /usr/local/bin/gunicorn -w 4 -b 0.0.0.0:5000 endpoint:app
</code>```

I am running a machine learning script that sucks down the CPU. I tried using nice python3 tweet.py and it works and doesn't kill the process.

However, when I try call the api endpoint I built. The service starts up using a worker and then gets killed for OOM (Out of Memory).

I am using Ubuntu 20.04 & Apache2

Any ideas? I was able to get nice running on the main PID by updating the /etc/sudoers/ and adding a line to allow sudo to use it.

But I still can't get the script to run as a service using nice for the workers PIDs too when they start up upon an API call to the flask app I've got running.

I am using gunicorn (version 20.1.0)

Thanks!

I've tried everything at this point. I want nice to be applied to gunicorn workers when my flask app has an api call sent to it without getting killed for OOM.

I'm using a 4GB Intel 80GB Disk premium intel droplet on DigitalOcean.

Body:
I have a service:

[Unit]
Description=tweetsift

After=network.target

[Service]
User=root
Group=root
WorkingDirectory=/var/www/html
ExecStart=sudo /usr/bin/nice -n -20 sudo -u root sudo gunicorn -w 4 -b 0.0.0.0:5000 endpoint:app

Restart=on-failure

[Install]
WantedBy=multi-user.target

When I run sudo systemctl status tweet I see that I am using /usr/bin/nice for the main PID. However it is not taking on the workers.

 tweetsift.service - tweet
     Loaded: loaded (/etc/systemd/system/tweet.service; enabled; preset: enabled)
     Active: active (running) since Mon 2023-01-09 04:36:08 UTC; 5min ago
   Main PID: 3124 (sudo)
      Tasks: 12 (limit: 4661)
     Memory: 702.8M
        CPU: 7.580s
     CGroup: /system.slice/tweet.service
             ├─3124 sudo /usr/bin/nice -n -20 sudo -u root sudo gunicorn -w 4 -b 0.0.0.0:5000 endpoint:app
             ├─3125 sudo -u root sudo gunicorn -w 4 -b 0.0.0.0:5000 endpoint:app
             ├─3126 sudo gunicorn -w 4 -b 0.0.0.0:5000 endpoint:app
             ├─3127 /usr/bin/python3 /usr/local/bin/gunicorn -w 4 -b 0.0.0.0:5000 endpoint:app
             ├─3128 /usr/bin/python3 /usr/local/bin/gunicorn -w 4 -b 0.0.0.0:5000 endpoint:app
             ├─3129 /usr/bin/python3 /usr/local/bin/gunicorn -w 4 -b 0.0.0.0:5000 endpoint:app
             ├─3130 /usr/bin/python3 /usr/local/bin/gunicorn -w 4 -b 0.0.0.0:5000 endpoint:app
             └─3131 /usr/bin/python3 /usr/local/bin/gunicorn -w 4 -b 0.0.0.0:5000 endpoint:app

I am running a machine learning script that sucks down the CPU. I tried using nice python3 tweet.py and it works and doesn't kill the process.

However, when I try call the api endpoint I built. The service starts up using a worker and then gets killed for OOM (Out of Memory).

I am using Ubuntu 20.04 & Apache2

Any ideas? I was able to get nice running on the main PID by updating the /etc/sudoers/ and adding a line to allow sudo to use it.

But I still can't get the script to run as a service using nice for the workers PIDs too when they start up upon an API call to the flask app I've got running.

I am using gunicorn (version 20.1.0)

Thanks!

I've tried everything at this point. I want nice to be applied to gunicorn workers when my flask app has an api call sent to it without getting killed for OOM.

I'm using a 4GB Intel 80GB Disk premium intel droplet on DigitalOcean.


问:
understanding confusion matrix and classification report (*Logistic Regression model)
I would like to know if the result is quite reasonable for logistics regression model to predict churn for markteting

Confusion Matrix

[[ 14  31]
[  8 146]]

**              precision    recall  f1-score   support**

```<code>       0       0.64      0.31      0.42        45
       1       0.82      0.95      0.88       154

accuracy                           0.80       199
</code>```

macro avg       0.73      0.63      0.65       199
weighted avg       0.78      0.80      0.78       199

0 = not churn
1 = churn

The reason I ask for this question is I'm not sure that though the accuracy is not that bad, the performance of model could deem good

if you look at the confusion matrix, the point such as 31(FP) seems relatively big

Thank you for sharing your understanding in advance.

I check this blog posting to undertsand but I'm not sure I can still see the accuracy is good

https://towardsdatascience.com/understanding-confusion-matrix-a9ad42dcfd62

Body:
I would like to know if the result is quite reasonable for logistics regression model to predict churn for markteting

Confusion Matrix

[[ 14  31]
[  8 146]]

**              precision    recall  f1-score   support**

       0       0.64      0.31      0.42        45
       1       0.82      0.95      0.88       154

accuracy                           0.80       199

macro avg       0.73      0.63      0.65       199
weighted avg       0.78      0.80      0.78       199

0 = not churn
1 = churn

The reason I ask for this question is I'm not sure that though the accuracy is not that bad, the performance of model could deem good

if you look at the confusion matrix, the point such as 31(FP) seems relatively big

Thank you for sharing your understanding in advance.

I check this blog posting to undertsand but I'm not sure I can still see the accuracy is good

https://towardsdatascience.com/understanding-confusion-matrix-a9ad42dcfd62


问:
django-test-migrations failing when using multiple postgres schemas in django
I am using local postgres 12 db.
I have 2 models:

```<code>class CustomUser2(models.Model):
    name = models.CharField(max_length=100)

class CustomUser3(models.Model):
    name = models.CharField(max_length=100)

    class Meta:
        db_table = 'schema1\".\"custom_user_3'
</code>```

I run following test:

from django_test_migrations.contrib.unittest_case import MigratorTestCase

```<code>class TestDirectMigration(MigratorTestCase):
    """This class is used to test direct migrations."""

    migrate_from = ('core', '0002_customuser2')
    migrate_to = ('core', '0003_customuser3')

    def prepare(self):
        """Prepare some data before the migration."""
        SomeItem = self.old_state.apps.get_model('core', 'CustomUser2')

    def test_migration_main0003(self):
        """Run the test itself."""
        SomeItem = self.new_state.apps.get_model('core', 'CustomUser2')
</code>```

I get following error:

```<code>django.db.utils.ProgrammingError: relation "custom_user_3" already exists
</code>```

Is there a way to test migrations when using different schemas in django + postgres ?

Body:
I am using local postgres 12 db.
I have 2 models:

class CustomUser2(models.Model):
    name = models.CharField(max_length=100)

class CustomUser3(models.Model):
    name = models.CharField(max_length=100)

    class Meta:
        db_table = 'schema1\".\"custom_user_3'

I run following test:

from django_test_migrations.contrib.unittest_case import MigratorTestCase

class TestDirectMigration(MigratorTestCase):
    """This class is used to test direct migrations."""

    migrate_from = ('core', '0002_customuser2')
    migrate_to = ('core', '0003_customuser3')

    def prepare(self):
        """Prepare some data before the migration."""
        SomeItem = self.old_state.apps.get_model('core', 'CustomUser2')

    def test_migration_main0003(self):
        """Run the test itself."""
        SomeItem = self.new_state.apps.get_model('core', 'CustomUser2')

I get following error:

django.db.utils.ProgrammingError: relation "custom_user_3" already exists

Is there a way to test migrations when using different schemas in django + postgres ?


问:
Search for text and highlight within a PDFKitView
I am trying to create a pdfviewer that will allow for entering text into a textbox, and then highlight that entered text within the view.

```<code>
struct PDFKitRepresentedView: UIViewRepresentable {
    typealias UIViewType = PDFView
    let url: URL
    @Binding var pageNum: Int
    @Binding var currentPage: Int
    let isPreview: Bool
    let pdfView = PDFView()
    let inputText: String?

    func makeUIView(context: Context) -> UIViewType {
        pdfView.document = PDFDocument(url: self.url)
        pdfView.displayMode = .singlePage
        pdfView.autoScales = true
        if !isPreview {
            pdfView.displayDirection = .horizontal
            pdfView.usePageViewController(true)
        }
        return pdfView
    }

    func search(searchText: String) {
        print("Searching \(searchText)")
        let selectionList = pdfView.document?.findString(searchText, withOptions: NSString.CompareOptions.caseInsensitive)
//        print(selectionList)
        guard let page = selectionList?.first?.pages.first else { return }
        pdfView.go(to: page)
        selectionList?.forEach({ selection in
            selection.pages.forEach { page in
                let highlight = PDFAnnotation(bounds: selection.bounds(for: page), forType: .highlight, withProperties: nil)
                    highlight.endLineStyle = .square
                    highlight.color = UIColor.orange.withAlphaComponent(0.5)
                    page.addAnnotation(highlight)
            }

        })
    }

    func updateUIView(_ pdfView: UIViewType, context _: Context) {
        pdfView.document = PDFDocument(url: self.url)
    }
}

</code>```

I have called the search function from my swiftui view, but the pdfView comes back as nil.

Body:
I am trying to create a pdfviewer that will allow for entering text into a textbox, and then highlight that entered text within the view.

struct PDFKitRepresentedView: UIViewRepresentable {
    typealias UIViewType = PDFView
    let url: URL
    @Binding var pageNum: Int
    @Binding var currentPage: Int
    let isPreview: Bool
    let pdfView = PDFView()
    let inputText: String?

    func makeUIView(context: Context) -> UIViewType {
        pdfView.document = PDFDocument(url: self.url)
        pdfView.displayMode = .singlePage
        pdfView.autoScales = true
        if !isPreview {
            pdfView.displayDirection = .horizontal
            pdfView.usePageViewController(true)
        }
        return pdfView
    }

    func search(searchText: String) {
        print("Searching \(searchText)")
        let selectionList = pdfView.document?.findString(searchText, withOptions: NSString.CompareOptions.caseInsensitive)
//        print(selectionList)
        guard let page = selectionList?.first?.pages.first else { return }
        pdfView.go(to: page)
        selectionList?.forEach({ selection in
            selection.pages.forEach { page in
                let highlight = PDFAnnotation(bounds: selection.bounds(for: page), forType: .highlight, withProperties: nil)
                    highlight.endLineStyle = .square
                    highlight.color = UIColor.orange.withAlphaComponent(0.5)
                    page.addAnnotation(highlight)
            }

        })
    }

    func updateUIView(_ pdfView: UIViewType, context _: Context) {
        pdfView.document = PDFDocument(url: self.url)
    }
}

I have called the search function from my swiftui view, but the pdfView comes back as nil.


问:
Make DOM load in web_sys
How would I modify this to get the result below? The thing is there is no iterable. I am not sure what I am doing at this point as this code was AI generated. But my desired result it the js code snippet below.

```<code>use web_sys::{Element, HtmlElement};

fn init_dropdowns() -> Result<(), JsValue> {
  let elems = web_sys::window()
    .unwrap()
    .document()
    .unwrap()
    .query_selector_all(".dropdown-trigger")?;

  let elems: Vec<Element> = elems
    .into_iter()
    .map(|elem| elem.unwrap())
    .collect();

  let elems: Vec<HtmlElement> = elems
    .into_iter()
    .map(|elem| elem.dyn_into::<HtmlElement>().unwrap())
    .collect();

  M::Dropdown::init(elems.as_ref(), &JsValue::NULL);

  Ok(())
}
</code>```

Here is a what I would like it to be like

```<code> document.addEventListener('DOMContentLoaded', function() {
        var elems = document.querySelectorAll('.dropdown-trigger');
        var instances = M.Dropdown.init(elems);
        });
</code>```

Title: Make DOM load in web_sys

Body:
How would I modify this to get the result below? The thing is there is no iterable. I am not sure what I am doing at this point as this code was AI generated. But my desired result it the js code snippet below.

use web_sys::{Element, HtmlElement};

fn init_dropdowns() -> Result<(), JsValue> {
  let elems = web_sys::window()
    .unwrap()
    .document()
    .unwrap()
    .query_selector_all(".dropdown-trigger")?;

  let elems: Vec<Element> = elems
    .into_iter()
    .map(|elem| elem.unwrap())
    .collect();

  let elems: Vec<HtmlElement> = elems
    .into_iter()
    .map(|elem| elem.dyn_into::<HtmlElement>().unwrap())
    .collect();

  M::Dropdown::init(elems.as_ref(), &JsValue::NULL);

  Ok(())
}

Here is a what I would like it to be like

 document.addEventListener('DOMContentLoaded', function() {
        var elems = document.querySelectorAll('.dropdown-trigger');
        var instances = M.Dropdown.init(elems);
        });


问:
Android force app to wait until asynchronous work in onCreate is finished before starting first activity, also when first activity is not splash
I have a Splash activity and a Loading activity. Then the current idea when the app is started normally (from the app icon in phone home screen) is having the Splash activity show initially and then have Loading activity display an animation until app asynchronous initialization is finished. Then the first Relevant activity is launched.

This is working ok, but the problem arrives when I want to start the app from some implicit or explicit intent (example: click on a notification after app has been killed) that targets an activity other than the Splash activity. Aforementioned activity flow does not happen, and so the Relevant activity starts before the asynchronous app initialization is finished.

I have been thinking about how to fix this, and I came up with this idea:

Make sure that all requests that come from outside the app to start an activity, target the Splash activity so that normal initialization can happen. Then pass the intent through to the Relevant activity.

I believe that this could make the app's logic more complex, and I could still find unforeseen problems, so I would like to find a simpler/better alternative. Any ideas?

Thanks in advance.


问:
MinGW-w64 link with Windows system libraries undefined reference
I installed msys2 and I'm using the UCRT64 environment that comes with it. I installed the mingw-w64-ucrt-x86_64-toolchain group of packages, which I am using to compile C++.

I have a file which compiles as a static library libtestwin64.a and contains this:

```<code>#include <windows.h> // contains <winuser.h> <wingdi.h>

void funcA() {
    HDC dc = GetDC(NULL); // references to <winuser.h> cause no error.
    HCOLORSPACE hcs = GetColorSpace(dc); // references to <wingdi.h> cause error.
}
</code>```

When I try to link with libtestwin64.a and compile an executable g++ -I../mirr/inc   obj/Win64/three.o obj/Win64/four.o -o ../bin/test64.exe -luser32 -lgdi32 -L../mirr/lib  -ltestwin64, it causes these undefined reference errors for anything from wingdi.h:

```<code>D:/software/msys/ucrt64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe:
../mirr/lib/libtestwin64.a(one.o):one.cpp:(.text+0xfd): undefined reference to `__imp_GetColorSpace'
</code>```

ld.exe reports no error about finding the files libgdi32.a etc. Adding options like -lgdi32 to the linker doesn't change the result. Other system libraries like libuser32.a cause no error.

What can I do to use functions from Windows GDI through msys2?

Body:
I installed msys2 and I'm using the UCRT64 environment that comes with it. I installed the mingw-w64-ucrt-x86_64-toolchain group of packages, which I am using to compile C++.

I have a file which compiles as a static library libtestwin64.a and contains this:

#include <windows.h> // contains <winuser.h> <wingdi.h>

void funcA() {
    HDC dc = GetDC(NULL); // references to <winuser.h> cause no error.
    HCOLORSPACE hcs = GetColorSpace(dc); // references to <wingdi.h> cause error.
}

When I try to link with libtestwin64.a and compile an executable g++ -I../mirr/inc   obj/Win64/three.o obj/Win64/four.o -o ../bin/test64.exe -luser32 -lgdi32 -L../mirr/lib  -ltestwin64, it causes these undefined reference errors for anything from wingdi.h:

D:/software/msys/ucrt64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe:
../mirr/lib/libtestwin64.a(one.o):one.cpp:(.text+0xfd): undefined reference to `__imp_GetColorSpace'

ld.exe reports no error about finding the files libgdi32.a etc. Adding options like -lgdi32 to the linker doesn't change the result. Other system libraries like libuser32.a cause no error.

What can I do to use functions from Windows GDI through msys2?


问:
Arabic Numbers converted to question marks in Oracle Database 21c EE
I am trying to insert Arabic numbers in my client database. But the database is converting those Arabic numbers into questions marks (?). I am not facing any issues while storing Arabic letters in the same DB. The DBA is like there is some issue with the characters I am passing. But I didn't have any issues when I inserted the same Arabic numbers in MySQL database.

**Version of Database: *Oracle Database 21c EE Extreme Perf
Release 21.0.0.0.0 - Production*

NLS_CHARACTERSET:   *AR8ISO8859P6*

Arabic numbers (converted to?): *٨٥٤٣٣٨٦٣ *

Arabic letters (no issue at all): ذثجج**


问:
P-table of Lazy load when we sort it always goes offset page 1, when i was on page 3 or 4
When iam any other page 2 or 3, if i click on Sort of lazy , its shows data of 2 or 3 only but why always the page shows first page offset 0.

In lazy mode it always show ,which ever page i was there , should not navigate to offset page 1


问:
Server could not create ASP.reporting_reportvalueprediction_aspx
I am binding RDLC Report viewer in my project but getting this error

Server could not create ASP.reporting_reportvalueprediction_aspx.

Exception Details: System.InvalidOperationException: Server could not create ASP.reporting_reportvalueprediction_aspx.

Stack Trace:

[InvalidOperationException: Server could not create ASP.reporting_reportvalueprediction_aspx.]
__ASP.FastObjectFactory_app_web_sxcnkdic.Create_ASP_reporting_reportvalueprediction_aspx() +192
System.Web.Compilation.BuildResultCompiledType.CreateInstance() +31
System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(VirtualPath virtualPath, Type requiredBaseType, HttpContext context, Boolean allowCrossApp) +104
System.Web.UI.PageHandlerFactory.GetHandlerHelper(HttpContext context, String requestType, VirtualPath virtualPath, String physicalPath) +33
System.Web.UI.PageHandlerFactory.GetHandler(HttpContext context, String requestType, String virtualPath, String path) +39
System.Web.MaterializeHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +386
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +50
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +163

```<code>`<%@ Page Language="vb" Debug="true" AutoEventWireup="false" CodeBehind="ReportValuePrediction.aspx.vb" Inherits="TimiWeb.ReportValuePrediction" %>
<%@ Register Assembly="Microsoft.ReportViewer.WebForms, Version=15.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"
    Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager" runat="server">
        </asp:ScriptManager>
        <div>

            <rsweb:ReportViewer ID="rptReportViewer" runat="server" Width="100%" Height="700px">
            </rsweb:ReportViewer>
        </div>
    </form>
</body>
</html>`
</code>```

**
I write these VB code to bind report**

```<code>Imports Microsoft.Reporting.WebForms

Public Class ReportValuePrediction
    Inherits System.Web.UI.Page
    Private _dt As DataTable
    Public Sub New(ByVal dt As DataTable)

        _dt = dt

    End Sub
    Protected Sub Page_Load(sender As Object, e As EventArgs)

        If Not IsPostBack Then
            Dim rep As LocalReport = rptReportViewer.LocalReport
            rep.ReportPath = "/Reporting/ValuePrediction.rdlc"
            Dim rds As New ReportDataSource()

            If _dt.Rows.Count > 0 Then
                rds.Name = "ValuePredictionDS"
                rds.Value = _dt
                rep.DataSources.Add(rds)
            End If
        End If

    End Sub

End Class
</code>```

Body:
I am binding RDLC Report viewer in my project but getting this error

Server could not create ASP.reporting_reportvalueprediction_aspx.

Exception Details: System.InvalidOperationException: Server could not create ASP.reporting_reportvalueprediction_aspx.

Stack Trace:

[InvalidOperationException: Server could not create ASP.reporting_reportvalueprediction_aspx.]
__ASP.FastObjectFactory_app_web_sxcnkdic.Create_ASP_reporting_reportvalueprediction_aspx() +192
System.Web.Compilation.BuildResultCompiledType.CreateInstance() +31
System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(VirtualPath virtualPath, Type requiredBaseType, HttpContext context, Boolean allowCrossApp) +104
System.Web.UI.PageHandlerFactory.GetHandlerHelper(HttpContext context, String requestType, VirtualPath virtualPath, String physicalPath) +33
System.Web.UI.PageHandlerFactory.GetHandler(HttpContext context, String requestType, String virtualPath, String path) +39
System.Web.MaterializeHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +386
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +50
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +163

`<%@ Page Language="vb" Debug="true" AutoEventWireup="false" CodeBehind="ReportValuePrediction.aspx.vb" Inherits="TimiWeb.ReportValuePrediction" %>
<%@ Register Assembly="Microsoft.ReportViewer.WebForms, Version=15.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"
    Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>

<!DOCTYPE html>

    <title></title>

    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager" runat="server">
        </asp:ScriptManager>

            <rsweb:ReportViewer ID="rptReportViewer" runat="server" Width="100%" Height="700px">
            </rsweb:ReportViewer>

    </form>

`

**
I write these VB code to bind report**

Imports Microsoft.Reporting.WebForms

Public Class ReportValuePrediction
    Inherits System.Web.UI.Page
    Private _dt As DataTable
    Public Sub New(ByVal dt As DataTable)

        _dt = dt

    End Sub
    Protected Sub Page_Load(sender As Object, e As EventArgs)

        If Not IsPostBack Then
            Dim rep As LocalReport = rptReportViewer.LocalReport
            rep.ReportPath = "/Reporting/ValuePrediction.rdlc"
            Dim rds As New ReportDataSource()

            If _dt.Rows.Count > 0 Then
                rds.Name = "ValuePredictionDS"
                rds.Value = _dt
                rep.DataSources.Add(rds)
            End If
        End If

    End Sub

End Class


问:
url tag not finding existing 'google_login' view function of django-allauth
I have a simple HTML content point towards the Google Login, as below.

```<code># foo.html

<a class="p-2 text-dark" href="{% url 'google_login' %}">Google Login</a>
</code>```

This simple demo project was using django==3.2.x and django-allauth==0.43.x. Recently, I have upgraded packages to the latest versions, viz, django==4.1.x and django-allauth==0.52.x.

After the upgrade, I was getting the following error -

Reverse for 'google_login' not found. 'google_login' is not a valid view function or pattern name.

I have confirmed the google_login is present by executing the reverse(...) function from the shell.

```<code>In [1]: from django.urls import  reverse

In [2]: reverse("google_login")
Out[2]: '/accounts/google/login/'
</code>```

Error traceback

```<code>Environment:

Request Method: GET
Request URL: http://127.0.0.1:1234/

Django Version: 4.1.5
Python Version: 3.9.11
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'whitenoise.runserver_nostatic',
 'django.contrib.staticfiles',
 'django.contrib.sites',
 'allauth',
 'allauth.account',
 'allauth.socialaccount',
 'allauth.socialaccount.providers.google',
 'crispy_forms',
 'debug_toolbar',
 'drf_yasg',
 'django_extensions',
 'rest_framework',
 'drf_spectacular',
 'accounts',
 'pages',
 'polls',
 'extra',
 'attendance']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'whitenoise.middleware.WhiteNoiseMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'debug_toolbar.middleware.DebugToolbarMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Template error:
In template /home/jpg/work-dir/projects/-personal/generic-django-example/templates/_base.html, error at line 32
   Reverse for 'google_login' not found. 'google_login' is not a valid view function or pattern name.
   22 :         <link rel="stylesheet" href="{% static 'css/base.css' %}">
   23 :     {% endblock %}
   24 : </head>
   25 :
   26 : <body>
   27 : <main role="main">
   28 :     <div class="d-flex flex-column flex-md-row align-items-center p-3 px-md-4 mb-3 bg-white border-bottom shadow-sm">
   29 :         <h5 class="my-0 mr-md-auto font-weight-normal">
   30 :             <a href="{% url 'home' %}">DjangoX</a>
   31 :         </h5>
   32 :         <a class="p-2 text-dark" href=" {% url 'google_login' %} ">Google Login</a>
   33 :         <a class="p-2 text-dark" href="{% url 'polls-api:api-root' %}">Polls APIs</a>
   34 :         <a class="p-2 text-dark" href="{% url 'drf-yasg:schema-swagger-ui' %}">API Docs (drf-yasg)</a>
   35 :         <a class="p-2 text-dark" href="{% url 'drf-spectacular:swagger-ui' %}">API Docs (drf-spectacular)</a>
   36 :         <a class="p-2 text-dark" href="{% url 'about' %}">About</a>
   37 :         <a class="p-2 text-dark" href="{% url 'admin:index' %}">Admin</a>
   38 :         <nav class="my-2 my-md-0 mr-md-3">
   39 :             {% if user.is_authenticated %}
   40 :                 <ul class="navbar-nav ml-auto">
   41 :                     <li class="nav-item">
   42 :                         <a class="nav-link dropdown-toggle" href="#" id="userMenu"

Traceback (most recent call last):
  File "/home/jpg/.local/share/virtualenvs/generic-django-example-Kc6WXfau/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
  File "/home/jpg/.local/share/virtualenvs/generic-django-example-Kc6WXfau/lib/python3.9/site-packages/django/core/handlers/base.py", line 220, in _get_response
    response = response.render()
  File "/home/jpg/.local/share/virtualenvs/generic-django-example-Kc6WXfau/lib/python3.9/site-packages/django/template/response.py", line 114, in render
    self.content = self.rendered_content
  File "/home/jpg/.local/share/virtualenvs/generic-django-example-Kc6WXfau/lib/python3.9/site-packages/django/template/response.py", line 92, in rendered_content
    return template.render(context, self._request)
  File "/home/jpg/.local/share/virtualenvs/generic-django-example-Kc6WXfau/lib/python3.9/site-packages/django/template/backends/django.py", line 62, in render
    return self.template.render(context)
  File "/home/jpg/.local/share/virtualenvs/generic-django-example-Kc6WXfau/lib/python3.9/site-packages/django/template/base.py", line 175, in render
    return self._render(context)
  File "/home/jpg/.local/share/virtualenvs/generic-django-example-Kc6WXfau/lib/python3.9/site-packages/django/test/utils.py", line 111, in instrumented_test_render
    return self.nodelist.render(context)
  File "/home/jpg/.local/share/virtualenvs/generic-django-example-Kc6WXfau/lib/python3.9/site-packages/django/template/base.py", line 1005, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/home/jpg/.local/share/virtualenvs/generic-django-example-Kc6WXfau/lib/python3.9/site-packages/django/template/base.py", line 1005, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/home/jpg/.local/share/virtualenvs/generic-django-example-Kc6WXfau/lib/python3.9/site-packages/django/template/base.py", line 966, in render_annotated
    return self.render(context)
  File "/home/jpg/.local/share/virtualenvs/generic-django-example-Kc6WXfau/lib/python3.9/site-packages/django/template/loader_tags.py", line 157, in render
    return compiled_parent._render(context)
  File "/home/jpg/.local/share/virtualenvs/generic-django-example-Kc6WXfau/lib/python3.9/site-packages/django/test/utils.py", line 111, in instrumented_test_render
    return self.nodelist.render(context)
  File "/home/jpg/.local/share/virtualenvs/generic-django-example-Kc6WXfau/lib/python3.9/site-packages/django/template/base.py", line 1005, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/home/jpg/.local/share/virtualenvs/generic-django-example-Kc6WXfau/lib/python3.9/site-packages/django/template/base.py", line 1005, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/home/jpg/.local/share/virtualenvs/generic-django-example-Kc6WXfau/lib/python3.9/site-packages/django/template/base.py", line 966, in render_annotated
    return self.render(context)
  File "/home/jpg/.local/share/virtualenvs/generic-django-example-Kc6WXfau/lib/python3.9/site-packages/django/template/defaulttags.py", line 472, in render
    url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
  File "/home/jpg/.local/share/virtualenvs/generic-django-example-Kc6WXfau/lib/python3.9/site-packages/django/urls/base.py", line 88, in reverse
    return resolver._reverse_with_prefix(view, prefix, *args, **kwargs)
  File "/home/jpg/.local/share/virtualenvs/generic-django-example-Kc6WXfau/lib/python3.9/site-packages/django/urls/resolvers.py", line 828, in _reverse_with_prefix
    raise NoReverseMatch(msg)

Exception Type: NoReverseMatch at /
Exception Value: Reverse for 'google_login' not found. 'google_login' is not a valid view function or pattern name.

</code>```

What could be the issue? How can I fix it?

Update-1

```<code># urls.py

from django.conf import settings
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path("admin/", admin.site.urls),
    path("accounts/", include("allauth.urls")),
    path("polls/", include("polls.urls")),
    path("attendance/", include("attendance.urls")),
    path("gql/strawberry/", include("strawberry_gql.urls")),
    path("", include("pages.urls")),
]

if settings.DEBUG:
    import debug_toolbar

    urlpatterns = [
        path("__debug__/", include(debug_toolbar.urls)),
    ] + urlpatterns

</code>```

Body:
I have a simple HTML content point towards the Google Login, as below.

# foo.html

Google Login

This simple demo project was using django==3.2.x and django-allauth==0.43.x. Recently, I have upgraded packages to the latest versions, viz, django==4.1.x and django-allauth==0.52.x.

After the upgrade, I was getting the following error -

Reverse for 'google_login' not found. 'google_login' is not a valid view function or pattern name.

I have confirmed the google_login is present by executing the reverse(...) function from the shell.

In [1]: from django.urls import  reverse

In [2]: reverse("google_login")
Out[2]: '/accounts/google/login/'

Error traceback

Environment:

Request Method: GET
Request URL: http://127.0.0.1:1234/

Django Version: 4.1.5
Python Version: 3.9.11
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'whitenoise.runserver_nostatic',
 'django.contrib.staticfiles',
 'django.contrib.sites',
 'allauth',
 'allauth.account',
 'allauth.socialaccount',
 'allauth.socialaccount.providers.google',
 'crispy_forms',
 'debug_toolbar',
 'drf_yasg',
 'django_extensions',
 'rest_framework',
 'drf_spectacular',
 'accounts',
 'pages',
 'polls',
 'extra',
 'attendance']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'whitenoise.middleware.WhiteNoiseMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'debug_toolbar.middleware.DebugToolbarMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Template error:
In template /home/jpg/work-dir/projects/-personal/generic-django-example/templates/_base.html, error at line 32
   Reverse for 'google_login' not found. 'google_login' is not a valid view function or pattern name.
   22 :         <link rel="stylesheet" href="{% static 'css/base.css' %}">
   23 :     {% endblock %}
   24 :
   25 :
   26 :
   27 :
   28 :

   29 :

   30 :             DjangoX
   31 :

   32 :         Google Login
   33 :         Polls APIs
   34 :         API Docs (drf-yasg)
   35 :         API Docs (drf-spectacular)
   36 :         About
   37 :         Admin
   38 :
   39 :             {% if user.is_authenticated %}
   40 :

   41 :

   42 :                         <a class="nav-link dropdown-toggle" href="#" id="userMenu"

Traceback (most recent call last):
  File "/home/jpg/.local/share/virtualenvs/generic-django-example-Kc6WXfau/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
  File "/home/jpg/.local/share/virtualenvs/generic-django-example-Kc6WXfau/lib/python3.9/site-packages/django/core/handlers/base.py", line 220, in _get_response
    response = response.render()
  File "/home/jpg/.local/share/virtualenvs/generic-django-example-Kc6WXfau/lib/python3.9/site-packages/django/template/response.py", line 114, in render
    self.content = self.rendered_content
  File "/home/jpg/.local/share/virtualenvs/generic-django-example-Kc6WXfau/lib/python3.9/site-packages/django/template/response.py", line 92, in rendered_content
    return template.render(context, self._request)
  File "/home/jpg/.local/share/virtualenvs/generic-django-example-Kc6WXfau/lib/python3.9/site-packages/django/template/backends/django.py", line 62, in render
    return self.template.render(context)
  File "/home/jpg/.local/share/virtualenvs/generic-django-example-Kc6WXfau/lib/python3.9/site-packages/django/template/base.py", line 175, in render
    return self._render(context)
  File "/home/jpg/.local/share/virtualenvs/generic-django-example-Kc6WXfau/lib/python3.9/site-packages/django/test/utils.py", line 111, in instrumented_test_render
    return self.nodelist.render(context)
  File "/home/jpg/.local/share/virtualenvs/generic-django-example-Kc6WXfau/lib/python3.9/site-packages/django/template/base.py", line 1005, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/home/jpg/.local/share/virtualenvs/generic-django-example-Kc6WXfau/lib/python3.9/site-packages/django/template/base.py", line 1005, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/home/jpg/.local/share/virtualenvs/generic-django-example-Kc6WXfau/lib/python3.9/site-packages/django/template/base.py", line 966, in render_annotated
    return self.render(context)
  File "/home/jpg/.local/share/virtualenvs/generic-django-example-Kc6WXfau/lib/python3.9/site-packages/django/template/loader_tags.py", line 157, in render
    return compiled_parent._render(context)
  File "/home/jpg/.local/share/virtualenvs/generic-django-example-Kc6WXfau/lib/python3.9/site-packages/django/test/utils.py", line 111, in instrumented_test_render
    return self.nodelist.render(context)
  File "/home/jpg/.local/share/virtualenvs/generic-django-example-Kc6WXfau/lib/python3.9/site-packages/django/template/base.py", line 1005, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/home/jpg/.local/share/virtualenvs/generic-django-example-Kc6WXfau/lib/python3.9/site-packages/django/template/base.py", line 1005, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/home/jpg/.local/share/virtualenvs/generic-django-example-Kc6WXfau/lib/python3.9/site-packages/django/template/base.py", line 966, in render_annotated
    return self.render(context)
  File "/home/jpg/.local/share/virtualenvs/generic-django-example-Kc6WXfau/lib/python3.9/site-packages/django/template/defaulttags.py", line 472, in render
    url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
  File "/home/jpg/.local/share/virtualenvs/generic-django-example-Kc6WXfau/lib/python3.9/site-packages/django/urls/base.py", line 88, in reverse
    return resolver._reverse_with_prefix(view, prefix, *args, **kwargs)
  File "/home/jpg/.local/share/virtualenvs/generic-django-example-Kc6WXfau/lib/python3.9/site-packages/django/urls/resolvers.py", line 828, in _reverse_with_prefix
    raise NoReverseMatch(msg)

Exception Type: NoReverseMatch at /
Exception Value: Reverse for 'google_login' not found. 'google_login' is not a valid view function or pattern name.

What could be the issue? How can I fix it?

Update-1

# urls.py

from django.conf import settings
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path("admin/", admin.site.urls),
    path("accounts/", include("allauth.urls")),
    path("polls/", include("polls.urls")),
    path("attendance/", include("attendance.urls")),
    path("gql/strawberry/", include("strawberry_gql.urls")),
    path("", include("pages.urls")),
]

if settings.DEBUG:
    import debug_toolbar

    urlpatterns = [
        path("__debug__/", include(debug_toolbar.urls)),
    ] + urlpatterns


问:
Integration Between Oracle Apex 5.1 And Oracle Fusion
Hello I'm really new on using Oracle Apex.
I want to get some data report from Oracle Fusion Instance and put the data into Oracle Apex Table. Since the Apex 5.1 doesn't have  'REST Data Sources' menu  under 'Shared Component'is there any way to connect between those two instance. Thanks before

A documentation how to connect between Oracle apex and Oracle Fusion without using 'REST Data Sources' Menu


问:
Transforming PipelinedRDD to spark dataframe
I am trying to convert a PipelinedRDD into a Spark dataframe, but I am getting the following error:

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Creating Spark session and taking a subset of the data:

```<code>from pyspark.sql import SparkSession

spark = SparkSession.builder.appName("SimpleApp").getOrCreate()
df = spark.read \
    .options(header=True, delimiter = ";") \
    .csv("decode_this_2.csv")

rdd = df.head(50000) # taking a sample of the data for testing purposes
</code>```

What the rdd/df looks like:

ID
Metadata

123
jf9834fi2f8924f2

345
oi2ehfd2hf4g3fg2

Using a lambda function to decode the metadata:

```<code>rdd2 = spark.sparkContext.parallelize(rdd) # parallelizing data

# create message decoder
message = protobuf_decoder.Metadata()

# decode message
def decode(x):
    try:
        a = x['metadata']
        temp_list = {} # storing data in a dictionary

        # decoding the metadata
        data = base64.b64decode(a)
        message.ParseFromString(data)

        temp_list['id'] = message.id # saving to dictionary

        # Add the list to a pandas DF to return into the rdd
        df_new_row = pd.DataFrame([temp_list])
        return df_new_row

    except Exception as e:
        print("except")
        print("e: ", e)

# call spark map to apply lambda decode function to the rdd
rdd3=rdd2.map(lambda x: decode(x))
</code>```

Output of rdd.collect():

```<code>[                                document_id
0  RSS-63c1e560-2c42-4ae4-9864-ee6965424944,                                 document_id
0  RSS-98a57ad3-ab20-4811-a9f6-c05fe455d1d5,                                  document_id
0  ASR-BARC-a431734c436079c1bfebbb5078ddc217,                                  document_id
0  ASR-BARC-a431734c436079c1bfebbb5078ddc217,                                  document_id
0  ASR-BARC-a431734c436079c1bfebbb5078ddc217,                                  document_id
0  ASR-BARC-a431734c436079c1bfebbb5078ddc217,                                  document_id
0  ASR-BARC-a431734c436079c1bfebbb5078ddc217,                                     document_id
0  MTN-a39f74a188b967c939fb8c351311603defbba7b6,                                     document_id
0  MTN-a39f74a188b967c939fb8c351311603defbba7b6,                                     document_id
0  MTN-a39f74a188b967c939fb8c351311603defbba7b6]

</code>```

^^ this output seems a little odd to me, but it seems like every row is a new index (index 0)? I was hoping someone could explain this output to me.

Now I want to upload the data into Google Cloud Storage as a CSV file, but PipelinedRDD is not a format I can export as a csv file. The reason I want to upload the file into Google Cloud Storage as a CSV file is because it will be easy to then upload the file into BigQuery.

I have tried the following functions:

rdd3.toDF()
rdd4 = spark.createDataFrame(rdd3, schema = "id")

Unfortunately, I am getting the following error:

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

I can use the following function, but the problem is that it is not scalable when you are trying to deal with about 100k records. I think it might be taking a long time collect the data (also trying to store a lot of data on memory probably isn't the best idea, especially when there could be more than 100k records):

```<code>def rdd_to_df(rdd3):
    # convert rdd to df
    df = rdd3.collect()
    df_df = pd.DataFrame()
    for i in df:
        # print(i)
        df_df = pd.concat([df_df, i])
    return df_df
</code>```

Body:
I am trying to convert a PipelinedRDD into a Spark dataframe, but I am getting the following error:

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Creating Spark session and taking a subset of the data:

from pyspark.sql import SparkSession

spark = SparkSession.builder.appName("SimpleApp").getOrCreate()
df = spark.read \
    .options(header=True, delimiter = ";") \
    .csv("decode_this_2.csv")

rdd = df.head(50000) # taking a sample of the data for testing purposes

What the rdd/df looks like:

ID
Metadata

123
jf9834fi2f8924f2

345
oi2ehfd2hf4g3fg2

Using a lambda function to decode the metadata:

rdd2 = spark.sparkContext.parallelize(rdd) # parallelizing data

# create message decoder
message = protobuf_decoder.Metadata()

# decode message
def decode(x):
    try:
        a = x['metadata']
        temp_list = {} # storing data in a dictionary

        # decoding the metadata
        data = base64.b64decode(a)
        message.ParseFromString(data)

        temp_list['id'] = message.id # saving to dictionary

        # Add the list to a pandas DF to return into the rdd
        df_new_row = pd.DataFrame([temp_list])
        return df_new_row

    except Exception as e:
        print("except")
        print("e: ", e)

# call spark map to apply lambda decode function to the rdd
rdd3=rdd2.map(lambda x: decode(x))

Output of rdd.collect():

[                                document_id
0  RSS-63c1e560-2c42-4ae4-9864-ee6965424944,                                 document_id
0  RSS-98a57ad3-ab20-4811-a9f6-c05fe455d1d5,                                  document_id
0  ASR-BARC-a431734c436079c1bfebbb5078ddc217,                                  document_id
0  ASR-BARC-a431734c436079c1bfebbb5078ddc217,                                  document_id
0  ASR-BARC-a431734c436079c1bfebbb5078ddc217,                                  document_id
0  ASR-BARC-a431734c436079c1bfebbb5078ddc217,                                  document_id
0  ASR-BARC-a431734c436079c1bfebbb5078ddc217,                                     document_id
0  MTN-a39f74a188b967c939fb8c351311603defbba7b6,                                     document_id
0  MTN-a39f74a188b967c939fb8c351311603defbba7b6,                                     document_id
0  MTN-a39f74a188b967c939fb8c351311603defbba7b6]

^^ this output seems a little odd to me, but it seems like every row is a new index (index 0)? I was hoping someone could explain this output to me.

Now I want to upload the data into Google Cloud Storage as a CSV file, but PipelinedRDD is not a format I can export as a csv file. The reason I want to upload the file into Google Cloud Storage as a CSV file is because it will be easy to then upload the file into BigQuery.

I have tried the following functions:

rdd3.toDF()
rdd4 = spark.createDataFrame(rdd3, schema = "id")

Unfortunately, I am getting the following error:

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

I can use the following function, but the problem is that it is not scalable when you are trying to deal with about 100k records. I think it might be taking a long time collect the data (also trying to store a lot of data on memory probably isn't the best idea, especially when there could be more than 100k records):

def rdd_to_df(rdd3):
    # convert rdd to df
    df = rdd3.collect()
    df_df = pd.DataFrame()
    for i in df:
        # print(i)
        df_df = pd.concat([df_df, i])
    return df_df