QuestionId
int64 74.8M
79.8M
| UserId
int64 56
29.4M
| QuestionTitle
stringlengths 15
150
| QuestionBody
stringlengths 40
40.3k
| Tags
stringlengths 8
101
| CreationDate
stringdate 2022-12-10 09:42:47
2025-11-01 19:08:18
| AnswerCount
int64 0
44
| UserExpertiseLevel
int64 301
888k
| UserDisplayName
stringlengths 3
30
⌀ |
|---|---|---|---|---|---|---|---|---|
78,884,453
| 5,342,009
|
Azure Appservice for Django fails with Azure Devops Pipeline
|
<p>I have an appservice running on Azure in a Linux environment.</p>
<p>I try to associate it with a Azure Devops Pipeline so I can have CI/CD for the repositories & branches on Github.</p>
<p>I want the builds to occur on Azure Pipeline & Azure infrastructure, not Github Actions.</p>
<p>I have tried all other suggestions including following environment variables on App Service :</p>
<pre><code>SCM_DO_BUILD_DURING_DEPLOYMENT=true
WEBSITE_NODE_DEFAULT_VERSION=~18
WEBSITE_RUN_FROM_PACKAGE=true
</code></pre>
<p>Here is the logs that I receive from the Kudu / Azure Devops Pipeline / AppService logs :</p>
<pre><code>/home/LogFiles/2024_08_14_ln1xsdlwk0000K3_docker.log (https://project-app-development.scm.azurewebsites.net/api/vfs/LogFiles/2024_08_14_ln1xsdlwk0000K3_docker.log)
2024-08-14T23:51:45.168Z INFO - Status: Image is up to date for 10.1.0.6:13209/appsvc/python:3.10_20240619.2.tuxprod
2024-08-14T23:51:45.179Z INFO - Pull Image successful, Time taken: 0 Seconds
2024-08-14T23:51:45.223Z INFO - Starting container for site
2024-08-14T23:51:45.223Z INFO - docker run -d --expose=8000 --name project-app-development_0_f2e0544d -e WEBSITE_USE_DIAGNOSTIC_SERVER=false -e WEBSITE_SITE_NAME=project-app-development -e WEBSITE_AUTH_ENABLED=False -e WEBSITE_ROLE_INSTANCE_ID=0 -e WEBSITE_HOSTNAME=project-app-development.azurewebsites.net -e WEBSITE_INSTANCE_ID=3f627dbbecdaed255d87aa9c3e8f1448758df1cdff41f5e14b114384ea9b244a appsvc/python:3.10_20240619.2.tuxprod gunicorn -b :$PORT project.wsgi
2024-08-14T23:51:45.223Z INFO - Logging is not enabled for this container.
Please use https://aka.ms/linux-diagnostics to enable logging to see container logs here.
2024-08-14T23:51:45.893Z INFO - Initiating warmup request to container project-app-development_0_f2e0544d for site project-app-development
2024-08-14T23:51:49.043Z ERROR - Container project-app-development_0_f2e0544d for site project-app-development has exited, failing site start
2024-08-14T23:51:49.057Z ERROR - Container project-app-development_0_f2e0544d didn't respond to HTTP pings on port: 8000, failing site start. See container logs for debugging.
2024-08-14T23:51:49.063Z INFO - Stopping site project-app-development because it failed during startup.
/home/LogFiles/2024_08_14_ln1xsdlwk0000WT_default_docker.log (https://project-app-development.scm.azurewebsites.net/api/vfs/LogFiles/2024_08_14_ln1xsdlwk0000WT_default_docker.log)
2024-08-14T00:05:39.611783454Z File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
2024-08-14T00:05:39.611788754Z File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
2024-08-14T00:05:39.611793955Z File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
2024-08-14T00:05:39.611799355Z File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked
2024-08-14T00:05:39.611804655Z ModuleNotFoundError: No module named 'project'
2024-08-14T00:05:39.611810055Z [2024-08-14 00:05:39 +0000] [83] [INFO] Worker exiting (pid: 83)
2024-08-14T00:05:39.756375163Z [2024-08-14 00:05:39 +0000] [49] [ERROR] Worker (pid:83) exited with code 3
2024-08-14T00:05:39.758705055Z [2024-08-14 00:05:39 +0000] [49] [ERROR] Shutting down: Master
2024-08-14T00:05:39.758726256Z [2024-08-14 00:05:39 +0000] [49] [ERROR] Reason: Worker failed to boot.
</code></pre>
<p>Here is my startup command on Azure AppService Configuration :</p>
<pre><code>gunicorn -b :8000 project.wsgi
% cat app.yaml
runtime: python37
entrypoint: gunicorn -b :$PORT project.wsgi
# service: "project-ai-266410"
service: "default"
handlers:
# This configures Google App Engine to serve the files in the app's static
# directory.
- url: /static
static_dir: static
secure: always
# This handler routes all requests not caught above to your main app. It is
# required when static routes are defined, but can be omitted (along with
# the entire handlers section) when there are no static files defined.
- url: /.*
script: auto
secure: always%
% cat ./project/wsgi.py
"""
WSGI config for project project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
application = get_wsgi_application()
</code></pre>
<p>Here is my github workflow file :</p>
<pre><code># Docs for the Azure Web Apps Deploy action: https://github.com/Azure/webapps-deploy
# More GitHub Actions for Azure: https://github.com/Azure/actions
# More info on Python, GitHub Actions, and Azure App Service: https://aka.ms/python-webapps-actions
name: Build and deploy Python app to Azure Web App - project-app-development
on:
push:
branches:
- 543-azure-based-secrets
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python version
uses: actions/setup-python@v5
with:
python-version: '3.12'
- name: Create and start virtual environment
run: |
python -m venv antenv
source antenv/bin/activate
- name: Install dependencies
run: pip install -r requirements.txt
# Optional: Add step to run tests here (PyTest, Django test suites, etc.)
- name: Zip artifact for deployment
run: zip release.zip ./* -r
- name: Upload artifact for deployment jobs
uses: actions/upload-artifact@v4
with:
name: python-app
path: |
release.zip
!venv/
deploy:
runs-on: ubuntu-latest
needs: build
environment:
name: 'Production'
url: ${{ steps.deploy-to-webapp.outputs.webapp-url }}
permissions:
id-token: write #This is required for requesting the JWT
steps:
- name: Download artifact from build job
uses: actions/download-artifact@v4
with:
name: python-app
- name: Unzip artifact for deployment
run: unzip release.zip
- name: Login to Azure
uses: azure/login@v2
with:
client-id: ${{ secrets.AZUREAPPSERVICE_CLIENTID_5DF5B8B04E0349C7828DF5D5B258B9CD }}
tenant-id: ${{ secrets.AZUREAPPSERVICE_TENANTID_741E597FD19043F4B2CBF83B89C75D92 }}
subscription-id: ${{ secrets.AZUREAPPSERVICE_SUBSCRIPTIONID_ED0C3DE592084669926EEBA461FB5E98 }}
- name: 'Deploy to Azure Web App'
uses: azure/webapps-deploy@v3
id: deploy-to-webapp
with:
app-name: 'project-app-development'
slot-name: 'Production'
</code></pre>
<p>Azure devops Yaml file :</p>
<pre><code>trigger:
- $(feature-branch)
variables:
azureServiceConnectionId: '-db5f-4993-91f8-85f3a75cb357'
webAppName: 'project-app-development'
vmImageName: 'ubuntu-latest'
environmentName: 'project-app-development'
projectRoot: $(System.DefaultWorkingDirectory)
pythonVersion: '3.8'
system.debug: true
stages:
- stage: Build
displayName: Build stage
jobs:
- job: BuildJob
pool:
vmImage: $(vmImageName)
steps:
- task: UsePythonVersion@0
inputs:
versionSpec: '$(pythonVersion)'
displayName: 'Use Python $(pythonVersion)'
- script: |
python -m virtualenv env
source env/bin/activate
python -m pip install --upgrade pip
pip install -r requirements.txt
workingDirectory: $(projectRoot)
displayName: "Install requirements"
- task: ArchiveFiles@2
displayName: 'Archive files'
inputs:
rootFolderOrFile: '$(projectRoot)'
includeRootFolder: true
archiveType: zip
archiveFile: $(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip
replaceExistingArchive: true
- upload: $(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip
displayName: 'Upload package'
artifact: drop
- stage: Deploy
displayName: 'Deploy Web App'
dependsOn: Build
condition: succeeded()
jobs:
- deployment: DeploymentJob
pool:
vmImage: $(vmImageName)
environment: $(environmentName)
strategy:
runOnce:
deploy:
steps:
- task: UsePythonVersion@0
inputs:
versionSpec: '$(pythonVersion)'
displayName: 'Use Python version'
- task: AzureWebApp@1
displayName: 'Deploy Azure Web App : project-app-development'
inputs:
azureSubscription: $(azureServiceConnectionId)
appName: $(webAppName)
package: $(Pipeline.Workspace)/drop/$(Build.BuildId).zip
</code></pre>
<p>Latest github actions error message :</p>
<pre><code>##[debug]logs from kudu deploy: https://project-app-development.scm.azurewebsites.net/api/deployments/temp-69fc3536/log
##[debug]setting affinity cookie ["ARRAffinity=f1c95587fdc6f942a20e5a5078e78322a753dff56e2f30cc9c09a2b930fa89ac;Path=/;HttpOnly;Secure;Domain=project-app-development.scm.azurewebsites.net","ARRAffinitySameSite=f1c95587fdc6f942a20e5a5078e78322a753dff56e2f30cc9c09a2b930fa89ac;Path=/;HttpOnly;SameSite=None;Secure;Domain=project-app-development.scm.azurewebsites.net"]
##[debug][GET] https://project-app-development.scm.azurewebsites.net/api/deployments/temp-69fc3536/log
##[debug]getDeploymentLogs. Data: {"statusCode":200,"statusMessage":"OK","headers":{"content-length":"268","content-type":"application/json; charset=utf-8","date":"Mon, 19 Aug 2024 15:57:25 GMT","server":"Kestrel"},"body":[{"log_time":"2024-08-19T15:57:13.2195847Z","id":"afc2dd47-e1ad-4b07-b6aa-fb59b6531aad","message":"Fetching changes.","type":0,"details_url":"https://project-app-development.scm.azurewebsites.net/api/deployments/temp-69fc3536/log/afc2dd47-e1ad-4b07-b6aa-fb59b6531aad"}]}
Fetching changes.
##[debug]setting affinity cookie ["ARRAffinity=f1c95587fdc6f942a20e5a5078e78322a753dff56e2f30cc9c09a2b930fa89ac;Path=/;HttpOnly;Secure;Domain=project-app-development.scm.azurewebsites.net","ARRAffinitySameSite=f1c95587fdc6f942a20e5a5078e78322a753dff56e2f30cc9c09a2b930fa89ac;Path=/;HttpOnly;SameSite=None;Secure;Domain=project-app-development.scm.azurewebsites.net"]
##[debug][GET] https://project-app-development.scm.azurewebsites.net/api/deployments/temp-69fc3536/log/afc2dd47-e1ad-4b07-b6aa-fb59b6531aad
##[debug]getDeploymentLogs. Data: {"statusCode":200,"statusMessage":"OK","headers":{"content-length":"274","content-type":"application/json; charset=utf-8","date":"Mon, 19 Aug 2024 15:57:26 GMT","server":"Kestrel"},"body":[{"log_time":"2024-08-19T15:57:14.2281682Z","id":"","message":"Cleaning up temp folders from previous zip deployments and extracting pushed zip file /tmp/zipdeploy/c28a10f3-d998-437f-94af-eed376d90b90.zip (24.85 MB) to /tmp/zipdeploy/extracted","type":0,"details_url":null}]}
Cleaning up temp folders from previous zip deployments and extracting pushed zip file /tmp/zipdeploy/c28a10f3-d998-437f-94af-eed376d90b90.zip (24.85 MB) to /tmp/zipdeploy/extracted
Error: Failed to deploy web package to App Service.
Error: Deployment Failed, Package deployment using ZIP Deploy failed. Refer logs for more details.
##[debug][POST] https://management.azure.com/subscriptions/***/resourceGroups/project-app-development_group/providers/Microsoft.Web/sites/project-app-development/config/appsettings/list?api-version=2016-08-01
##[debug][GET] https://management.azure.com/subscriptions/***/providers/microsoft.insights/components?$filter=InstrumentationKey eq '4f576d13-00e5-4831-a1d5-7e5ea3cab3c5'&api-version=2015-05-01
##[debug]Unable to find Application Insights resource with Instrumentation key 4f576d13-00e5-4831-a1d5-7e5ea3cab3c5. Skipping adding release annotation.
App Service Application URL: https://project-app-development.azurewebsites.net
##[debug]Deployment failed
##[debug]Node Action run completed with exit code 1
##[debug]AZURE_HTTP_USER_AGENT='GITHUBACTIONS_DeployWebAppToAzure_0a886200850ef7f915637c263559bb1d8963ef779ce24674d123a365c5ec1237'
##[debug]AZURE_HTTP_USER_AGENT=''
##[debug]Set output webapp-url = https://project-app-development.azurewebsites.net
##[debug]Finishing: Deploy to Azure Web App
</code></pre>
<p>Simpler error logs (Turned off advanced logs)</p>
<pre><code>Run azure/webapps-deploy@v3
Package deployment using OneDeploy initiated.
{
id: 'temp-fb83a24b',
status: 3,
status_text: '',
author_email: 'N/A',
author: 'N/A',
deployer: 'OneDeploy',
message: 'OneDeploy',
progress: '',
received_time: '2024-08-19T16:47:42.3127586Z',
start_time: '2024-08-19T16:47:42.3127586Z',
end_time: '2024-08-19T16:47:51.8169497Z',
last_success_end_time: null,
complete: true,
active: false,
is_temp: true,
is_readonly: false,
url: 'https://project-app-development.scm.azurewebsites.net/api/deployments/temp-fb83a24b',
log_url: 'https://project-app-development.scm.azurewebsites.net/api/deployments/temp-fb83a24b/log',
site_name: 'project-app-development',
build_summary: { errors: [], warnings: [] }
}
Fetching changes.
Cleaning up temp folders from previous zip deployments and extracting pushed zip file /tmp/zipdeploy/31a79a90-85fe-4021-92a0-24cd5f24118d.zip (24.85 MB) to /tmp/zipdeploy/extracted
Error: Failed to deploy web package to App Service.
Error: Deployment Failed, Package deployment using ZIP Deploy failed. Refer logs for more details.
App Service Application URL: https://project-app-development.azurewebsites.net
</code></pre>
<p>When I set includeRootFolder : true, build does not fail, logs :
<a href="https://filetransfer.io/data-package/FFthMYut#link" rel="nofollow noreferrer">succesful but not working detailed logs 488</a></p>
<p>When I set includeRootFolder : false, build fails with the following, you can find the detailed logs here : <a href="https://filetransfer.io/data-package/FFthMYut#link" rel="nofollow noreferrer">failed detailed logs 489</a></p>
<p>Update : I am also trying with Github actions, the primary problem is : the zip file never arrives to Appservice from devops; either azure pipelines or github actions.</p>
<p>Change diff for "includeRootFolder : false" :</p>
<pre><code> displayName: 'Archive files'
inputs:
rootFolderOrFile: '$(projectRoot)'
includeRootFolder: true
includeRootFolder: false
archiveType: zip
archiveFile: $(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip
replaceExistingArchive: true
</code></pre>
<p>Logs after setting "includeRootFolder : false" :</p>
<pre><code> ##[error]Failed to deploy web package to App Service.
##[error]KuduStackTraceURL https://$project-app-development:***@videoo-app-development.scm.azurewebsites.net/api/vfs/LogFiles/kudu/trace
##[error]Error: Package deployment using ZIP Deploy failed. Refer logs for more details.
Latest logs after setting
-includeRootFolder : false
-ENABLE_ORYX_BUILD : false
-SCM_DO_BUILD_DURING_DEPLOYMENT : true
-WEBSITE_RUN_FROM_PACKAGE : 1
2024-08-20T05:57:34.254Z INFO - Starting container for site
2024-08-20T05:57:34.256Z INFO - docker run -d --expose=8000 --name project-app-development_0_c5c7b0dd -e WEBSITE_USE_DIAGNOSTIC_SERVER=false -e PORT=8000 -e WEBSITES_PORT=8000 -e WEBSITE_SITE_NAME=project-app-development -e WEBSITE_AUTH_ENABLED=False -e WEBSITE_ROLE_INSTANCE_ID=0 -e WEBSITE_HOSTNAME=project-app-development.azurewebsites.net -e WEBSITE_INSTANCE_ID=3f627dbbecdaed255d87aa9c3e8f1448758df1cdff41f5e14b114384ea9b244a -e HTTP_LOGGING_ENABLED=1 appsvc/python:3.8-bullseye_20240619.2.tuxprod
2024-08-20T05:57:35.308Z INFO - Initiating warmup request to container project-app-development_0_c5c7b0dd for site project-app-development
2024-08-20T05:57:36.327Z ERROR - Container project-app-development_0_c5c7b0dd for site project-app-development has exited, failing site start
2024-08-20T05:57:36.334Z ERROR - Container project-app-development_0_c5c7b0dd didn't respond to HTTP pings on port: 8000, failing site start. See container logs for debugging.
2024-08-20T05:57:36.337Z INFO - Stopping site project-app-development because it failed during startup.
2024-08-20T05:57:53.915425573Z _____
2024-08-20T05:57:53.915485375Z / _ \ __________ _________ ____
2024-08-20T05:57:53.915492475Z / /_\ \\___ / | \_ __ \_/ __ \
2024-08-20T05:57:53.915497675Z / | \/ /| | /| | \/\ ___/
2024-08-20T05:57:53.915502375Z \____|__ /_____ \____/ |__| \___ >
2024-08-20T05:57:53.915507176Z \/ \/ \/
2024-08-20T05:57:53.915511976Z A P P S E R V I C E O N L I N U X
2024-08-20T05:57:53.915516676Z
2024-08-20T05:57:53.915521376Z Documentation: http://aka.ms/webapp-linux
2024-08-20T05:57:53.915529576Z Python 3.8.19
2024-08-20T05:57:53.915536477Z Note: Any data outside '/home' is not persisted
2024-08-20T05:57:54.221285535Z Starting OpenBSD Secure Shell server: sshd.
2024-08-20T05:57:54.235160933Z WEBSITES_INCLUDE_CLOUD_CERTS is not set to true.
2024-08-20T05:57:54.265297413Z App Command Line not configured, will attempt auto-detect
2024-08-20T05:57:54.265793631Z Launching oryx with: create-script -appPath /home/site/wwwroot -output /opt/startup/startup.sh -virtualEnvName antenv -defaultApp /opt/defaultsite
2024-08-20T05:57:54.292483387Z Could not find build manifest file at '/home/site/wwwroot/oryx-manifest.toml'
2024-08-20T05:57:54.292508088Z Could not find operation ID in manifest. Generating an operation id...
2024-08-20T05:57:54.292513388Z Build Operation ID: b6e4f53f-a160-4836-81df-40a78959b714
2024-08-20T05:57:54.395411376Z Oryx Version: 0.2.20240619.2, Commit: cf006407a02b225f59dccd677986973c7889aa50, ReleaseTagName: 20240619.2
2024-08-20T05:57:54.398960704Z Detected an app based on Django
2024-08-20T05:57:54.399159411Z Generating `gunicorn` command for 'project.wsgi'
2024-08-20T05:57:54.410518018Z Writing output script to '/opt/startup/startup.sh'
2024-08-20T05:57:54.427810538Z WARNING: Could not find virtual environment directory /home/site/wwwroot/antenv.
2024-08-20T05:57:54.427831338Z WARNING: Could not find package directory /home/site/wwwroot/__oryx_packages__.
2024-08-20T05:57:54.970237380Z [2024-08-20 05:57:54 +0000] [48] [INFO] Starting gunicorn 22.0.0
2024-08-20T05:57:54.987807809Z [2024-08-20 05:57:54 +0000] [48] [INFO] Listening at: http://0.0.0.0:8000 (48)
2024-08-20T05:57:54.987844111Z [2024-08-20 05:57:54 +0000] [48] [INFO] Using worker: sync
2024-08-20T05:57:54.997822968Z [2024-08-20 05:57:54 +0000] [57] [INFO] Booting worker with pid: 57
2024-08-20T05:57:55.045597781Z [2024-08-20 05:57:55 +0000] [57] [ERROR] Exception in worker process
2024-08-20T05:57:55.045636382Z Traceback (most recent call last):
2024-08-20T05:57:55.045643782Z File "/opt/python/3.8.19/lib/python3.8/site-packages/gunicorn/arbiter.py", line 609, in spawn_worker
2024-08-20T05:57:55.045658983Z worker.init_process()
2024-08-20T05:57:55.045664583Z File "/opt/python/3.8.19/lib/python3.8/site-packages/gunicorn/workers/base.py", line 134, in init_process
2024-08-20T05:57:55.045683084Z self.load_wsgi()
2024-08-20T05:57:55.045688584Z File "/opt/python/3.8.19/lib/python3.8/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi
2024-08-20T05:57:55.045694184Z self.wsgi = self.app.wsgi()
2024-08-20T05:57:55.045699484Z File "/opt/python/3.8.19/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi
2024-08-20T05:57:55.045704784Z self.callable = self.load()
2024-08-20T05:57:55.045710085Z File "/opt/python/3.8.19/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 58, in load
2024-08-20T05:57:55.045715485Z return self.load_wsgiapp()
2024-08-20T05:57:55.045720885Z File "/opt/python/3.8.19/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp
2024-08-20T05:57:55.045726285Z return util.import_app(self.app_uri)
2024-08-20T05:57:55.045731885Z File "/opt/python/3.8.19/lib/python3.8/site-packages/gunicorn/util.py", line 371, in import_app
2024-08-20T05:57:55.045737786Z mod = importlib.import_module(module)
2024-08-20T05:57:55.045743086Z File "/opt/python/3.8.19/lib/python3.8/importlib/__init__.py", line 127, in import_module
2024-08-20T05:57:55.045748486Z return _bootstrap._gcd_import(name[level:], package, level)
2024-08-20T05:57:55.045753786Z File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
2024-08-20T05:57:55.045759786Z File "<frozen importlib._bootstrap>", line 991, in _find_and_load
2024-08-20T05:57:55.045765487Z File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
2024-08-20T05:57:55.045771387Z File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
2024-08-20T05:57:55.045776787Z File "<frozen importlib._bootstrap_external>", line 843, in exec_module
2024-08-20T05:57:55.045782087Z File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
2024-08-20T05:57:55.045787187Z File "/home/site/wwwroot/project/wsgi.py", line 12, in <module>
2024-08-20T05:57:55.045792588Z from django.core.wsgi import get_wsgi_application
2024-08-20T05:57:55.045797988Z ModuleNotFoundError: No module named 'django'
2024-08-20T05:57:55.046148100Z [2024-08-20 05:57:55 +0000] [57] [INFO] Worker exiting (pid: 57)
2024-08-20T05:57:55.107735008Z [2024-08-20 05:57:55 +0000] [48] [ERROR] Worker (pid:57) exited with code 3
2024-08-20T05:57:55.107770709Z [2024-08-20 05:57:55 +0000] [48] [ERROR] Shutting down: Master
2024-08-20T05:57:55.107777009Z [2024-08-20 05:57:55 +0000] [48] [ERROR] Reason: Worker failed to boot.
2024-08-20 05:57:54,978 [MainThread] [DEBUG] : Initializating AppServiceAppLogging
2024-08-20 05:57:54,982 [Thread-1 ] [DEBUG] : Did not find any previously bound socket
2024-08-20 05:57:54,983 [MainThread] [DEBUG] : Initialized AppServiceAppLogging
2024-08-20T05:57:53.623Z INFO - Starting container for site
2024-08-20T05:57:53.641Z INFO - docker run -d --expose=8000 --name project-app-development_0_4c6a7e4b -e WEBSITE_USE_DIAGNOSTIC_SERVER=false -e PORT=8000 -e WEBSITES_PORT=8000 -e WEBSITE_SITE_NAME=project-app-development -e WEBSITE_AUTH_ENABLED=False -e WEBSITE_ROLE_INSTANCE_ID=0 -e WEBSITE_HOSTNAME=project-app-development.azurewebsites.net -e WEBSITE_INSTANCE_ID=8a9506920697ea08e988fb00cb7a286fb2bda894a9cbfd61c5690d00f38d01a6 -e HTTP_LOGGING_ENABLED=1 appsvc/python:3.8-bullseye_20240619.2.tuxprod
2024-08-20T05:57:55.010Z INFO - Initiating warmup request to container project-app-development_0_4c6a7e4b for site project-app-development
2024-08-20T05:57:56.129Z ERROR - Container project-app-development_0_4c6a7e4b for site project-app-development has exited, failing site start
2024-08-20T05:57:56.140Z ERROR - Container project-app-development_0_4c6a7e4b didn't respond to HTTP pings on port: 8000, failing site start. See container logs for debugging.
2024-08-20T05:57:56.145Z INFO - Stopping site project-app-development because it failed during startup.
</code></pre>
|
<python><django><azure><azure-devops><azure-pipelines>
|
2024-08-18 11:24:41
| 1
| 1,312
|
london_utku
|
78,884,344
| 4,262,324
|
How to obtain syntax highlight/coloring for Snakemake file?
|
<p>The snakemake documentation show syntax highlighting of the <code>Snakefile</code> file, like in here
<a href="https://i.sstatic.net/QsEVyRyn.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/QsEVyRyn.png" alt="enter image description here" /></a></p>
<p>Can I obtain something like for the <code>Snakefile</code> in an IDE, e.g. PyCharm or VSC?</p>
<p>With PyCharm I have tried associating the Python file type also with files called <code>Snakefile</code>, but that also checks the syntax, and of course shows errors all over the place. I would like to get (configure) syntax highlights only, if possible.</p>
|
<python><snakemake>
|
2024-08-18 10:35:30
| 2
| 3,149
|
Fanta
|
78,884,251
| 12,338,762
|
Unable to install wordnet with nltk 3.9.0 as importing nltk requires installed wordnet
|
<p>It is not possible to import nltk, and the solution given by the output required me to import nltk:</p>
<pre class="lang-py prettyprint-override"><code>>>>import nltk
Traceback (most recent call last):
File "D:\project\Lib\site-packages\nltk\corpus\util.py", line 84, in __load
root = nltk.data.find(f"{self.subdir}/{zip_name}")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\project\Lib\site-packages\nltk\data.py", line 579, in find
raise LookupError(resource_not_found
LookupError:
**********************************************************************
Resource wordnet not found.
Please use the NLTK Downloader to obtain the resource:
>>> import nltk
>>> nltk.download('wordnet')
For more information see: https://www.nltk.org/data.html
Attempted to load corpora/wordnet.zip/wordnet/
Searched in:
- 'C:\\Users\\me/nltk_data'
- 'D:\\project\\nltk_data'
- 'D:\\project\\share\\nltk_data'
- 'D:\\project\\lib\\nltk_data'
- 'C:\\Users\\me\\AppData\\Roaming\\nltk_data'
- 'C:\\nltk_data'
- 'D:\\nltk_data'
- 'E:\\nltk_data'
**********************************************************************
</code></pre>
<p>Basically - I cannot import nltk because wordnet is missing, but in order to download wordnet, I have to import nltk which I cannot, because wordnet is missing.</p>
<p>Noteworthy is, that it throws this exception twice, but with a different traceback -</p>
<pre class="lang-py prettyprint-override"><code>During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "D:\project\Lib\site-packages\nltk\__init__.py", line 156, in <module>
from nltk.stem import *
File "D:\project\Lib\site-packages\nltk\stem\__init__.py", line 34, in <module>
from nltk.stem.wordnet import WordNetLemmatizer
File "D:\project\Lib\site-packages\nltk\stem\wordnet.py", line 13, in <module>
class WordNetLemmatizer:
File "D:project\Lib\site-packages\nltk\stem\wordnet.py", line 48, in WordNetLemmatizer
morphy = wn.morphy
^^^^^^^^^
File "D:\project\Lib\site-packages\nltk\corpus\util.py", line 120, in __getattr__
self.__load()
File "D:\project\Lib\site-packages\nltk\corpus\util.py", line 86, in __load
raise e
File "D:\project\Lib\site-packages\nltk\corpus\util.py", line 81, in __load
root = nltk.data.find(f"{self.subdir}/{self.__name}")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\project\Lib\site-packages\nltk\data.py", line 579, in find
raise LookupError(resource_not_found)
LookupError:
**********************************************************************
Resource wordnet not found.
Please use the NLTK Downloader to obtain the resource:
>>> import nltk
>>> nltk.download('wordnet')
For more information see: https://www.nltk.org/data.html
Attempted to load corpora/wordnet
Searched in:
- 'C:\\Users\\me/nltk_data'
- 'D:\\project\\nltk_data'
- 'D:\\project\\share\\nltk_data'
- 'D:\\project\\lib\\nltk_data'
- 'C:\\Users\\me\\AppData\\Roaming\\nltk_data'
- 'C:\\nltk_data'
- 'D:\\nltk_data'
- 'E:\\nltk_data'
**********************************************************************
</code></pre>
<p>What is the suggested solution in this case?</p>
|
<python><nltk><wordnet>
|
2024-08-18 09:53:51
| 1
| 1,263
|
Maritn Ge
|
78,884,169
| 3,561,433
|
"tf.summary.image" gives Invalid Argument Error for the standard example
|
<p>I have recently started Tensorflow by trying to replicate some of the existing repos, and I have been stuck at writing summaries since quite some time now.</p>
<p>Specifically, I have been trying to port the <a href="https://github.com/bmild/nerf" rel="nofollow noreferrer">https://github.com/bmild/nerf</a> code to TF2.x. And I realised that</p>
<blockquote>
<p>tf.summary.image</p>
</blockquote>
<p>doesn't seem to work even with the default examples provided in TF's documentation. - <a href="https://www.tensorflow.org/api_docs/python/tf/summary/image#raises" rel="nofollow noreferrer">tf.summary.image</a> While I am able to make it work, if the input is scalar, but not for images.</p>
<p>The code:-</p>
<pre><code>import tensorflow as tf
w = tf.summary.create_file_writer('test/logs')
with w.as_default():
image1 = tf.random.uniform(shape=[8, 8, 1])
image2 = tf.random.uniform(shape=[8, 8, 1])
tf.summary.image("grayscale_noise", [image1, image2], step=0)
</code></pre>
<p>It throws the following error:-</p>
<pre><code>Exception has occurred: InvalidArgumentError
image must be 3-dimensional[2,8,8,1] [Op:EncodePng]
tensorflow.python.eager.core._NotOkStatusException: InvalidArgumentError: image must be 3-dimensional[2,8,8,1] [Op:EncodePng]
During handling of the above exception, another exception occurred:
File "C:\Users\QYGXAMU\Documents\NeRF\nerf\check_tf_summary.py", line 7, in <module>
tf.summary.image("grayscale_noise", [image1, image2], step=0)
tensorflow.python.framework.errors_impl.InvalidArgumentError: image must be 3-dimensional[2,8,8,1] [Op:EncodePng]
</code></pre>
<p>Please let me know why this basic snippet is also not working.</p>
|
<python><tensorflow2.0><tensorboard>
|
2024-08-18 09:16:40
| 1
| 522
|
Manish
|
78,884,161
| 7,695,845
|
Control how many digits are printed for an astropy quantity in a jupyter notebook
|
<p>I use <code>astropy</code> to make calculations with units and I normally do these calculations in a jupyter notebook so the results are printed nicely. I would like to know how to control the number of digits that are displayed in the notebook. Take a look at this example:</p>
<p><a href="https://i.sstatic.net/iVlFGhij.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/iVlFGhij.png" alt="" /></a></p>
<p>The speed of light is defined to be <strong>exactly</strong> "c = 29,979,245,800 cm/s". However, when I print <code>const.c.cgs</code> in a cell, I get "2.9979246 x 10^10 cm/s". It rounded it up. I know that the exact value is indeed stored in that constant as can be seen by printing it or accessing its value directly (e.g. <code>print(const.c.cgs)</code> or simply <code>const.c.cgs.value</code> which gives the exact value "29979245800 cm/s"), but it displays it with rounding up. I understand this behavior and it's fine for most cases, but there are cases like this where I'd like to see more digits. How can I change the number of digits that are printed in the cell? I want to have this pretty printing of jupyter, but I want to see the full value too.</p>
|
<python><jupyter-notebook><astropy>
|
2024-08-18 09:11:21
| 1
| 1,420
|
Shai Avr
|
78,884,128
| 4,454,021
|
Zip file is only partially downloaded
|
<p>I am trying to download a zip file with Python 3 requests:</p>
<pre><code>try:
r = requests.get(BASEURL, stream=True)
with open(localfiletitle, 'wb') as fd:
shutil.copyfileobj(r.raw, fd)
except requests.exceptions.RequestException as e:
send_notice_mail("Error downloading the file:", e)
return False
</code></pre>
<p>but I am always getting a partial, invalid file. I have also tried using <code>urllib.request</code>, and in that case I am getting <code>http.client.IncompleteRead: IncompleteRead</code> error.</p>
|
<python><python-requests>
|
2024-08-18 08:50:17
| 1
| 1,677
|
Fabio Marzocca
|
78,884,068
| 16,725,431
|
ytdlp download video with fixed output path
|
<p>By default, ytdl adds an extension to the file and I am trying to avoid that.</p>
<p>I created the function below to save video files <em>exactly</em> at <code>output_path</code> (will be further used by some other function).</p>
<pre><code>import logging
import yt_dlp as youtube_dl
from typing import Callable, Any, Optional
import os
def download_video(url: str, output_path: str, progress_hook_func: Callable[[dict], Any] = lambda d: None):
downloaded_file_path: Optional[str] = None
def _progress_hook(d):
nonlocal downloaded_file_path
progress_hook_func(d)
if d['status'] != 'finished':
return
downloaded_file_path = d['filename']
ydl_opts = {
'format': 'bestvideo[height<=720]+bestaudio/best[height<=720]',
'outtmpl': output_path,
'quiet': True, # Suppress console output
'progress_hooks': [_progress_hook],
'logger': logging.Logger("quiet", level=60),
'postprocessors': []
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download([url])
if downloaded_file_path is not None and downloaded_file_path != output_path:
os.rename(downloaded_file_path, output_path)
def test():
download_video(r"https://www.youtube.com/watch?v=Ot2IGEPbe4I", "test", lambda d: print(d))
if __name__ == '__main__':
test()
</code></pre>
<p>However, there is an error:</p>
<pre class="lang-none prettyprint-override"><code>File "C:\Users\USER\PycharmProjects\pythonProject\srcs\algo\download_videos.py", line 60, in download_video
os.rename(downloaded_file_path, output_path)
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'test.f251.webm' -> 'test'
</code></pre>
<p><code>'filename'</code> isn't really filename, it's a tempfile-like path. I checked the working directory and its saved as <code>'test.webp'</code> instead of <code>'test.f251.webm'</code></p>
<p>How can I save the video to a fixed path with no extension?</p>
|
<python><youtube-dl><yt-dlp>
|
2024-08-18 08:14:56
| 1
| 444
|
Electron X
|
78,884,032
| 9,397,607
|
Histogram with bar width not proportional to bar range
|
<p>Using Matplotlib, I want to display a heavily long-tailed distribution, such as the one in the attached picture. Obviously, this figure is not very readable. What I want to achieve is as follows:</p>
<ul>
<li>get a histogram with 4 bars of equal width</li>
<li>the ranges of the bars must be '0', '1-5', '6-25', '26-125'</li>
<li>each bar has its range as a label under the bar</li>
</ul>
<p>How can I achieve this? I keep getting stuck because Matplotlib makes the bars with a smaller range (e.g. '0') incredibly narrow.</p>
<p><a href="https://i.sstatic.net/z1ta3TR5.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/z1ta3TR5.png" alt="the long-tailed distribution" /></a></p>
<p>The attached picture was generated with the following code:</p>
<pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt
# fill each of the ranges with 100 elements
data = [0] * 100 + list(range(1,6)) * 20 + list(range(6,26)) * 5 + list(range(26, 125))
# this generates the attached picture
plt.hist(data, bins=max(data)+1)
</code></pre>
|
<python><matplotlib>
|
2024-08-18 07:59:31
| 1
| 940
|
Jonas De Schouwer
|
78,883,943
| 22,466,650
|
How to identify groups based on id and sign change?
|
<p>My input is a dataframe with one column :</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'ID': ['A1-B1', 'A1-B2', 'A1-B3', 'A1-B8', 'A2-B10', 'A2-B16', 'A2-B9', 'A3-B13', 'A3-B14']})
</code></pre>
<p>I'm trying to create a second column that will identify the groups based on two things :</p>
<ul>
<li>the Axx</li>
<li>the sign change of Bxx</li>
</ul>
<p>Group1 : In A1: the numbers of Bxx are increasing = B1 to B8<br />
Group2 : In A2, the numbers of Bxx are first increasing = B10 to B16<br />
Group3 : In A2, the numbers of Bxx then decreased to B9<br />
Group4 : In A3, the number of Bxx are increasing = B13 to B14</p>
<p>My expected output is this :</p>
<pre><code> ID GROUP
0 A1-B1 1
1 A1-B2 1
2 A1-B3 1
3 A1-B8 1
4 A2-B10 2
5 A2-B16 2
6 A2-B9 3
7 A3-B13 4
8 A3-B14 4
</code></pre>
<p>I tried using an idea of findall and ngroup but it didn't goes well :</p>
<pre><code>new_df = df['ID'].str.findall(r'\d+').apply(lambda x: pd.Series(x))
new_df.columns = ['Axx', 'Bxx']
new_df['GROUP'] = new_df.groupby(['Axx', 'Bxx']).ngroup()
print(new_df)
Axx Bxx GROUP
0 1 1 0
1 1 2 1
2 1 3 2
3 1 8 3
4 2 10 4
5 2 16 5
6 2 9 6
7 3 13 7
8 3 14 8
</code></pre>
<p>Do you guys have a proposition ?</p>
|
<python><pandas>
|
2024-08-18 07:14:36
| 1
| 1,085
|
VERBOSE
|
78,883,931
| 14,724,837
|
How to avoid single block formatting when exporting DataFrame to CSV?
|
<p>I'm facing an issue when exporting a DataFrame to a CSV file using <code>df.to_csv()</code> in pandas. The content in one of my DataFrame columns is multiline text, but when I export it to a CSV file, the entire text block gets written into a single cell without proper line breaks, resulting in an unreadable format.</p>
<p>For example, this is the kind of content I'm dealing with, and I expected it should be like this:</p>
<p><a href="https://i.sstatic.net/kEv1zsyb.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/kEv1zsyb.png" alt="Output from the dataframe" /></a></p>
<p>But after exporting with the following code:</p>
<pre><code>df.to_csv('Findcomposer_updated.csv', index=False, quoting=pd.io.common.csv_quoting.QUOTE_ALL, encoding='utf-8', sep=',', line_terminator='\n')
</code></pre>
<p>It shows</p>
<p><a href="https://i.sstatic.net/FygteC6V.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/FygteC6V.png" alt="Export to csv" /></a></p>
<p>I want the CSV to properly reflect the multiline structure as it appears in the DataFrame, with line breaks, so that each section of the text appears on a new line within the same cell.</p>
<p>For a quick example, my exported csv should be</p>
<pre class="lang-none prettyprint-override"><code>Column: Genre People Content
First row: Fruit Mark The fruit is a peach.
It is very delicious.
Second row: Animal Kiki The animal is a dog.
It is very cute
</code></pre>
<p>But it would be</p>
<pre class="lang-none prettyprint-override"><code>Column: Genre People Content
First row: Fruit Mark The fruit is a peach.
Second row It is very delicious.
Third row: Animal Kiki The animal is a dog.
Fourth row: It is very cute
</code></pre>
|
<python><csv>
|
2024-08-18 07:07:42
| 1
| 689
|
Megan
|
78,883,833
| 1,176,573
|
Use plotly to plot multiple pandas column with a dropdown menu to select column
|
<p>I have a pandas dataframe for which I am trying to a plot bar graph using <code>Plotly</code> with a dropdown menu to select by the stock name column, referring <a href="https://stackoverflow.com/a/56236906/1176573">this answer</a>.</p>
<p>But I am unsure how do I add multiple columns to the <code>updatemenus</code> as the names of the columns could vary.</p>
<pre class="lang-py prettyprint-override"><code>import plotly.graph_objects as go
# plotly setup
fig = go.Figure()
# Add traces, starting from First Column. Each column is a stock data.
for mycolumn in df.columns[1:]:
fig.add_traces( go.Scatter(x=list(df.Quarters), y=list(df[mycolumn])) )
updatemenus = None
for mycolumn in df.columns[1:]:
# construct menus
updatemenus = [{'buttons':
[{'method': 'update',
'label' : column, # what?
'args' : [{'y': [values_1, values_1b]},] # what?
}
'direction': 'down',
'showactive': True,}
]
# update layout with buttons, and show the figure
fig.update_layout(updatemenus=updatemenus)
fig.show()
</code></pre>
<p>The dataframe for ref:</p>
<div class="s-table-container"><table class="s-table">
<thead>
<tr>
<th>Quarters</th>
<th>526433</th>
<th>AARTIIND</th>
<th>DEEPAKNTR</th>
<th>GREENPANEL</th>
<th>METROBRAND</th>
<th>MOLDTECH</th>
<th>MUFTI</th>
<th>MUTHOOTFIN</th>
<th>YASHO</th>
<th>ZENTEC</th>
</tr>
</thead>
<tbody>
<tr>
<td>Mar-21</td>
<td></td>
<td></td>
<td></td>
<td>4.6</td>
<td>1.69</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Jun-21</td>
<td>2.99</td>
<td>4.55</td>
<td>22.19</td>
<td>2.43</td>
<td></td>
<td>1.16</td>
<td></td>
<td>24.37</td>
<td>10.01</td>
<td>-0.14</td>
</tr>
<tr>
<td>Sep-21</td>
<td>3.77</td>
<td>4.14</td>
<td>18.65</td>
<td>5.47</td>
<td>1.89</td>
<td>1.3</td>
<td></td>
<td>24.97</td>
<td>12.44</td>
<td>0</td>
</tr>
<tr>
<td>Dec-21</td>
<td>4.3</td>
<td>20.01</td>
<td>17.78</td>
<td>5.14</td>
<td>3.69</td>
<td>0.59</td>
<td></td>
<td>25.91</td>
<td>12.71</td>
<td>-0.02</td>
</tr>
<tr>
<td>Mar-22</td>
<td>1.54</td>
<td>5.34</td>
<td>19.59</td>
<td>6.57</td>
<td>2.49</td>
<td>1.67</td>
<td></td>
<td>24.84</td>
<td>11.69</td>
<td>0.42</td>
</tr>
<tr>
<td>Jun-22</td>
<td>3.35</td>
<td>3.75</td>
<td>17.2</td>
<td>6.33</td>
<td>3.8</td>
<td>1.1</td>
<td></td>
<td>20.41</td>
<td>16.99</td>
<td>0.94</td>
</tr>
<tr>
<td>Sep-22</td>
<td>2.84</td>
<td>3.42</td>
<td>12.79</td>
<td>5.91</td>
<td>2.72</td>
<td>2.43</td>
<td>80.9</td>
<td>22.22</td>
<td>19.61</td>
<td>0.71</td>
</tr>
<tr>
<td>Dec-22</td>
<td>2.25</td>
<td>3.77</td>
<td>15.33</td>
<td>3.06</td>
<td>4.22</td>
<td>3.26</td>
<td>60.25</td>
<td>23.11</td>
<td>9.18</td>
<td>1.19</td>
</tr>
<tr>
<td>Mar-23</td>
<td>0.25</td>
<td>4.11</td>
<td>17.15</td>
<td>5.62</td>
<td>2.44</td>
<td>3.58</td>
<td>67.43</td>
<td>24.25</td>
<td>13.76</td>
<td>2.54</td>
</tr>
<tr>
<td>Jun-23</td>
<td>0.36</td>
<td>1.93</td>
<td>10.99</td>
<td>3.04</td>
<td>3.91</td>
<td>2.21</td>
<td>1.33</td>
<td>25.46</td>
<td>12.97</td>
<td>5.6</td>
</tr>
<tr>
<td>Sep-23</td>
<td>-1.59</td>
<td>2.51</td>
<td>15.04</td>
<td>3.34</td>
<td>2.92</td>
<td>2.86</td>
<td>4.35</td>
<td>26.39</td>
<td>10.23</td>
<td>1.82</td>
</tr>
<tr>
<td>Dec-23</td>
<td>-0.19</td>
<td>3.42</td>
<td>14.81</td>
<td>2.82</td>
<td>3.52</td>
<td>2.47</td>
<td>2.42</td>
<td>27.49</td>
<td>11.88</td>
<td>3.64</td>
</tr>
<tr>
<td>Mar-24</td>
<td>-2.59</td>
<td>3.64</td>
<td>18.61</td>
<td>2.43</td>
<td>6.05</td>
<td>2.26</td>
<td>1.1</td>
<td>28.37</td>
<td>15.74</td>
<td>4.16</td>
</tr>
<tr>
<td>Jun-24</td>
<td>2.83</td>
<td>3.78</td>
<td>14.85</td>
<td></td>
<td>3.4</td>
<td>1.81</td>
<td>1.51</td>
<td>28.99</td>
<td>-2.16</td>
<td>9.14</td>
</tr>
</tbody>
</table></div>
|
<python><pandas><drop-down-menu><plotly>
|
2024-08-18 06:03:07
| 1
| 1,536
|
RSW
|
78,883,801
| 16,723,655
|
umap.plot requires pandas matplotlib datashader bokeh holoviews scikit-image and colorcet to be installed
|
<pre><code>import sklearn.datasets
pendigits = sklearn.datasets.load_digits()
mapper = umap.UMAP().fit(pendigits.data)
umap.plot.connectivity(mapper, show_points=True)
</code></pre>
<p>Above code gave me the error below.</p>
<pre><code>umap.plot requires pandas matplotlib datashader bokeh holoviews scikit-image and colorcet to be installed
</code></pre>
<p>How to solve the error?</p>
|
<python>
|
2024-08-18 05:39:22
| 2
| 403
|
MCPMH
|
78,883,777
| 14,250,641
|
How to Optimize Memory Usage for Cross-Validation of Large Datasets
|
<p>I have a very large DF (~200GB) of features that I want to perform cross validation on a random forest model with these features.
The features are from a huggingface model in the form of a .arrow file.</p>
<p>I am trying to figure out how I can minimize the amount of RAM needed to process this code-- even with 600GB of RAM, my code crashes.</p>
<p>I believe the issue is I am transforming from a huggingface dataset (<a href="https://huggingface.co/docs/datasets/en/loading" rel="nofollow noreferrer">https://huggingface.co/docs/datasets/en/loading</a>) to a pandas df to a numpy array (see the first 5 lines of code). I tried to figure out a way around this, but unfortunately, I haven't been able to figure it out.</p>
<p>If there are other ways to make my code more RAM efficient, please let me know.</p>
<pre><code># Load data
file_path = 'data.arrow' #200 GB in size
df = Dataset.from_file(file_path)
df = df.data
df = df.to_pandas()
X = np.array([np.array(x) for x in df['embeddings'].values])
y = df['label'].values
groups = df['Chromosome'].values
group_kfold = GroupKFold(n_splits=10)
# Initialize figure for plotting
fig, axes = plt.subplots(1, 2, figsize=(15, 6))
all_fpr = []
all_tpr = []
all_accuracy = []
all_pr_auc = []
best_score = 0
best_model = None
for i, (train_idx, val_idx) in enumerate(group_kfold.split(X, y, groups)):
X_train_fold, X_val_fold = X[train_idx], X[val_idx]
y_train_fold, y_val_fold = y[train_idx], y[val_idx]
# Initialize classifier
rf_classifier = RandomForestClassifier(n_estimators=30, random_state=42, n_jobs=-1)
# Train the classifier on this fold
rf_classifier.fit(X_train_fold, y_train_fold)
# Make predictions on the validation set
y_pred_proba = rf_classifier.predict_proba(X_val_fold)[:, 1]
# Calculate ROC curve
fpr, tpr, _ = roc_curve(y_val_fold, y_pred_proba)
all_fpr.append(fpr)
all_tpr.append(tpr)
roc_auc = auc(fpr, tpr) #
# Keep track of the best model based on ROC AUC
if roc_auc > best_score:
best_score = roc_auc
best_model = rf_classifier
# Plot ROC curve for this fold
axes[0].plot(fpr, tpr, lw=1, alpha=0.7, label=f'ROC Fold {i+1} (AUC = {roc_auc:.2f})')
# Calculate precision-recall curve
precision, recall, _ = precision_recall_curve(y_val_fold, y_pred_proba)
# Calculate PR AUC
pr_auc = auc(recall, precision)
all_pr_auc.append(pr_auc)
# Plot PR curve for this fold
axes[1].plot(recall, precision, lw=1, alpha=0.7, label=f'PR Curve Fold {i+1} (AUC = {pr_auc:.2f})')
# Calculate accuracy
accuracy = accuracy_score(y_val_fold, rf_classifier.predict(X_val_fold))
all_accuracy.append(accuracy)
# Save the best model
joblib.dump(best_model, 'model.pkl')
</code></pre>
|
<python><pandas><dataframe><scikit-learn><huggingface-transformers>
|
2024-08-18 05:13:15
| 1
| 514
|
youtube
|
78,883,527
| 10,589,070
|
Django Choice Dropdown Not Working on Cloned Form in Formset
|
<p>I am cloning my an empty form in django following guidance I've found elsewhere in stack overflow. The JS will append a new form as intendended however the dropdowns from a choice widget are no longer working and I can't figure out why.</p>
<p>I have already validated that all of my options are there using my browser's inspect feature. It appears to be that the javascript isn't working with the object.</p>
<p>This is from the template:</p>
<pre><code>
<form method="post"> {% csrf_token %}
<div id="form_set">
{{ FightForms.management_form|materializecss }}
{% for form in FightForms %}
<div class="card white darken-1 col m12">
<table class='no_error'>
{{ form.non_field_errors }}
<row>
<div class="col m3">
<div class="fieldWrapper">
{{ form.guild_member_id|materializecss }}
</div>
</div>
</row>
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
</table>
</div>
{% endfor %}
</div>
<div class="col m12">
<div>
<input class="btn light-blue lighten-1" type="button" value="Add More" id="add_more">
</div>
<br>
<button class="btn light-blue lighten-1" type="submit">Submit Guild Members</button>
</div>
<div id="empty_form" style="display:none">
<div class="card white darken-1 col m12">
<table class='no_error'>
{{ FightForms.empty_form.non_field_errors }}
<row>
<div class="col m3">
<div class="fieldWrapper">
{{ FightForms.empty_form.guild_member_id|materializecss }}
</div>
</div>
</row>
{% for hidden in form.hidden_fields %}
{{ hidden|materializecss }}
{% endfor %}
</table>
</div>
</div>
</form>
<script>
$('#add_more').click(function() {
var form_idx = $('#id_form-TOTAL_FORMS').val();
$('#form_set').append($('#empty_form').html().replace(/__prefix__/g, form_idx));
$('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1);
});
</script>
</code></pre>
<p>Here are my header imports if it's an issue with versioning or something...</p>
<pre><code><html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0"/>
<title>League Chronicler</title>
<link rel="shortcut icon" type="image/png" href="{% static 'img/CScroll.png' %}"/>
<!-- CSS -->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="{% static 'css/chronicler.css' %}" type="text/css" media="screen,projection"/>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
{% block css %}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
{% endblock css %}
<!-- javascript -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
</code></pre>
<p><strong>EDIT/Update:</strong>
So what appears to be happening is that the javascript/query function isn't copying the that the materialize wants to use as dropdown content. Instead, what is happening is that the script is appending that ul to the #empty_form. So if I hit the add form button 3 times, the empty form will have 4 ul's (original+3) and the new forms won't have any.</p>
<p>Walkthrough:</p>
<p>After clicking the button to add an empty form once I have an empty form without a ul which makes the dropdown appear empty.</p>
<p><a href="https://i.sstatic.net/fzLUvLa6.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/fzLUvLa6.png" alt="enter image description here" /></a></p>
<p>We can see there is no ul in this new form to reference as dropdown content.
<a href="https://i.sstatic.net/iGKEsHj8.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/iGKEsHj8.png" alt="enter image description here" /></a></p>
<p>However, if we look at the blank form, it now has 2 ul's.
<a href="https://i.sstatic.net/EDxnps5Z.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/EDxnps5Z.png" alt="enter image description here" /></a></p>
<p>I believe the ".append()" or ".html()" is causing this.</p>
<pre><code><script>
$('#add_more').click(function() {
var form_idx = $('#id_form-TOTAL_FORMS').val();
$('#form_set').append($('#empty_form').html().replace(/__prefix__/g, form_idx));
$('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1);
});
</script>
</code></pre>
|
<javascript><python><css><django><materialize>
|
2024-08-18 00:35:45
| 1
| 446
|
krewsayder
|
78,883,445
| 1,285,061
|
Find absolute difference value between elements using just NumPy array operations
|
<pre><code>a = np.array([101,105,90,102,90,10,50])
b = np.array([99,110,85,110,85,90,60])
expected result = np.array([2,5,5,8,5,20,10])
</code></pre>
<p>How can I find minimum absolute difference value between elements using just <code>numpy</code> operations; with modulus of 100 if two values are across 100.</p>
|
<python><numpy><numpy-ndarray>
|
2024-08-17 23:16:00
| 4
| 3,201
|
Majoris
|
78,883,312
| 1,405,767
|
Django REST Framework cached view returning 2 different payloads
|
<p>I'm experiencing a strange issue with my Django REST Framework paginated list view, which utilizes a 2 hour cache. If I repeatedly make requests to the view's endpoint, I am sometimes getting Response 1 (x bytes in size) and sometimes getting Response 2 (y bytes in size).</p>
<p>The view code is as follows:</p>
<pre><code>class MyListView(generics.ListAPIView):
model = MyListModel
serializer_class = MyListSerializer
pagination_class = PageNumberPagination
pagination_class.page_size = 1000
def get_queryset(self):
region = self.kwargs.get('region')
sort_param = '-date_created'
return MyListModel.objects.filter(region=region).order_by(sort_param)
@method_decorator(cache_page(2*60*60))
def get(self, *args, **kwargs):
return super().get(*args, **kwargs)
</code></pre>
<p>I'm not sure if this is relevant, but once a day, I run a cronjob which clears all cached views using the following code:</p>
<pre><code>from django.core.cache import cache
cache.clear()
</code></pre>
<p>I have confirmed that the difference in response data from this endpoint is not due to the cache expiring and being replaced with new data. I have also confirmed that the data in the database for <code>MyListModel</code> is not being changed at all. I have also confirmed that the region parameter is consistent between requests.</p>
<p>I'm at a loss for how I could be getting 2 different responses from this endpoint. Cache or no cache, the underlying data is not changing so the response should be consistent. This leads me to believe that there is somehow 2 cached responses being held and sometimes Response 1's cached data is being returned and sometimes Response 2's cached data is being returned. But I still do not know by what mechanism this could possibly occur.</p>
|
<python><django><django-rest-framework>
|
2024-08-17 21:32:52
| 1
| 926
|
stackunderflow
|
78,883,292
| 6,814,154
|
concate column rows with previous rows based on a condition
|
<p>I have this CSV file, (part of a very large one)</p>
<div class="s-table-container"><table class="s-table">
<thead>
<tr>
<th>Course/Section</th>
<th>Credits</th>
<th>Course Name</th>
<th>Time</th>
<th>Building</th>
<th>Instructor</th>
<th>Exam Date</th>
<th>Course Language</th>
</tr>
</thead>
<tbody>
<tr>
<td>ACCT1112/10</td>
<td>3</td>
<td>Introductory Financial</td>
<td>MON</td>
<td>CMT/E07</td>
<td>xxxxxxx</td>
<td>8/5/2022</td>
<td>English</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Accounting</td>
<td>08:00-09:50</td>
<td></td>
<td></td>
<td>SUN</td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>08:00-11:00</td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>E15</td>
<td></td>
</tr>
<tr>
<td>ACCT1112/11</td>
<td>3</td>
<td>Introductory Financial</td>
<td>WED</td>
<td>CMT/E07</td>
<td>xxxxxxx</td>
<td></td>
<td>English</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Accounting</td>
<td>08:00-09:50</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>ACCT1112/20</td>
<td>3</td>
<td>Introductory Financial</td>
<td>MON</td>
<td>CMT/E05</td>
<td>xxxxxxx</td>
<td>8/5/2022</td>
<td>English</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Accounting</td>
<td>10:00-11:50</td>
<td></td>
<td></td>
<td>SUN</td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>08:00-11:00</td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>E16</td>
<td></td>
</tr>
<tr>
<td>ACCT1112/21</td>
<td>3</td>
<td>Introductory Financial</td>
<td>WED</td>
<td>CMT/E05</td>
<td>xxxxxxx</td>
<td></td>
<td>English</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Accounting</td>
<td>10:00-11:50</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>ACCT1112/30</td>
<td>3</td>
<td>Introductory Financial</td>
<td>MON</td>
<td>CMT/E06</td>
<td>xxxxxxx</td>
<td>8/5/2022</td>
<td>English</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Accounting</td>
<td>12:00-13:50</td>
<td></td>
<td></td>
<td>SUN</td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>08:00-11:00</td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>E17</td>
<td></td>
</tr>
<tr>
<td>ACCT1112/31</td>
<td>3</td>
<td>Introductory Financial</td>
<td>WED</td>
<td>CMT/E06</td>
<td>xxxxxxx</td>
<td></td>
<td>English</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Accounting</td>
<td>12:00-13:50</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>ACCT1112/40</td>
<td>3</td>
<td>Introductory Financial</td>
<td>MON</td>
<td>CMT/E23</td>
<td>xxxxxxx</td>
<td>8/5/2022</td>
<td>English</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Accounting</td>
<td>14:15-16:05</td>
<td></td>
<td></td>
<td>SUN</td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>08:00-11:00</td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>E18</td>
<td></td>
</tr>
<tr>
<td>ACCT1112/41</td>
<td>3</td>
<td>Introductory Financial</td>
<td>WED</td>
<td>CMT/E23</td>
<td>xxxxxxx</td>
<td></td>
<td>English</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Accounting</td>
<td>14:15-16:05</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>ACCT1112/50</td>
<td>3</td>
<td>Introductory Financial</td>
<td>SUN</td>
<td>CMT/E27</td>
<td>xxxxxxx</td>
<td>8/5/2022</td>
<td>English</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Accounting</td>
<td>10:00-11:50</td>
<td></td>
<td></td>
<td>SUN</td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>08:00-11:00</td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>E19</td>
<td></td>
</tr>
<tr>
<td>ACCT1112/51</td>
<td>3</td>
<td>Introductory Financial</td>
<td>THU</td>
<td>CMT/E27</td>
<td>xxxxxxx</td>
<td></td>
<td>English</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Accounting</td>
<td>10:00-11:50</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>ACCT1112/60</td>
<td>3</td>
<td>Introductory Financial</td>
<td>TUE</td>
<td>CMT/E16</td>
<td>xxxxxxx-1</td>
<td>8/5/2022</td>
<td>English</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Accounting</td>
<td>10:00-11:50</td>
<td></td>
<td>xxxxxxx-2</td>
<td>SUN</td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>08:00-11:00</td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>E20</td>
<td></td>
</tr>
<tr>
<td>ACCT1112/61</td>
<td>3</td>
<td>Introductory Financial</td>
<td>THU</td>
<td>CMT/E16</td>
<td>mmmmm-1</td>
<td></td>
<td>English</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Accounting</td>
<td>08:00-09:50</td>
<td></td>
<td>mmmmm-2</td>
<td></td>
<td></td>
</tr>
</tbody>
</table></div>
<p><strong>I want to convert it to</strong></p>
<div class="s-table-container"><table class="s-table">
<thead>
<tr>
<th>Course/Section</th>
<th>Credits</th>
<th>Course Name</th>
<th>Time</th>
<th>Building</th>
<th>Instructor</th>
<th>Exam Date</th>
<th>Course Language</th>
</tr>
</thead>
<tbody>
<tr>
<td>ACCT1112/10</td>
<td>3</td>
<td>Introductory Financial Accounting</td>
<td>MON 08:00-09:50</td>
<td>CMT/E07</td>
<td>xxxxxxx</td>
<td>8/5/2022 SUN 08:00-11:00 E15</td>
<td>English</td>
</tr>
<tr>
<td>ACCT1112/11</td>
<td>3</td>
<td>Introductory Financial Accounting</td>
<td>WED 08:00-09:50</td>
<td>CMT/E07</td>
<td>xxxxxxx</td>
<td></td>
<td>English</td>
</tr>
<tr>
<td>ACCT1112/20</td>
<td>3</td>
<td>Introductory Financial Accounting</td>
<td>MON 10:00-11:50</td>
<td>CMT/E05</td>
<td>xxxxxxx</td>
<td>8/5/2022 SUN 08:00-11:00 E16</td>
<td>English</td>
</tr>
<tr>
<td>ACCT1112/21</td>
<td>3</td>
<td>Introductory Financial Accounting</td>
<td>WED 10:00-11:50</td>
<td>CMT/E05</td>
<td>xxxxxxx</td>
<td></td>
<td>English</td>
</tr>
<tr>
<td>ACCT1112/30</td>
<td>3</td>
<td>Introductory Financial Accounting</td>
<td>MON 12:00-13:50</td>
<td>CMT/E06</td>
<td>xxxxxxx</td>
<td>8/5/2022 SUN 08:00-11:00 E17</td>
<td>English</td>
</tr>
<tr>
<td>ACCT1112/31</td>
<td>3</td>
<td>Introductory Financial Accounting</td>
<td>WED 12:00-13:50</td>
<td>CMT/E06</td>
<td>xxxxxxx</td>
<td></td>
<td>English</td>
</tr>
<tr>
<td>ACCT1112/40</td>
<td>3</td>
<td>Introductory Financial Accounting</td>
<td>MON 14:15-16:05</td>
<td>CMT/E23</td>
<td>xxxxxxx</td>
<td>8/5/2022 SUN 08:00-11:00 E18</td>
<td>English</td>
</tr>
<tr>
<td>ACCT1112/41</td>
<td>3</td>
<td>Introductory Financial Accounting</td>
<td>WED 14:15-16:05</td>
<td>CMT/E23</td>
<td>xxxxxxx</td>
<td></td>
<td>English</td>
</tr>
<tr>
<td>ACCT1112/50</td>
<td>3</td>
<td>Introductory Financial Accounting</td>
<td>SUN 10:00-11:50</td>
<td>CMT/E27</td>
<td>xxxxxxx</td>
<td>8/5/2022 SUN 08:00-11:00 E19</td>
<td>English</td>
</tr>
<tr>
<td>ACCT1112/51</td>
<td>3</td>
<td>Introductory Financial Accounting</td>
<td>THU 10:00-11:50</td>
<td>CMT/E27</td>
<td>xxxxxxx</td>
<td></td>
<td>English</td>
</tr>
<tr>
<td>ACCT1112/60</td>
<td>3</td>
<td>Introductory Financial Accounting</td>
<td>TUE 10:00-11:50</td>
<td>CMT/E16</td>
<td>xxxxxxx-1 xxxxxxx-2</td>
<td>8/5/2022 SUN 08:00-11:00 E20</td>
<td>English</td>
</tr>
<tr>
<td>ACCT1112/61</td>
<td>3</td>
<td>Introductory Financial Accounting</td>
<td>THU 08:00-09:50</td>
<td>CMT/E16</td>
<td>mmmmm-1 mmmmm-2</td>
<td></td>
<td>English</td>
</tr>
</tbody>
</table></div>
<p><strong>I tried</strong></p>
<pre><code>for i in range(len(df) - 1, 0, -1):
if pd.isna(df.loc[i, 'Course/Section']):
for col in df.columns:
if pd.notna(df.loc[i, col]):
df.loc[i - 1, col] = f"{df.loc[i - 1, col]} {df.loc[i, col]}" if pd.notna(df.loc[i - 1, col]) else df.loc[i, col]
df = df.dropna(subset=['Course/Section']).reset_index(drop=True)
</code></pre>
<p>But my code does not seem to work as intended.</p>
<p>So, I want to concatenate row values with previous one, one by one from bottom to top as long the column <code>Course/Section</code> is empty until I reach the row where <code>Course/Section</code> is not empty</p>
|
<python><pandas>
|
2024-08-17 21:18:50
| 1
| 4,606
|
Khalil Al Hooti
|
78,882,910
| 16,869,946
|
Complicated nested integrals in terms of python scipy.integrate
|
<p>I want to write the following complicated function using python <code>scipy.integrate</code>:<a href="https://i.sstatic.net/CughB0rk.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/CughB0rk.png" alt="enter image description here" /></a></p>
<p>where \phi and \Phi are the pdf and cdf of the standard normal respectively and the sum i != 1,2 is over the thetas in *theta, and the product s != 1,i,2 is over the thetas in *theta that is not theta_i</p>
<p>To make things simpler, I break down the problem into a few easier pieces by defining a few more functions:</p>
<p><a href="https://i.sstatic.net/KnsWjQlG.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/KnsWjQlG.png" alt="enter image description here" /></a></p>
<p>And here is what I have tried:</p>
<pre class="lang-py prettyprint-override"><code>import scipy.integrate as integrate
from scipy.integrate import nquad
from scipy.stats import norm
import math
import numpy as np
def f(v, u, t1, ti, t2, *theta):
prod = 1
for t in theta:
prod = prod * (1 - norm.cdf(u + t2 - t))
return norm.pdf(v) * norm.cdf(v + ti - t1) * prod
def g(v, u, t1, t2, *theta):
S = 0
for ti in theta:
S = S + integrate.quad(f, -np.inf, u + t2 - ti, args=(u, t1, ti, t2, *theta))[0]
return S * norm.pdf(u)
def P(t1, t2, *theta):
return integrate.quad(g, -np.inf, np.inf, args=(t1, t2, *theta))[0]
</code></pre>
<p>But it doens't work because I think in the definition of P the integral is integrating w.r.t. the first variable, namely v but we should be integrating u but I don't know how we can do that.</p>
<p>Is there any quick way to do it?</p>
<p>For checking, here is what the correct P would produce:</p>
<pre><code>P(0.2, 0.1, 0.3, 0.4) = 0.08856347190679764
P(0.2, 0.1, 0.4, 0.3, 0.5) = 0.06094233268837703
</code></pre>
|
<python><scipy><numerical-integration><quad>
|
2024-08-17 17:47:45
| 1
| 592
|
Ishigami
|
78,882,696
| 2,180,332
|
How to use dynamic type parameters with mypy?
|
<p>I need to build a dynamic union of types to be used to create pydantic models dynamically. I am looking how to type the variable to be passed to the <code>Union</code> so mypy is happy.</p>
<p>A simplified snipped would look like this:</p>
<pre><code>from random import choice, randint
from typing import Union
types = (int, str, bool)
a = tuple(choice(types) for _ in range(randint(1, 10)))
b = Union[a]
</code></pre>
<p>mypy raises a <a href="https://mypy.readthedocs.io/en/stable/error_code_list.html#check-validity-of-types-valid-type" rel="nofollow noreferrer">valid-type</a> with this code, and I am not really sure how to solve it.</p>
<pre><code>example.py:6: error: Variable "example.a" is not valid as a type [valid-type]
example.py:6: note: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases
</code></pre>
<p>The error is the same with <code>a : Tuple[Type, ...]</code>.</p>
|
<python><python-typing><mypy>
|
2024-08-17 16:04:08
| 1
| 4,656
|
azmeuk
|
78,882,661
| 5,790,653
|
How to convert bytes to string in a list of dictionaries
|
<p>I have a list of dictionaries like this:</p>
<pre class="lang-py prettyprint-override"><code>list1 = [
{'id': b'1', 'ip': b'1.1.1.1'},
{'id': b'2', 'ip': b'2.2.2.2'}
]
</code></pre>
<p>How can I convert each value of the dictionaries within a <code>for</code> loop?</p>
<p>I first tried like this, but <code>tuple</code> does have no object assignment:</p>
<pre class="lang-py prettyprint-override"><code>for x in list1:
for y in x.items():
y[1] = y[1].decode('utf8')
print(x)
</code></pre>
<p>Would you please help me?</p>
|
<python>
|
2024-08-17 15:51:04
| 2
| 4,175
|
Saeed
|
78,882,526
| 312,444
|
Substitute elements of an array using JsonPath
|
<p>I am using jsonpath-ng to substitute an element of an array. Given the yaml below:</p>
<pre><code>paths
/api/v1/chats:
get:
- name: other_chats
in: query
required: false
type: boolean
- name: status
in: query
required: false
allOf:
- $ref: '#/definitions/ChatStatus'
</code></pre>
<p>I would like to have this output:</p>
<pre><code>paths
/api/v1/chats:
get:
- name: other_chats
in: query
required: false
type: boolean
- name: status
in: query
required: false
type: string
</code></pre>
<p>I have tried:</p>
<pre><code>all_of_expr = parse("$.paths.*.*.parameters[?(@.allOf)]")
all_of_elements = all_of_expr.find(openapi)
openapi = all_of_expr.update(openapi, {"type": "string"})
</code></pre>
<p>And I am getting:</p>
<pre><code>paths
/api/v1/chats:
get:
- name: other_chats
in: query
required: false
type: boolean
- type: string
</code></pre>
<p>If I try:</p>
<pre><code>all_of_expr = parse("$.paths.*.*.parameters[*].allOf")
all_of_elements = all_of_expr.find(openapi)
openapi = all_of_expr.update(openapi, {"type": "string"})
paths
/api/v1/chats:
get:
- name: other_chats
in: query
required: false
type: boolean
- name: status
in: query
required: false
allOf:
type: string
</code></pre>
|
<python><jsonpath><jsonpath-ng>
|
2024-08-17 14:51:56
| 1
| 8,446
|
p.magalhaes
|
78,882,469
| 16,869,946
|
New rows in Pandas Dataframe by considering combination of rows in the original dataframe and applying function to it
|
<p>I have a Pandas dataframe df that looks like</p>
<pre><code>Class_ID Student_ID theta
6 1 0.2
6 2 0.2
6 4 0.1
6 3 0.5
3 2 0.1
3 5 0.2
3 7 0.22
3 4 0.4
3 9 0.08
</code></pre>
<p>And I want to create a new dataframe by considering every <code>Student_ID</code> combination within the same <code>Class_ID</code>:</p>
<pre><code>Class_ID Student_ID_x theta_x Student_ID_y theta_y Student_Combination
6 1 0.20 2 0.20 1_2
6 1 0.20 4 0.10 1_4
6 1 0.20 3 0.50 1_3
6 2 0.20 4 0.10 2_4
6 2 0.20 3 0.50 2_3
6 3 0.50 4 0.10 3_4
3 2 0.10 5 0.20 2_5
3 2 0.10 7 0.22 2_7
3 2 0.10 4 0.40 2_4
3 2 0.10 9 0.08 2_9
3 5 0.20 7 0.22 5_7
3 5 0.20 9 0.08 5_9
3 7 0.22 9 0.08 7_9
3 4 0.40 5 0.20 4_5
3 4 0.40 7 0.22 4_7
3 4 0.40 9 0.08 4_9
</code></pre>
<p>My code for this is</p>
<pre><code>df_new = df.merge(
df,
how='inner',
on=['Class_ID']
)
df_new['Student_ID_x'] = df_new['Student_ID_x'].astype(int)
df_new['Student_ID_y'] = df_new['Student_ID_y'].astype(int)
df_new = df_new[df_new['Student_ID_x'] < df_new['Student_ID_y']]
df_new['Student_Combination'] = [f'{x}_{y}' for x, y in zip(df_new['Student_ID_x'], df_new['Student_ID_y'])]
</code></pre>
<p>and this works fine. However, for the new df <code>df_new</code>, I want to create a new column called <code>feature</code> for every <code>Student_Combination</code> by applying a function defined as follow:</p>
<pre><code>def func(theta_x, theta_y, *theta):
numerator = theta_x + theta_y
denominator = 0
for t in theta:
denominator += t*t
return numerator / denominator
</code></pre>
<p>where the <code>*theta</code>'s are the <code>theta</code>'s from the same <code>Class_ID</code> other than the original 2 students. So for example, for <code>Student_Combination = 1_2</code> in Class 6, the feature equals (0.2+0.2)/(0.1^2+0.5^2) = 1.53846154</p>
<p>and the desired output looks like</p>
<pre><code>Class_ID Student_ID_x theta_x Student_ID_y theta_y Student_Combination feature
6 1 0.20 2 0.20 1_2 1.53846154
6 1 0.20 4 0.10 1_4 1.03448276
6 1 0.20 3 0.50 1_3 14
6 2 0.20 4 0.10 2_4 1.03448276
6 2 0.20 3 0.50 2_3 14
6 3 0.50 4 0.10 3_4 7.5
3 2 0.10 5 0.20 2_5 1.39664804
3 2 0.10 7 0.22 2_7 1.5503876
3 2 0.10 4 0.40 2_4 5.2742616
3 2 0.10 9 0.08 2_9 1.28205128
3 5 0.20 7 0.22 5_7 2.38095238
3 5 0.20 9 0.08 5_9 1.28205128
3 7 0.22 9 0.08 7_9 1.42857143
3 4 0.40 5 0.20 4_5 9.25925926
3 4 0.40 7 0.22 4_7 10.9929078
3 4 0.40 9 0.08 4_9 4.87804878
</code></pre>
<p>And I have no idea how to do this. Thanks in advance</p>
|
<python><pandas><dataframe><group-by>
|
2024-08-17 14:30:48
| 3
| 592
|
Ishigami
|
78,882,366
| 11,565,514
|
Delete div and label for that div without label id
|
<p>Using Crispy forms in Django app, I the HTML code:</p>
<pre><code><div id="div_id_pripadnost" class="form-group"> <label for="id_pripadnost_0" class="">
Pripadnost
</label>
<div class="">
<div class="form-check"> <input type="radio" class="form-check-input" name="pripadnost" id="id_pripadnost_1" value=""> <label for="id_pripadnost_1" class="form-check-label">
---------
</label> </div>
<div class="form-check"> <input type="radio" class="form-check-input" checked="checked" name="pripadnost" id="id_pripadnost_2" value="CRS"> <label for="id_pripadnost_2" class="form-check-label">
CRS
</label> </div>
<div class="form-check"> <input type="radio" class="form-check-input" name="pripadnost" id="id_pripadnost_3" value="SCM"> <label for="id_pripadnost_3" class="form-check-label">
SCM
</label>
</div> </div> </div>
</code></pre>
<p>I would like to remove <code>div</code> with <code>id="id_pripadnost_1"</code>. I have removed <code>radio button/div "form-check"</code>, but I can't remove <code>label '---------'</code>, since it doesn't have an id. How can you remove that label?</p>
<p>I have tried:</p>
<pre><code> const radioBtn = document.getElementById('id_pripadnost_1');
radioBtn.style.display = 'none';
radioBtn.previousElementSibling.style.display = 'none';
</code></pre>
<pre><code> document.getElementById('id_pripadnost_1').remove();
</code></pre>
|
<javascript><python><html><django><django-crispy-forms>
|
2024-08-17 13:39:15
| 1
| 373
|
MarkoZg
|
78,882,352
| 5,451,769
|
Plotting a timeseries as bar plot with pandas results in an incorrect year
|
<p>I have the following dataframe (except my actual data is over 25 years):</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
df = pd.DataFrame(
dict(
date=pd.date_range(start="2020-01-01", end="2020-12-31", freq="MS"),
data=[1,2,3,4,5,6,7,8,9,10,11,12]
),
)
df
</code></pre>
<p>Output:</p>
<pre><code> date data
0 2020-01-01 1
1 2020-02-01 2
2 2020-03-01 3
3 2020-04-01 4
4 2020-05-01 5
5 2020-06-01 6
6 2020-07-01 7
7 2020-08-01 8
8 2020-09-01 9
9 2020-10-01 10
10 2020-11-01 11
11 2020-12-01 12
</code></pre>
<p>And I get different results with matplotlib and pandas default plotting:</p>
<pre class="lang-py prettyprint-override"><code>import matplotlib as mpl
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
fig = mpl.figure.Figure(constrained_layout=True)
axs = fig.subplot_mosaic("ac;bd")
ax = axs["a"]
ax.bar(x="date", height="data", data=df, width=15)
ax = axs["b"]
ax.bar(x="date", height="data", data=df, width=15)
locator = mdates.AutoDateLocator(minticks=12, maxticks=24)
formatter = mdates.ConciseDateFormatter(locator)
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)
ax = axs["c"]
df.plot.bar(x="date", y="data", ax=ax, legend=False)
ax = axs["d"]
df.plot.bar(x="date", y="data", ax=ax, legend=False, ) # incorrect year -> 1970 instead of 2020
locator = mdates.AutoDateLocator(minticks=12, maxticks=24)
formatter = mdates.ConciseDateFormatter(locator)
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)
for k, ax in axs.items():
for label in ax.get_xticklabels():
label.set_rotation(40)
label.set_horizontalalignment('right')
fig
</code></pre>
<p>Output:</p>
<p><a href="https://i.sstatic.net/E48H4AgZ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/E48H4AgZ.png" alt="enter image description here" /></a></p>
<p>I would like to be able to use pandas for plotting but then format the ticks appropriately for a publication ready plot. However, it appears that I lose the date time information or get the incorrect year when using pandas.</p>
<p>Is there a way to format the axis ticklabels using <code>mdates</code> features without using the data directly? i.e. if I resample the data, or slice in a different year, I'd like the axis to reflect that automatically.</p>
<hr />
<p>Here's a more simple illustration of the issue I'm having:</p>
<pre class="lang-py prettyprint-override"><code>import matplotlib as mpl
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
fig = mpl.figure.Figure(constrained_layout=True)
axs = fig.subplot_mosaic("a")
ax = axs["a"]
df.plot.bar(x="date", y="data", ax=ax, legend=False) # incorrect year -> 1970 instead of 2020
formatter = mdates.DateFormatter("%Y - %b")
ax.xaxis.set_major_formatter(formatter)
fig
</code></pre>
<p><a href="https://i.sstatic.net/8296NElT.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/8296NElT.png" alt="enter image description here" /></a></p>
<p>The dates are all wrong when using <code>DateFormatter</code>.</p>
|
<python><pandas><dataframe><matplotlib><plot>
|
2024-08-17 13:33:37
| 1
| 1,366
|
kdheepak
|
78,882,326
| 8,545,455
|
Python ruamel.yaml - ensure quotes on specific keys
|
<p>Following on from this question: <a href="https://stackoverflow.com/questions/55808945/json-to-yaml-in-python-how-to-get-correct-string-manipulation">JSON to YAML in Python : How to get correct string manipulation?</a></p>
<p>I'd like to have specific key names (regardless of nesting depth) always given a double-quote style. This is the starting point:</p>
<pre class="lang-py prettyprint-override"><code>import sys
from ruamel.yaml import YAML
data = {
'simple': 'nonquoted',
'grouping': 'quoted',
'deep': {
'simple': 'nonquoted',
'grouping': 'quoted',
}
}
def test():
yaml = YAML()
yaml.default_flow_style = False
yaml.dump(data, sys.stdout)
test()
</code></pre>
<p>which currently gives:</p>
<pre><code>simple: nonquoted
grouping: quoted
deep:
simple: nonquoted
grouping: quoted
</code></pre>
<p>Id like it to be:</p>
<pre><code>simple: nonquoted
grouping: "quoted"
deep:
simple: nonquoted
grouping: "quoted"
</code></pre>
<p>I've looked at adding representers, but I got stuck.</p>
<p>I have Python 3.10.13 and ruamel.yaml 0.18.6.</p>
<p>Update: I'm able to do this by walking the tree, applying the <code>ruamel</code> specific type <code>DoubleQuotedScalarString</code></p>
<p>but maybe there is a way to do it on <code>dump</code>?</p>
<pre class="lang-py prettyprint-override"><code># Function to preprocess in-place the dictionary to quote values for specific keys
def preprocess_dict_in_place(data, doubleQuoteKeys={}):
if isinstance(data, dict):
for key in list(data.keys()):
if key in doubleQuoteKeys:
data[key] = DoubleQuotedScalarString(data[key])
elif isinstance(data[key], dict):
preprocess_dict_in_place(data[key], doubleQuoteKeys)
elif isinstance(data[key], list):
for index in range(len(data[key])):
preprocess_dict_in_place(data[key][index], doubleQuoteKeys)
elif isinstance(data, list):
for index in range(len(data)):
preprocess_dict_in_place(data[index])
</code></pre>
|
<python><ruamel.yaml>
|
2024-08-17 13:19:18
| 1
| 1,237
|
tuck1s
|
78,882,235
| 15,218,250
|
How can I send a batch email using postmark in Anymail for Django?
|
<p>I am trying to use the Anymail API for postmark in my Django application. This is not the same as putting a list of emails in the cc, but I am trying to send a separate email to each individual email address (the email content is the same though). Right now, I have the following to send transactional (one-time) emails. I need this to work with html contents as well!</p>
<pre><code>from anymail.message import AnymailMessage
email = AnymailMessage(
subject=subject,
body=body,
from_email=from_email,
to=to,
)
email.attach_alternative(html_content, "text/html")
email.esp_extra = {
'MessageStream': message_stream, # Specify the message stream
}
</code></pre>
<p>I initially tried using a for loop to send a separate email to each email address, but that consumed too much time and the page couldn't load long enough. How can I then achieve this batch email send in Django using Anymail?</p>
<p>Please leave a comment if you have any questions.</p>
|
<python><django><email><django-anymail>
|
2024-08-17 12:37:36
| 1
| 613
|
coderDcoder
|
78,882,184
| 7,784,017
|
How to properly reload a module in Python
|
<p>This question has been asked many times, here are a few for reference:</p>
<p><a href="https://stackoverflow.com/questions/1254370/reimport-a-module-while-interactive">Reimport a module while interactive</a></p>
<p><a href="https://stackoverflow.com/questions/2534480/proper-way-to-reload-a-python-module-from-the-console">Proper way to reload a python module from the console</a></p>
<p><a href="https://stackoverflow.com/questions/7271082/how-to-reload-a-modules-function-in-python">How to reload a module's function in Python?</a></p>
<p>From what I searched and learned, I have wrote the following but it fails to properly reload the module:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
pd.get_option('display.width') # 80
pd.set_option("display.width", 150)
del pd
import importlib
import sys
pd = importlib.reload(sys.modules['pandas'])
pd.get_option('display.width') # 150
</code></pre>
|
<python><module><python-import>
|
2024-08-17 12:11:18
| 1
| 876
|
Shayan
|
78,882,159
| 5,923,374
|
How to validate with RetrievalMetric in Lightning on multiple GPU?
|
<p>I want to compute retrieval metric in distributed setting with torch lightning.</p>
<p>Retrieval metrics compute metrics over groups of inputs. This is a problem in distributed setting, because the groups get split between different batches, so just logging the metric in validation step will result in incorrect output. Therefore, I need to aggregate all batch inputs and predictions first before computing the final metric.</p>
<p>However, as of now, lightning 2.4.0 does not have any out of the box support for this use case. The <a href="https://lightning.ai/docs/pytorch/stable/common/lightning_module.html" rel="nofollow noreferrer">documentation</a> only briefly mentions, that you need to aggregate the results yourself into a mutable list:</p>
<pre class="lang-py prettyprint-override"><code>class LightningTransformer(L.LightningModule):
def __init__(self, vocab_size):
...
self.validation_step_outputs = []
def validation_step(self, batch, batch_idx, dataloader_ix):
x, y, group = batch
preds = self.model(x, y)
self.validation_step_outputs.append([y,group,preds])
return loss
def on_validation_epoch_end(self):
y, group, preds = torch.stack(self.validation_step_outputs)
metric = self.retrival_metric(preds, y, group)
self.validation_step_outputs.clear() # free memory
</code></pre>
<p>However, this approach does not account for multiple gpus and multiple validation datasets. Also, it seems awfully convoluted for something that should be supported out of the box.</p>
<p><strong>What is the correct way to compute eg. <code>torchmetrics.RetrievalNormalizedDCG</code> for several validation datasets on 2+ devices</strong>?</p>
|
<python><pytorch-lightning>
|
2024-08-17 11:56:51
| 1
| 1,538
|
Ford O.
|
78,882,117
| 3,752,268
|
AssertionError when assigning set with a single element in numba njit method
|
<p>I'm trying to use numba's njit decorator to optimize a method. I'm getting an error that seems to be caused by defining a set with multiple elements, then overwriting it with a set with a single element (or vice versa).
I'm running python 3.10.12, numba version 0.60.0.</p>
<p>The following minimal example reproduces the error</p>
<pre><code>import numba
@numba.njit
def foo(n: int):
s = {1, 2, 3}
if n == 1:
pass
else:
s = {2} # This causes an error
# s = {2, 3, 4} # This works
res = sum(list(s))
return res
def main():
res = foo(2)
print(res)
if __name__ == '__main__':
main()
</code></pre>
<p>According to the <a href="https://numba.readthedocs.io/en/stable/reference/pysupported.html#set" rel="nofollow noreferrer">numba docs</a></p>
<blockquote>
<p>All methods and operations on sets are supported in JIT-compiled functions.</p>
</blockquote>
<p>so I don't understand what causes an error in this case. Even doing <code>sum(s)</code> without converting to a list beforehand throws an error.</p>
<p>What is the cause of the error, and how can I make it work?</p>
|
<python><numba>
|
2024-08-17 11:41:15
| 1
| 2,816
|
bjarkemoensted
|
78,882,013
| 1,785,063
|
Errors while trying to install matplotlib
|
<p>I am not python expert and this project used to work but now giving me massive red errors while trying to build the project:</p>
<p><code>pip2 install -r requirements.txt --no-cache-dir</code></p>
<p>Can somebody help me to figure out how to fix it. It seems the issue related to <code>matplotlib</code> and <code>numpy</code> as far as I could tell.</p>
<p>I am using macOS Sonoma 14.4.1 (23E224).
python version: Python 2.7.18
and pip version: pip 20.3.4.</p>
<p>this is my requirement file:</p>
<pre><code>astropy == 2.0.16
atomicwrites == 1.4.0
attrs == 21.2.0
backports.functools-lru-cache == 1.6.4
bidict == 0.18.4
colorama == 0.4.4
cycler == 0.10.0
funcsigs == 1.0.2
kiwisolver == 1.1.0
matplotlib == 2.2.5
mock == 1.3.0
more-itertools == 5.0.0
nose == 1.3.7
numpy == 1.16.6
pandas == 0.24.2
pbr == 1.3.0
pluggy == 0.7.1
py == 1.11.0
pyparsing == 2.4.7
python-dateutil == 2.8.2
pytz == 2021.3
scipy == 1.2.3
six == 1.16.0
tk == 0.1.0
tqdm == 4.62.3
wheel == 0.24.0
lmfit == 0.9.15
</code></pre>
<pre><code>ERROR: Command errored out with exit status 1:
command: /Users/duaa.jaber/personalWorkSpace/asad/asad_dev_0.1.0/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/t_/b3qw1kjj7sx5gxc_10fdxnbr0000gq/T/pip-install-kadPSo/matplotlib/setup.py'"'"'; __file__='"'"'/private/var/folders/t_/b3qw1kjj7sx5gxc_10fdxnbr0000gq/T/pip-install-kadPSo/matplotlib/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/t_/b3qw1kjj7sx5gxc_10fdxnbr0000gq/T/pip-pip-egg-info-EdE3Nz
cwd: /private/var/folders/t_/b3qw1kjj7sx5gxc_10fdxnbr0000gq/T/pip-install-kadPSo/matplotlib/
Complete output (3002 lines):
============================================================================
Edit setup.cfg to change the build options
BUILDING MATPLOTLIB
matplotlib: yes [2.2.5]
python: yes [2.7.18 (default, May 18 2024, 18:29:57) [GCC
Apple LLVM 15.0.0 (clang-1500.3.9.4)]]
platform: yes [darwin]
REQUIRED DEPENDENCIES AND EXTENSIONS
numpy: yes [not found. pip may install it below.]
install_requires: yes [handled by setuptools]
libagg: yes [pkg-config information for 'libagg' could not
be found. Using local copy.]
freetype: yes [version 2.13.2]
png: yes [version 1.6.43]
qhull: yes [pkg-config information for 'libqhull' could not
be found. Using local copy.]
OPTIONAL SUBPACKAGES
sample_data: yes [installing]
toolkits: yes [installing]
tests: no [skipping due to configuration]
toolkits_tests: no [skipping due to configuration]
OPTIONAL BACKEND EXTENSIONS
macosx: yes [installing, darwin]
qt5agg: no [PySide2 not found; PyQt5 not found]
qt4agg: no [PySide not found; PyQt4 not found]
gtk3agg: no [Requires pygobject to be installed.]
DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support pip 21.0 will remove support for this functionality.
ERROR: Command errored out with exit status 1:
command: /Users/duaa.jaber/personalWorkSpace/asad/asad_dev_0.1.0/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/t_/b3qw1kjj7sx5gxc_10fdxnbr0000gq/T/pip-wheel-3XAIjW/numpy/setup.py'"'"'; __file__='"'"'/private/var/folders/t_/b3qw1kjj7sx5gxc_10fdxnbr0000gq/T/pip-wheel-3XAIjW/numpy/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /private/var/folders/t_/b3qw1kjj7sx5gxc_10fdxnbr0000gq/T/pip-wheel-lhR0EK
cwd: /private/var/folders/t_/b3qw1kjj7sx5gxc_10fdxnbr0000gq/T/pip-wheel-3XAIjW/numpy/
Complete output (2908 lines):
Running from numpy source directory.
blas_opt_info:
blas_mkl_info:
customize UnixCCompiler
libraries mkl_rt not found in ['/Users/duaa.jaber/personalWorkSpace/asad/asad_dev_0.1.0/lib', '/usr/local/lib', '/usr/lib']
NOT AVAILABLE
blis_info:
customize UnixCCompiler
libraries blis not found in ['/Users/duaa.jaber/personalWorkSpace/asad/asad_dev_0.1.0/lib', '/usr/local/lib', '/usr/lib']
NOT AVAILABLE
openblas_info:
customize UnixCCompiler
customize UnixCCompiler
libraries openblas not found in ['/Users/duaa.jaber/personalWorkSpace/asad/asad_dev_0.1.0/lib', '/usr/local/lib', '/usr/lib']
NOT AVAILABLE
atlas_3_10_blas_threads_info:
Setting PTATLAS=ATLAS
customize UnixCCompiler
libraries tatlas not found in ['/Users/duaa.jaber/personalWorkSpace/asad/asad_dev_0.1.0/lib', '/usr/local/lib', '/usr/lib']
NOT AVAILABLE
atlas_3_10_blas_info:
customize UnixCCompiler
libraries satlas not found in ['/Users/duaa.jaber/personalWorkSpace/asad/asad_dev_0.1.0/lib', '/usr/local/lib', '/usr/lib']
NOT AVAILABLE
atlas_blas_threads_info:
Setting PTATLAS=ATLAS
customize UnixCCompiler
libraries ptf77blas,ptcblas,atlas not found in ['/Users/duaa.jaber/personalWorkSpace/asad/asad_dev_0.1.0/lib', '/usr/local/lib', '/usr/lib']
NOT AVAILABLE
atlas_blas_info:
customize UnixCCompiler
libraries f77blas,cblas,atlas not found in ['/Users/duaa.jaber/personalWorkSpace/asad/asad_dev_0.1.0/lib', '/usr/local/lib', '/usr/lib']
NOT AVAILABLE
accelerate_info:
FOUND:
extra_link_args = ['-Wl,-framework', '-Wl,Accelerate']
define_macros = [('NO_ATLAS_INFO', 3), ('HAVE_CBLAS', None)]
extra_compile_args = ['-faltivec', '-I/System/Library/Frameworks/vecLib.framework/Headers']
FOUND:
extra_link_args = ['-Wl,-framework', '-Wl,Accelerate']
define_macros = [('NO_ATLAS_INFO', 3), ('HAVE_CBLAS', None)]
extra_compile_args = ['-faltivec', '-I/System/Library/Frameworks/vecLib.framework/Headers']
/bin/sh: svnversion: command not found
non-existing path in 'numpy/distutils': 'site.cfg'
lapack_opt_info:
lapack_mkl_info:
customize UnixCCompiler
libraries mkl_rt not found in ['/Users/duaa.jaber/personalWorkSpace/asad/asad_dev_0.1.0/lib', '/usr/local/lib', '/usr/lib']
NOT AVAILABLE
openblas_lapack_info:
customize UnixCCompiler
customize UnixCCompiler
libraries openblas not found in ['/Users/duaa.jaber/personalWorkSpace/asad/asad_dev_0.1.0/lib', '/usr/local/lib', '/usr/lib']
NOT AVAILABLE
openblas_clapack_info:
customize UnixCCompiler
customize UnixCCompiler
libraries openblas,lapack not found in ['/Users/duaa.jaber/personalWorkSpace/asad/asad_dev_0.1.0/lib', '/usr/local/lib', '/usr/lib']
NOT AVAILABLE
</code></pre>
<p>I can't post the whole error body as it is 3000+ lines.</p>
|
<python><matplotlib><macos-sonoma>
|
2024-08-17 10:47:26
| 1
| 347
|
Duaa Zahi
|
78,881,895
| 315,168
|
Using short (native) tracebacks in Jupyter Notebooks
|
<p>Currently Jupyter Notebook, as run in Visual Studio Code, uses its verbose traceback output, outputting code samples where the exception propagated. This is the opposite of Python native traceback that only gives you the file and line number.</p>
<p>Example snippet:</p>
<pre><code>UnboundLocalError Traceback (most recent call last)
Cell In[18], line 3
1 from tradeexecutor.backtest.backtest_runner import run_backtest_inline
----> 3 result = run_backtest_inline(
4 name=parameters.id,
5 engine_version="0.5",
6 decide_trades=decide_trades,
7 create_indicators=create_indicators,
8 client=client,
9 universe=strategy_universe,
10 parameters=parameters,
11 strategy_logging=False,
12 max_workers=1
13 )
15 state = result.state
17 trade_count = len(list(state.portfolio.get_all_trades()))
File ~/code/executor/trade-executor/tradeexecutor/backtest/backtest_runner.py:1009, in run_backtest_inline(start_at, end_at, minimum_data_lookback_range, client, decide_trades, create_trading_universe, create_indicators, indicator_combinations, indicator_storage, cycle_duration, initial_deposit, reserve_currency, trade_routing, universe, routing_model, max_slippage, candle_time_frame, log_level, data_preload, data_delay_tolerance, name, allow_missing_fees, engine_version, strategy_logging, parameters, mode, max_workers, grid_search, execution_context, execution_test_hook, *ignore)
978 execution_context.mode = mode
980 backtest_setup = BacktestSetup(
981 start_at,
982 end_at,
(...)
1006 grid_search=grid_search,
1007 )
-> 1009 result = run_backtest(
1010 backtest_setup,
1011 client,
1012 allow_missing_fees=True,
1013 execution_context=execution_context,
1014 execution_test_hook=execution_test_hook,
1015 )
1017 result.diagnostics_data["wallet"] = wallet
1019 #: TODO: Hack to pass the backtest data range to the grid search
...
-> More than 1000 lines follows
</code></pre>
<p>The problem is that this format is extremely long, and for complex code with long stack, it makes it painful to read due to amount of scrolling required.</p>
<ul>
<li>Is it possible to force Jupyter Notebook to use normal, shorter, Python traceback output?</li>
<li>Are there other ways to make traceback output more manageable in Jupyter Notebook (or Visual Studio Code?)</li>
</ul>
|
<python><jupyter-notebook>
|
2024-08-17 09:50:25
| 0
| 84,872
|
Mikko Ohtamaa
|
78,881,845
| 874,380
|
How to open a Github folder in Google Colab?
|
<p>I have a GitHub repository with the following general structure</p>
<pre><code>repository/
-- topic1/
-- topic2/
-- topic3/
---- data/
---- src/
------ notebook3.1.ipynb
------ notebook3.2.ipynb
------ notebook3.3.ipynb
-- topic4/
-- topic5/
...
</code></pre>
<p>The notebooks belonging to the same notebook may access the same data. For example, one notebook may preprocess some data and save to <code>data/</code> and then a subsequent notebook loads and works with this preprocessed data. Also the notebooks might import some utility methods provided by <code>.py</code> files in the <code>src/</code> folder.</p>
<p>I make this repository available to my students and currently always assume that the students clone or download the repository and run the notebooks locally. This works of course perfectly fine.</p>
<p>Now I wonder if there's an (easy) way to also share those notebooks to less tech-savvy users who do not have their own Jupyter setup locally running on their PCs or laptops. Ideally, I would like to take the Github link for a whole topic and share it with others. For example, if I share "some" link for topic 3, users should see</p>
<pre><code>topic3/
-- data/
-- src/
---- notebook3.1.ipynb
---- notebook3.2.ipynb
---- notebook3.3.ipynb
</code></pre>
<p>in their Google Colab.</p>
<p>I know that it is reasonably straightforward to open individual notebooks hosted on Github in Google Colab, e.g., by replacing "github" with "githubtocolab" in the URL. However, unsurprisingly this breaks codes such as</p>
<ul>
<li><p><code>from src.utils import plot_data(df)</code></p>
</li>
<li><p><code>df=pd.read_csv('data/demo.csv')</code></p>
</li>
</ul>
<p>I also assume that notebooks running on Colab this way are independent? For example, even if <code>notebook3.1.ipynb</code> and <code>notebook3.2.ipynb</code> see some <code>data/</code> folder, would it be the same?</p>
<p>Is there an easy and systematic way to share a complete folder with multiple notebooks and subfolders on Google Colab? Or is this simply not possible?</p>
|
<python><github><jupyter-notebook><google-colaboratory>
|
2024-08-17 09:21:48
| 0
| 3,423
|
Christian
|
78,881,781
| 315,427
|
How to determine model changes?
|
<p>My <code>QListView</code> class is feed by <code>QAbstractListModel</code>, where I've implemented insert, remove, update rows. There is no problem between model and list view. However, I would like to subscribe to model change to do some custom calculations.</p>
<p>For that I can't find any events neither in QListView nor in QAbstractListModel, to which I can connect and receive signal something like onDataChanged.</p>
<p>Below is a sample code to demonstrate details.</p>
<pre><code>class WorktimeListModel(QAbstractListModel):
...
def addItem(self, data):
index = QModelIndex()
self.beginInsertRows(index, self.rowCount(index), self.rowCount(index))
...
self.endInsertRows()
def modifyItem(self, index, data):
self.beginResetModel()
...
self.endResetModel()
</code></pre>
<p>Somewhere in main window class:</p>
<pre><code>...
self.customWorktimesModel = WorktimeListModel()
self.listViewWorktimes.setModel(self.customWorktimesModel)
# I need something like this
self.listViewWorktimes.onModelChanged.connect(self.updateLabel)
# or this
self.customWorktimesModel.onModelChanged.connect(self.updateLabel)
...
def updateLabel(self):
value = self.customWorktimesModel.calculate_something()
self.label.setText(value)
</code></pre>
|
<python><pyqt><pyqt6>
|
2024-08-17 08:50:41
| 1
| 29,709
|
Pablo
|
78,881,333
| 865,220
|
Group by and transform the value each group with its median
|
<p>I have a Pandas dataframe with data like this:</p>
<pre><code>Name,Year,Value
----------------
Wendys,2021,6915
Wendys,2021,6916
Wendys,2022,6943
Wendys,2022,7016
Wendys,2022,7026
Wendys,2022,7028
Wendys,2023,7055
Wendys,2023,7128
Wendys,2023,7129
Wendys,2023,7138
Wendys,2023,7140
Wendys,2024,7166
White Castle,1950,88
White Castle,1950,90
White Castle,1951,91
White Castle,1951,92
White Castle,1951,93
</code></pre>
<p>I want to transform it to this:</p>
<pre><code>Name,Year,Value
----------------
Wendys,2021,6915.5
Wendys,2022,6979.5
Wendys,2023,7129
Wendys,2024,7166
White Castle,1950,89
White Castle,1951,92
</code></pre>
<p><strong>Note above:</strong></p>
<ul>
<li><code>6915.5 is median(6915,6916)</code></li>
<li><code>7129 is median(7055,7128,7129,7138,7140)</code></li>
</ul>
|
<python><pandas><dataframe>
|
2024-08-17 03:43:35
| 1
| 18,382
|
ishandutta2007
|
78,881,240
| 5,003,606
|
Decimal shift behaves bizarrely if constructed from float
|
<p>Consider the following Python code:</p>
<pre class="lang-py prettyprint-override"><code>from decimal import Decimal
d = Decimal("1.23")
print(f"{d = }, {d.shift(1) = }")
</code></pre>
<p>When I execute it in Python 3.12.4, I get this output:</p>
<pre class="lang-none prettyprint-override"><code>d = Decimal('1.23'), d.shift(1) = Decimal('12.30')
</code></pre>
<p>This is exactly the output that I expect: the shift operation, given an arg of positive 1, left shifted 1.23 by 1 decimal point, producing 12.30</p>
<p>Now execute this code:</p>
<pre class="lang-py prettyprint-override"><code>from decimal import Decimal
d = Decimal(1.23)
print(f"{d = }, {d.shift(1) = }")
</code></pre>
<p>The sole difference is that we construct d using a float instead of a str.</p>
<p>When I execute it, I get this output:</p>
<pre class="lang-none prettyprint-override"><code>d = Decimal('1.229999999999999982236431605997495353221893310546875'), d.shift(1) = Decimal('6.059974953532218933105468750E-24')
</code></pre>
<p>The first part of that output is what I expect: the float for 1.23 cannot perfectly represent the base 10 digits; this is expected floating point error.</p>
<p>But the output from shift(1) was strange. I was expecting it to be something like <code>Decimal('12.29999999999999982236431605997495353221893310546875')</code>. (That is, a value fairly close to 12.30.) Instead, it produced a completely unrelated result like <code>Decimal('6.059974953532218933105468750E-24')</code>.</p>
<p>Why does the shift method produces such radically different results when you construct the Decimal from a float?</p>
|
<python><floating-point><decimal><shift>
|
2024-08-17 02:02:30
| 1
| 951
|
HaroldFinch
|
78,881,135
| 1,189,239
|
Why does my Bayesian linear regression with survival analysis perform worse than standard linear regression?
|
<p>Experts in statistics wanted here.</p>
<p>I am working on a Bayesian linear regression function that considers asymmetric uncertainties and censored data (upper/lower limits) in both x and y. The function uses the emcee MCMC package to estimate the posterior distributions of the slope and intercept. Despite taking into account these complexities, I find that a simple linear regression (done with scipy’s stats.linregress) or a basic Bayesian linear regression using emcee without considering the uncertainties and limits performs better on simulated data.</p>
<p>My function:</p>
<pre><code>def bayesian_linear_regression_survival_analysis(x, y, xerr_low, xerr_high, yerr_low, yerr_high, m_guess, d_guess, nwalkers=8, nsteps=int(0.5e4)):
"""
Perform Bayesian linear regression considering asymmetric uncertainties and censored data in both x and y.
"""
def model(theta, x):
slope, intercept = theta
return slope * x + intercept
def survival_function(observed_value, model_value, sigma):
""" Survival function for censored data. Returns the probability of observing data above (for lower limits) or below (for upper limits) the given value. """
return stats.norm.sf(observed_value, loc=model_value, scale=sigma)
def estimate_sigma(limit_value, model_value, fixed_sigma=1e-6):
# Calculate the sigma as the absolute difference between the limit value and the model value
sigma = np.abs(limit_value - model_value)
# Ensure that the sigma is not an array with ambiguous truth values
sigma = np.where(sigma > 0, sigma, fixed_sigma)
return sigma
def log_likelihood(theta, x, y, xerr_low, xerr_high, yerr_low, yerr_high):
slope, intercept = theta
model_line = model(theta, x)
sigma_x = estimate_sigma(x, model_line)
sigma_y = estimate_sigma(y, model_line)
# Weight sigma_x and sigma_y based on the relative contributions of the lower and upper errors
weight_x = np.where(x > model_line, xerr_high / (xerr_high + xerr_low), xerr_low / (xerr_high + xerr_low))
weighted_sigma_x = weight_x * sigma_x
weight_y = np.where(y > model_line, yerr_high / (yerr_high + yerr_low), yerr_low / (yerr_high + yerr_low))
weighted_sigma_y = weight_y * sigma_y
# Calculate the total variance, including the contribution from sigma_x and sigma_y
point_variance = weighted_sigma_y**2 + (slope * weighted_sigma_x)**2
# Calculate the residuals between observed data and the model prediction
residuals = y - model_line
# Calculate weights based on how much the errors contribute to the point variance
weight = (weighted_sigma_y**2 + (slope * weighted_sigma_x)**2) / point_variance
# Calculate the weighted log-likelihood
log_likelihood = -0.5 * np.sum(weight * ((residuals)**2 / point_variance + np.log(point_variance)))
# Apply survival function for censored data (upper/lower limits)
for i in range(len(x)):
if xerr_low[i] == 0: # Lower limit on x
sigma_x_i = estimate_sigma(x[i], model_line[i])
log_likelihood += np.log(survival_function(x[i], model_line[i], sigma_x_i) + 1e-10)
if xerr_high[i] == 0: # Upper limit on x
sigma_x_i = estimate_sigma(x[i], model_line[i])
log_likelihood += np.log(survival_function(x[i], model_line[i], sigma_x_i) + 1e-10)
if yerr_low[i] == 0: # Lower limit on y
sigma_y_i = estimate_sigma(y[i], model_line[i])
log_likelihood += np.log(survival_function(y[i], model_line[i], sigma_y_i) + 1e-10)
if yerr_high[i] == 0: # Upper limit on y
sigma_y_i = estimate_sigma(y[i], model_line[i])
log_likelihood += np.log(survival_function(y[i], model_line[i], sigma_y_i) + 1e-10)
return log_likelihood
def log_prior(theta):
slope, intercept = theta
if -10.0 < slope < 10.0 and -10.0 < intercept < 10.0:
return 0.0
return -np.inf
def log_probability(theta, x, y, xerr_low, xerr_high, yerr_low, yerr_high):
lp = log_prior(theta)
if not np.isfinite(lp):
return -np.inf
return lp + log_likelihood(theta, x, y, xerr_low, xerr_high, yerr_low, yerr_high)
initial = np.array([m_guess, d_guess])
ndim = 2
sampler = emcee.EnsembleSampler(nwalkers, ndim, log_probability, args=(x, y, xerr_low, xerr_high, yerr_low, yerr_high))
pos = initial + 1e-4 * np.random.randn(nwalkers, ndim)
sampler.run_mcmc(pos, nsteps, progress=True)
samples = sampler.get_chain(discard=100, thin=15, flat=True)
return samples, sampler
</code></pre>
<p>Example Usage:</p>
<p>To keep this post concise, I will add an example later, but the function is tested on simulated data that includes asymmetric errors and randomly assigned upper/lower limits.</p>
<p>Issue:</p>
<p>When I compare the results of this function with a standard linear regression (using scipy.stats.linregress) or a basic Bayesian linear regression using emcee, I find that those simpler methods often outperform my survival analysis approach. This is unexpected, as my function should theoretically handle uncertainties and limits better.</p>
<p>Question:</p>
<p>Could there be an issue with my approach to calculating the log-likelihood or how I handle the uncertainties and limits? Any advice or insights would be greatly appreciated.</p>
<p>Full code:</p>
<pre><code>nwalkers, nsteps = 8, int(1e4)
# Initialize random data
# np.random.seed(42)
N = 20
x = np.random.uniform(0, 10, N)
true_slope = 2
true_intercept = 5
y = true_slope * x + true_intercept + np.random.normal(0, 3, N)
# True values for comparison
x_truth = np.arange(-1, 12, 0.2)
y_truth = x_truth * true_slope + true_intercept
# Initialize errors
yerr_low = np.random.uniform(0.5, 3.0, N)
yerr_upp = np.random.uniform(0.5, 3.0, N)
xerr_low = np.random.uniform(0.1, 3.0, N)
xerr_upp = np.random.uniform(0.1, 3.0, N)
large_error_threshold_x = 2.5
large_error_threshold_y = 4.0
# Identify indices where the errors exceed the threshold
upper_limit_indices_x = np.where(xerr_upp > large_error_threshold_x)[0]
lower_limit_indices_x = np.where(xerr_low > large_error_threshold_x)[0]
upper_limit_indices_y = np.where(yerr_upp > large_error_threshold_y)[0]
lower_limit_indices_y = np.where(yerr_low > large_error_threshold_y)[0]
# Remove indices from lower limits that are already in upper limits
lower_limit_indices_x = np.setdiff1d(lower_limit_indices_x, upper_limit_indices_x)
lower_limit_indices_y = np.setdiff1d(lower_limit_indices_y, upper_limit_indices_y)
# Apply the upper and lower limits
y[upper_limit_indices_y] += yerr_upp[upper_limit_indices_y] # Shifted upward for upper limits
y[lower_limit_indices_y] -= yerr_low[lower_limit_indices_y] # Shifted downward for lower limits
x[upper_limit_indices_x] += xerr_upp[upper_limit_indices_x]
x[lower_limit_indices_x] -= xerr_low[lower_limit_indices_x]
# Set yerr_low to 0 for upper limits and yerr_upp to 0 for lower limits in y, same for x
yerr_low[upper_limit_indices_y] = 0
yerr_upp[lower_limit_indices_y] = 0
xerr_low[upper_limit_indices_x] = 0
xerr_upp[lower_limit_indices_x] = 0
# Perform standard linear regression
standard_slope, standard_intercept, _, _, _ = stats.linregress(x, y)
# Perform standard Bayesian linear regression using emcee
def log_likelihood(theta, x, y):
slope, intercept = theta
model_line = slope * x + intercept
sigma2 = np.var(y)
return -0.5 * np.sum((y - model_line) ** 2 / sigma2 + np.log(sigma2))
def log_prior(theta):
slope, intercept = theta
if -10.0 < slope < 10.0 and -10.0 < intercept < 10.0:
return 0.0
return -np.inf
def log_probability(theta, x, y):
lp = log_prior(theta)
if not np.isfinite(lp):
return -np.inf
return lp + log_likelihood(theta, x, y)
initial = np.array([standard_slope, standard_intercept])
ndim = 2
sampler = emcee.EnsembleSampler(nwalkers, ndim, log_probability, args=(x, y))
pos = initial + 1e-4 * np.random.randn(nwalkers, ndim)
sampler.run_mcmc(pos, nsteps, progress=True)
emcee_samples = sampler.get_chain(discard=100, thin=15, flat=True)
emcee_median_slope = np.median(emcee_samples[:, 0])
emcee_median_intercept = np.median(emcee_samples[:, 1])
emcee_slope_percentiles = np.percentile(emcee_samples[:, 0], [16, 84])
emcee_intercept_percentiles = np.percentile(emcee_samples[:, 1], [16, 84])
# Perform Bayesian linear regression with survival analysis
samples, sampler = bayesian_linear_regression_survival_analysis(
x, y, xerr_low, xerr_upp, yerr_low, yerr_upp, standard_slope, standard_intercept, nwalkers, nsteps)
survival_median_slope = np.median(samples[:, 0])
survival_median_intercept = np.median(samples[:, 1])
survival_slope_percentiles = np.percentile(samples[:, 0], [16, 84])
survival_intercept_percentiles = np.percentile(samples[:, 1], [16, 84])
# Plot the data and the regression results
fig, ax = plt.subplots(figsize=(10, 6))
# Truth
ax.plot(x_truth, y_truth, color='k', label=f"Truth: $y = ({true_slope:.2f})x + ({true_intercept:.2f})$", ls='--')
# Plot all data points
ax.errorbar(x, y, xerr=[xerr_low, xerr_upp], yerr=[yerr_low, yerr_upp], fmt='o', mfc='silver', color='k', ecolor='silver', elinewidth=1)
# Plot the standard linear regression line
y_plot_standard = standard_slope * x_truth + standard_intercept
ax.plot(x_truth, y_plot_standard, label=f"Lin. Regression Fit: $y = ({standard_slope:.2f})x + ({standard_intercept:.2f})$", color='green')
# Plot the emcee fit line
y_plot_emcee = emcee_median_slope * x_truth + emcee_median_intercept
ax.plot(x_truth, y_plot_emcee, label=f"Emcee Fit: $y = ({emcee_median_slope:.2f})x + ({emcee_median_intercept:.2f})$", color='blue')
# Plot the Bayesian linear regression with survival analysis
y_plot_survival = survival_median_slope * x_truth + survival_median_intercept
ax.plot(x_truth, y_plot_survival, color='red', label=f"Survival Analysis Fit: $y = ({survival_median_slope:.2f})x + ({survival_median_intercept:.2f})$")
# Fill between 1-sigma for survival analysis
y_lower = survival_slope_percentiles[0] * x_truth + survival_intercept_percentiles[0]
y_upper = survival_slope_percentiles[1] * x_truth + survival_intercept_percentiles[1]
# ax.fill_between(x_truth, y_lower, y_upper, color='tab:red', alpha=0.3, label='1-sigma region (Survival)')
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.legend()
# Plot the corner plot for the MCMC samples
fig2 = corner.corner(samples, labels=["Slope", "Intercept"], truths=[survival_median_slope, survival_median_intercept],
quantiles=[0.16, 0.5, 0.84], show_titles=True, title_fmt=".2f", title_kwargs={"fontsize": 12})
</code></pre>
<p>Results:
<a href="https://i.sstatic.net/2fS3Lo5M.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/2fS3Lo5M.png" alt="enter image description here" /></a></p>
|
<python><statistics><linear-regression><bayesian><mcmc>
|
2024-08-16 23:59:33
| 0
| 933
|
Alessandro Peca
|
78,881,092
| 3,997,163
|
Unable to connect DB2 Database with Python in Visual Studio
|
<p>I have installed Python 3.12.5 and Visual studio in Windows. I have followed the steps mentioned in the link <a href="https://github.com/ibmdb/python-ibmdb/blob/master/INSTALL.md" rel="nofollow noreferrer">https://github.com/ibmdb/python-ibmdb/blob/master/INSTALL.md</a> (Step 1) . Executed the below command,</p>
<pre><code>pip install ibm_db
import ibm_db >> this resulted in error ImportError: DLL load failed while importing ibm_db: The specified module could not be found
</code></pre>
<p>Executed the below commands to overcome the error in python</p>
<pre><code>import os
os.add_dll_directory('C:\\Python\\Python312\\Lib\\site-packages\\clidriver\\bin')
import ibm_db
</code></pre>
<p>Tried to execute the below code in visual studio and resulted in error <strong>ImportError: DLL load failed while importing ibm_db: The specified module could not be found</strong></p>
<pre><code>import ibm_db
ibm_db.connect("DATABASE=name;HOSTNAME=host;PORT=60000;PROTOCOL=TCPIP;UID=username;
PWD=password;", "", "")
print('connection successful')
</code></pre>
<p>I'm not sure whether I'm missing any step as I tried to execute import ibm_db from python still it results in the same error.</p>
|
<python><visual-studio><db2>
|
2024-08-16 23:27:53
| 1
| 407
|
max092012
|
78,880,980
| 19,672,778
|
Why doesn't Marching Square Visualization In Pygame draws nothing?
|
<p>so i wanted to draw implicit equation of heart in pygame via using the marching squares algorithm in it. i implemented the marching square's algorithm but it doesn't work? can anyone help me out why?</p>
<pre class="lang-py prettyprint-override"><code>import pygame
w = 500
h = 500
grid = []
for i in range(-h//2, h//2):
tempo = []
for j in range(-w//2, w//2):
tempo.append((i**2 + j**2 - 1)**3 - i**2 * j**3)
grid.append(tempo)
print(i)
def Bisection_Method(a, b, t, state, thresh = 0.001):
if state:
a -= w/2
b -= w/2
else:
a -= h/2
b -= h/2
mid = (a + b)/2
while abs(b - a) >= thresh:
a1 = 0
k1 = 0
if state:
i = a
r = mid
j = t
a1 = (i**2 + j**2 - 1)**3 - i**2 * j**3
k1 = (r**2 + j**2 - 1)**3 - r**2 * j**3
else:
i = t
r = mid
j = a
a1 = (i**2 + j**2 - 1)**3 - i**2 * j**3
k1 = (i**2 + r**2 - 1)**3 - i**2 * r**3)
if(k1 == 0):
return mid
mid = (a + b)/2
if(a1 * k1 < 0):
b = mid
else:
a = mid
if state:
mid += w/2
else:
mid += h/2
return mid
def MarchingSquares(i1, j1, i2, j2, i3, j3, i4, j4, plane):
finalP1 = pygame.math.Vector2(float('inf'), float('inf'))
finalP2 = pygame.math.Vector2(float('inf'), float('inf'))
finalP3 = pygame.math.Vector2(float('inf'), float('inf'))
finalP4 = pygame.math.Vector2(float('inf'), float('inf'))
if((plane[i1][j1] < 0 and plane[i2][j2] > 0 and plane[i3][j3] > 0 and plane[i4][j4] > 0) or (plane[i1][j1] > 0 and plane[i2][j2] < 0 and plane[i3][j3] < 0 and plane[i4][j4] < 0)):
finalP1 = pygame.math.Vector2(Bisection_Method(j1, j2, i1, True), i1)
finalP2 = pygame.math.Vector2(j1, Bisection_Method(i1, i3, j1, False))
elif((plane[i1][j1] > 0 and plane[i2][j2] < 0 and plane[i3][j3] > 0 and plane[i4][j4] > 0) or (plane[i1][j1] < 0 and plane[i2][j2] > 0 and plane[i3][j3] < 0 and plane[i4][j4] < 0)):
finalP1 = pygame.math.Vector2(Bisection_Method(j1, j2, i1, True), i1)
finalP2 = pygame.math.Vector2(j2, Bisection_Method(i4, i2, j2, False))
elif((plane[i1][j1] > 0 and plane[i2][j2] > 0 and plane[i3][j3] < 0 and plane[i4][j4] > 0) or (plane[i1][j1] < 0 and plane[i2][j2] < 0 and plane[i3][j3] > 0 and plane[i4][j4] < 0)):
finalP1 = pygame.math.Vector2(Bisection_Method(j3, j4, i3, True), i3)
finalP2 = pygame.math.Vector2(j3, Bisection_Method(i1, i3, j3, False))
elif((plane[i1][j1] > 0 and plane[i2][j2] > 0 and plane[i3][j3] > 0 and plane[i4][j4] < 0) or (plane[i1][j1] < 0 and plane[i2][j2] < 0 and plane[i3][j3] < 0 and plane[i4][j4] > 0)):
finalP1 = pygame.math.Vector2(Bisection_Method(j3, j4, i4, True), i4)
finalP2 = pygame.math.Vector2(j4, Bisection_Method(i4, i2, j4, False))
elif((plane[i1][j1] > 0 and plane[i2][j2] > 0 and plane[i3][j3] < 0 and plane[i4][j4] < 0) or (plane[i1][j1] < 0 and plane[i2][j2] < 0 and plane[i3][j3] > 0 and plane[i4][j4] > 0)):
finalP1 = pygame.math.Vector2(j1, Bisection_Method(i1, i3, j1, False))
finalP2 = pygame.math.Vector2(j2, Bisection_Method(i4, i2, j2, False))
elif((plane[i1][j1] > 0 and plane[i2][j2] > 0 and plane[i3][j3] > 0 and plane[i4][j4] < 0) or (plane[i1][j1] < 0 and plane[i2][j2] > 0 and plane[i3][j3] < 0 and plane[i4][j4] > 0)):
finalP1 = pygame.math.Vector2(Bisection_Method(j1, j2, i1, True), i1)
finalP2 = pygame.math.Vector2(Bisection_Method(j3, j4, i3, True), i3)
elif((plane[i1][j1] < 0 and plane[i2][j2] > 0 and plane[i3][j3] > 0 and plane[i4][j4] < 0) or (plane[i1][j1] > 0 and plane[i2][j2] < 0 and plane[i3][j3] < 0 and plane[i4][j4] > 0)):
i = (i1 + i3 - h)/2
j = (j1 + j3 - w)/2
state = (i**2 + j**2 - 1)**3 - i**2 * j**3
if((state < 0 and plane[i1][j1] < 0) or (state > 0 and plane[i1][j1] > 0)):
finalP1 = pygame.math.Vector2(j1, Bisection_Method(i1, i3, j1, False))
finalP2 = pygame.math.Vector2(Bisection_Method(j3, j4, i3, True), i3)
finalP3 = pygame.math.Vector2(Bisection_Method(j1, j2, i1, True), i1)
finalP4 = pygame.math.Vector2(j4, Bisection_Method(i2, i4, j4, False))
else:
finalP2 = pygame.math.Vector2(j1, Bisection_Method(i1, i3, j1, False))
finalP3 = pygame.math.Vector2(Bisection_Method(j3, j4, i3, True), i3)
finalP1 = pygame.math.Vector2(Bisection_Method(j1, j2, i1, True), i1)
finalP4 = pygame.math.Vector2(j4, Bisection_Method(i2, i4, j4, False))
return finalP1, finalP2, finalP3, finalP4
t = []
for i in range(h - 1):
for j in range(w - 1):
P1, P2, P3, P4 = MarchingSquares(i, j, i, j + 1, i + 1, j, i + 1, j + 1, grid)
t.append([P1, P2, P3, P4])
print("marching {i}")
# pygame setup
pygame.init()
screen = pygame.display.set_mode((w, h))
clock = pygame.time.Clock()
running = True
dt = 0
while running:
# poll for events
# pygame.QUIT event means the user clicked X to close your window
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# fill the screen with a color to wipe away anything from last frame
screen.fill("white")
for x in t:
pygame.draw.line(screen, "purple", x[0], x[1])
if(x[2].x != float('inf')):
pygame.draw.line(screen, "purple", x[2], x[3])
# flip() the display to put your work on screen
pygame.display.flip()
# limits FPS to 60
# dt is delta time in seconds since last frame, used for framerate-
# independent physics.
dt = clock.tick(60) / 1000
pygame.quit()
</code></pre>
<p>Now to explain my code first i generate the grid on whole screen. after that i write marching square algorithm by checking the 16 cases via if else statements, and use bisection method as root finding algorithm. i give it a state parameter which determines what value should i extract from a and b, True => i am doing operations on X axis, False => i am doing operations on Y axis.</p>
<p>Here is result:</p>
<p><a href="https://i.sstatic.net/pznmI31f.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/pznmI31f.png" alt="enter image description here" /></a></p>
|
<python><pygame>
|
2024-08-16 22:17:33
| 1
| 319
|
NikoMolecule
|
78,880,945
| 5,563,584
|
weighted sum on multiple dataframes
|
<p>I have several dataframes with an ID, a time of day, and a number. I would like to weight each dataframe number and then sum them for each id/time of day. As an example:</p>
<pre><code>weighted 0.2
ID TOD M
0 10 morning 1
1 13 afternoon 3
2 32 evening 2
3 10 evening 2
weighted 0.4
ID TOD W
0 10 morning 1
1 13 morning 3
2 32 afternoon 2
3 10 evening 3
weighted sum:
ID TOD weighed_sum_mw
0 10 morning (0.2*1 + 0.4*1)
1 10 evening (0.2*2 + 0.4*3)
2 13 morning (0.4*3)
3 13 afternoon (0.4*2)
3 32 evening (0.2*2)
4 32 afternoon (0.4*2)
</code></pre>
<p>The following strategy works but is very memory consuming and I'm not sure if there's a way to do this without merging them. I also eventually only need the row with the time of day that has the largest sum for each ID so if that simplifies the process that works as well! (Tie breakers for equal max weighted sums will keep Afternoon, then Evening, then Morning first). I currently do this with 4 dataframes but may add more and they are approximately 10M rows each</p>
<pre><code>merged_oc= pd.merge(dfs[0], dfs[3], on=['ID', 'TIME_OF_DAY'], suffixes=('_O', '_C'), how='outer')
merged_s = pd.merge(dfs[1], dfs[2], on=['ID', 'TIME_OF_DAY'], suffixes=('_W', 'M'), how='outer')
# merge and weighted sum of O and C
merged_oc['COUNTS_O_weighted_02']= merged_oc['COUNTS_O'].fillna(0).multiply(0.2)
merged_oc['COUNTS_C_weighted_04'] = merged_oc['COUNTS_C'].fillna(0).multiply(0.4)
merged_oc['COUNTS'] = merged_oc['COUNTS_O_weighted_02'] + merged_oc['COUNTS_C_weighted_04']
result_oc = merged_oc[['ID', 'TIME_OF_DAY', 'COUNTS', 'COUNTS_O_weighted_02', 'COUNTS_C_weighted_04']]
merged_s['COUNTS_W_weighted_04'] = merged_s['COUNTS_W'].fillna(0).multiply(0.4)
merged_s['COUNTS_M_weighted_04'] = merged_s['COUNTS_M'].fillna(0).multiply(0.4)
merged_s['COUNTS'] = merged_s['COUNTS_W_weighted_04'] + merged_s['COUNTS_M_weighted_04']
result_s = merged_s[['ID', 'TIME_OF_DAY', 'COUNTS', 'COUNTS_W_weighted_04', 'COUNTS_M_weighted_04']]
merged_final = pd.merge(result_oc, result_s, on=['ID', 'TIME_OF_DAY'], suffixes=('_OC', '_S'), how='outer')
merged_final['COUNTS_OC']= merged_final['COUNTS_OC'].fillna(0)
merged_final['COUNTS_S'] = merged_final['COUNTS_S'].fillna(0)
merged_final['WEIGHTED_SUM'] = merged_final['COUNTS_OC'] + merged_final['COUNTS_SESSION']
merged_final = merged_final[['ID', 'TIME_OF_DAY', 'WEIGHTED_SUM', 'COUNTS_O_weighted_02', 'COUNTS_C_weighted_04', 'COUNTS_W_weighted_04', 'COUNTS_M_weighted_04']].fillna(0)
</code></pre>
|
<python><pandas><dataframe><weighted>
|
2024-08-16 21:56:08
| 1
| 327
|
greenteam
|
78,880,829
| 1,809,530
|
Selecting interpreter in VS Code does not activate environment
|
<p>I am working with a conda environment that contains multiple packages, and I am trying to debug a Python script that calls those packages via shell commands. While selecting interpreter via VS Code uses that environment's packages, it does not allow me to use the packages installed directly via conda.</p>
<p>Take this code example:</p>
<pre><code> import os
import sys
print(f'python: {sys.executable}')
print(f"env: {os.environ['CONDA_DEFAULT_ENV']}")
print('Trying trimmomatic:')
print(os.system('trimmomatic'))
print('\nTrying trimmomatic ater explicit conda activate:')
print(os.system('source ~/.bashrc; conda activate myenv; trimmomatic'))
</code></pre>
<p>I have an environment <code>myenv</code> that has the tool <code>trimmomatic</code> installed. You can see from the <code>sys.executable</code> (and from the bottom right corner of VS Code) that the interpreter is selected. However, in the second line, you can see that the conda environment is not activated, and instead <code>base</code> is the active environment. As a result, I cannot use the tool unless I activate the environment in conda explicitly. So this is the output I get:</p>
<pre><code>python: /path/to/envs/myenv/bin/python
env: base
Trying trimmomatic:
sh: line 1: trimmomatic: command not found
32512
Trying trimmomatic after explicit conda activate:
Usage:
PE [-version] [-threads <threads>] [-phred33|-phred64] [-trimlog <trimLogFile>] [-summary <statsSummaryFile>] [-quiet] [-validatePairs] [-basein <inputBase> | <inputFile1> <inputFile2>] [-baseout <outputBase> | <outputFile1P> <outputFile1U> <outputFile2P> <outputFile2U>] <trimmer1>...
or:
SE [-version] [-threads <threads>] [-phred33|-phred64] [-trimlog <trimLogFile>] [-summary <statsSummaryFile>] [-quiet] <inputFile> <outputFile> <trimmer1>...
or:
-version
256
</code></pre>
<p>How can I get VS Code to <em>really</em> activate the environment?</p>
|
<python><visual-studio-code><conda>
|
2024-08-16 20:58:28
| 1
| 11,824
|
tktk
|
78,880,721
| 4,177,781
|
Iterate over groups created using group_by on date column
|
<p><strong>Update:</strong> This was fixed by <a href="https://github.com/pola-rs/polars/pull/18251" rel="nofollow noreferrer">pull/18251</a></p>
<hr />
<p>I am new to Polars. I want to iterate over the groups created by grouping over the column where each cell of that column contains a list of two dates. I used the following (sample) piece of code to achieve and it used to work fine with <code>polars==0.20.18</code> version:</p>
<pre class="lang-py prettyprint-override"><code>import polars as pl
import datetime
dt_str = [{'ts': datetime.date(2023, 7, 1), 'files': 'AGG_202307.xlsx',
'period_bins': [datetime.date(2023, 7, 1), datetime.date(2024, 1, 1)]},
{'ts': datetime.date(2023, 8, 1), 'files': 'AGG_202308.xlsx',
'period_bins': [datetime.date(2023, 7, 1), datetime.date(2024, 1, 1)]},
{'ts': datetime.date(2023, 11, 1), 'files': 'KFC_202311.xlsx',
'period_bins': [datetime.date(2023, 7, 1), datetime.date(2024, 1, 1)]},
{'ts': datetime.date(2024, 2, 1), 'files': 'KFC_202402.xlsx',
'period_bins': [datetime.date(2024, 1, 1), datetime.date(2024, 7, 1)]}]
dt = pl.from_dicts(dt_str)
df_groups = dt.group_by("period_bins")
print(df_groups.all().to_dicts())
</code></pre>
<p>The above code does not work with <code>polars==1.x</code> and gives the following error:</p>
<pre class="lang-none prettyprint-override"><code>thread 'polars-0' panicked at crates/polars-row/src/encode.rs:289:15:
not implemented: Date32
thread 'polars-1' panicked at crates/polars-row/src/encode.rs:289:15:
not implemented: Date32
Traceback (most recent call last):
File "testpad.py", line 18, in <module>
print(df_groups.all().to_dicts())
File "python3.10/site-packages/polars/dataframe/group_by.py", line 430, in all
return self.agg(F.all())
File "python3.10/site-packages/polars/dataframe/group_by.py", line 228, in agg
self.df.lazy()
File "python3.10/site-packages/polars/lazyframe/frame.py", line 2027, in collect
return wrap_df(ldf.collect(callback))
pyo3_runtime.PanicException: not implemented: Date32
</code></pre>
<p>How do I fix this error?</p>
|
<python><datetime><python-polars>
|
2024-08-16 20:19:45
| 1
| 352
|
arman
|
78,880,486
| 6,118,556
|
How to change the state of a ttkbootstrap ScrolledText widget after creation?
|
<h3>Problem</h3>
<p>I'm trying to change the state of a <code>ScrolledText</code> <em>ttkboostrap</em> widget after creation. I can set its state as I please when I create it, but trying to change it after creation fails for both examples below with error message: <code>_tkinter.TclError: unknown option "-state"</code>.</p>
<h3>Question</h3>
<p>How can I change the state after creation?</p>
<h3>Minimal RepEx</h3>
<pre><code>import ttkbootstrap as ttk
from ttkbootstrap.scrolled import ScrolledText
app = ttk.Window()
# scrolled text with autohide vertical scrollbar
st = ScrolledText(
app,
padding=5,
height=10,
autohide=True,
# Both of these work
state='normal'
# state='disabled'
)
st.pack(fill='both', expand=True)
# add text
st.insert('end', 'Insert your text here.')
# Neither of these work
st.config(state='disabled')
st.configure(state='disabled')
app.mainloop()
</code></pre>
|
<python><tkinter><state><ttk><ttkbootstrap>
|
2024-08-16 18:55:05
| 1
| 1,136
|
pfabri
|
78,880,464
| 1,993,414
|
Plot sequence of colors in 1-d using associated x-values and labels by x-value and color value (Matplotlib)
|
<h1>Update</h1>
<p><a href="https://stackoverflow.com/questions/78880464/plot-sequence-of-colors-in-1-d-using-associated-x-values-and-labels-by-x-value-a">This question</a> provided a different method which did more accurately display the color values but I still have x-value and label issues.</p>
<pre><code>cmap_ = ListedColormap(rgb_values)
fig = plt.figure(figsize=(10,4))
ax = fig.add_axes([0.05, 0.1, 0.9, 0.85])
mpl.colorbar.ColorbarBase(ax, cmap=cmap_, orientation='horizontal')
plt.show()
</code></pre>
<p><a href="https://i.sstatic.net/7TLODzeK.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/7TLODzeK.png" alt="Updated Figure 1" /></a></p>
<h1>Background</h1>
<p>I am generating custom color sequences (lists of hex values). Each color is associated with a numerical value (held in a separate list). I am attempting to plot a 1-d grid along an x-axis described by the list of numerical values and filling the cells of said grid with the color described in the color sequence. I am struggling to generate a satisfactory plot in matplotlib. Currently, I can plot the sequence of colors but I am struggling with defining the x-axis using my list of numerical values.</p>
<h1>Example</h1>
<p>Here is a simplified version of what I have working.</p>
<pre><code>import matplotlib.pyplot as plt
from matplotlib.colors import hex2color, ListedColormap
num_values = [-10000000, -5000000, -2500000, -1000000, -500000, -250000, -100000, -50000, -10000, 0, 10000, 50000, 100000, 250000, 500000, 1000000, 2500000, 5000000, 10000000]
hex_values = ['#345f79', '#367aa3', '#368cbf', '#3690c0', '#74a9cf', '#a6bddb', '#d0d1e6', '#ece7f2', '#fff7fb', '#f0f0f0', '#ffffcc', '#ffeda0', '#fed976', '#feb24c', '#fda362', '#fc7154', '#d04c67', '#bd0026', '#a64c67']
rgb_values = [hex2color(hex) for hex in hex_values]
plt.imshow((num_values,), cmap=ListedColormap(rgb_values))
plt.show()
</code></pre>
<p>I am able to generate Figure 1 with the above code.</p>
<h1>Figure 1</h1>
<p><a href="https://i.sstatic.net/wia24FCY.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/wia24FCY.png" alt="Figure 1" /></a></p>
<h1>Questions</h1>
<p>This is not bad, but has some issues.</p>
<ol>
<li><p>The first issue is that the colors toward the center (which do trend gray) do not appear to plot the explicit values. Is it possible that values are being interpolated leading to these washing out in saturation?</p>
</li>
<li><p>As soon as I start playing around with xticks or similar, the plot throws an error and I'm stuck. How may I configure the plot to use the num_values list as the x-tick values?</p>
</li>
<li><p>I'd eventually like to add labels showing the hex value for each cell but a functioning plot is the first priority and so I have not done as much research on this question at this point in time. That said, if you have any insights here, I'd appreciate them.</p>
</li>
</ol>
<h1>References</h1>
<p>I've reviewed a number of sources but have been unable to find a good solution.</p>
<p><a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.imshow.html" rel="nofollow noreferrer">imshow</a></p>
<p><a href="https://matplotlib.org/stable/users/explain/colors/colormaps.html" rel="nofollow noreferrer">colormaps (here they plot colormaps with <em>imshow</em> but I don't understand how to modify this use to my case)</a></p>
<p><a href="https://matplotlib.org/stable/gallery/color/colormap_reference.html" rel="nofollow noreferrer">Colormap Reference</a></p>
<p><a href="https://www.pyngl.ucar.edu/Graphics/color_maps.shtml" rel="nofollow noreferrer">Color Maps</a></p>
<p><a href="https://stackoverflow.com/questions/16834861/create-own-colormap-using-matplotlib-and-plot-color-scale">Creating Colormaps using Matplotlib</a></p>
|
<python><matplotlib><colormap>
|
2024-08-16 18:48:38
| 2
| 389
|
XonAether
|
78,880,325
| 11,233,365
|
Perform an SQL 'database.exec()' search in a function not under a FastAPI decorator
|
<p>I am trying to streamline a FastAPI endpoint being developed by my team, in which we are repeatedly registering items to an SQL database if they don't already exist in it.</p>
<p>The session was defined in one file as follows:</p>
<pre class="lang-py prettyprint-override"><code>from functools import partial
from sqlmodel import Session, create_engine
from fastapi import Depends
def get_db_session() -> Session: # type: ignore
_url = "postgresql+psycopg2://some-path:8000"
engine = create_engine(_url)
with Session(engine) as session:
try:
yield session
finally:
session.close()
our_db_session = partial(get_db_session, some_config_file)
our_db: Session = Depends(our_db_session)
</code></pre>
<p>It is then imported for use in the file where the database lookups are happening:</p>
<pre class="lang-py prettyprint-override"><code>from fastapi import APIRouter
from other_file import our_db
router = APIRouter()
@router.post("/register_file/")
def register_file(
file_name: Path,
search_criteria: Union[int, str],
db: Session = our_db,
):
db_entry = db.exec(
select(Table1)
.where(Table1.file_name==file_name)
.where(Table1.some_value==search_criteria)
).one()
</code></pre>
<p>When placed inside the decorated function, the lookup works without issue. However, as there are many such functions registering different things, and the lookup criteria is the same, it got repetitive typing the same thing over and over again within the decorated functions. As such, I tried to move the lookup function into a separate function that gets called within the decorated functions:</p>
<pre class="lang-py prettyprint-override"><code>def get_db_entry(
file_name: Path,
search_criteria: Union[str, int],
db: Session = our_db,
):
db_entry = db.exec(
select(Table1)
.where(Table1.file_name==file_name)
.where(Table1.some_value==search_criteria)
).one()
return db_entry
@router.post("/register_file/")
def register_file(
file_name: Path,
search_criteria: Union[int, str],
db: Session = our_db,
):
db_entry = get_db_entry(file_name=file_name, search_criteria=search_criteria)
</code></pre>
<p>However, when I do it like that, I get an error saying that "Depends" does not have the attribute ".exec()".</p>
<p>I'm very new to FastAPI and SQL, so I would greatly appreciate advice on why this doesn't work, and what I need to change in order to migrate the search function out of the decorated function.</p>
|
<python><fastapi><sqlmodel>
|
2024-08-16 18:01:20
| 1
| 301
|
TheEponymousProgrammer
|
78,880,068
| 6,168,231
|
How to portably write stdout as if piped through `less`?
|
<p>I'm working on a Python project which is supposed to spit out output onto stdout. In some cases, the output can be quite long. In such situations, I'd like it if the output wasn't just dumped onto screen, but would behave as if piped into <code>less</code>, i.e. hold the position at the start of the output and allow me to scroll up and down with the arrow and j/k keys.</p>
<p>Is there a way of doing this without actually piping into <code>less</code> by e.g. calling <code>subprocess</code>? I suspect there might be a package which emulates this behaviour, but I wasn't able to find it. My project also needs to be able to run on Windows, so ideally the package would cover that for me.</p>
|
<python><windows><stdout>
|
2024-08-16 16:35:23
| 0
| 562
|
mivkov
|
78,879,801
| 1,439,122
|
gdown command not working in jupyter notebook in anaconda.cloud
|
<p>I am using Jupyter notebook on anaconda.cloud with kernel
<code>anaconda-2024.02-py310.</code></p>
<p>When I execute the following in a cell:</p>
<pre><code>!pip install gdown
!gdown 1on54WRa6RCAQwrlpE2mABChNs4mNO2fd
</code></pre>
<p>It throws the following error:</p>
<pre><code>Defaulting to user installation because normal site-packages is not writeable
Looking in links: /usr/share/pip-wheels
Requirement already satisfied: gdown in ./.local/lib/python3.10/site-packages (5.2.0)
...
/bin/bash: gdown: command not found
</code></pre>
<p>How come the <code>command not found</code> error is being thrown? Wasn't it just installed and the log also confirms that?</p>
<p>Could someone help me here? I restarted the kernel from the <code>Kernel</code> menu, however it doesn't show any confirmation sort of thing.</p>
<p>I did install <code>gdown</code> on my Mac and this command works on my local host:</p>
<p><code>gdown 1on54WRa6RCAQwrlpE2mABChNs4mNO2fd</code></p>
<p>(Of course, I have modified the id a bit here on SO).</p>
|
<python><jupyter-notebook><anaconda><gdown>
|
2024-08-16 15:18:11
| 2
| 2,721
|
RRM
|
78,879,781
| 9,571,463
|
How to get same results from base64 atob in Javascript vs Python
|
<p>I found some code online that I am trying to work through which encodes to base64. I know Python has <code>base64.urlsafe_b64decode()</code> but I would like to learn a bit more about what is going on.</p>
<p>The JS <code>atob</code> looks like:</p>
<pre><code>function atob (input) {
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var str = String(input).replace(/=+$/, '');
if (str.length % 4 == 1) {
throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded.");
}
for (
// initialize result and counters
var bc = 0, bs, buffer, idx = 0, output = '';
// get next character
buffer = str.charAt(idx++);
// character found in table? initialize bit storage and add its ascii value;
~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
// and if not first of each 4 characters,
// convert the first 8 bits to one ascii character
bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
) {
// try to find character in table (0-63, not found => -1)
buffer = chars.indexOf(buffer);
}
return output;
}
</code></pre>
<p>My goal is to port this Python, but I am trying to understand what the for loop is doing in Javascript.</p>
<p>It checks if the value is located in the <code>chars</code> table and then initializes some variables using a ternary like: <code>bs = bc % 4 ? bs*64+buffer: buffer, bc++ %4</code></p>
<p>I am not quite sure I understand what the <code>buffer, bc++ % 4</code> part of the ternary is doing. The comma confuses me a bit. Plus the <code>String.fromCharCode(255 & (bs >> (-2 * bc & 6)))</code> is a bit esoteric to me.</p>
<p>I've been trying something like this in Python, which produces some results, albeit different than what the javascript implementation is doing</p>
<pre><code># Test subject
b64_str: str = "fwHzODWqgMH+NjBq02yeyQ=="
# Lookup table for characters
chars: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
# Replace right padding with empty string
replaced = re.sub("=+$", '', b64_str)
if len(replaced) % 4 == 1:
raise ValueError("atob failed. The string to be decoded is not valid base64")
# Bit storage and counters
bc = 0
out: str = ''
for i in replaced:
# Get ascii value of character
buffer = ord(i)
# If counter is evenly divisible by 4, return buffer as is, else add the ascii value
bs = bc * 64 + buffer if bc % 4 else buffer
bc += 1 % 4 # Not sure I understand this part
# Check if character is in the chars table
if i in chars:
# Check if the bit storage and bit counter are non-zero
if bs and bc:
# If so, convert the first 8 bits to an ascii character
out += chr(255 & bs >> (-2 * bc & 6))
else:
out = 0
# Set buffer to the index of where the first instance of the character is in the b64 string
print(f"before: {chr(buffer)}")
buffer = chars.index(chr(buffer))
print(f"after: {buffer}")
print(out)
</code></pre>
<p>JS gives <code>ó85ªÁþ60jÓlÉ</code></p>
<p>Python gives <code>2:u1(²ë:ð1G>%Y</code></p>
|
<javascript><python><base64><base64url>
|
2024-08-16 15:12:50
| 2
| 1,767
|
Coldchain9
|
78,879,657
| 8,667,016
|
Selecting rows that compose largest group (within another group) in a pandas DataFrame
|
<h2>Main problem</h2>
<p>I'm trying to find a way to select the rows that make up the largest sub-group inside another group in a Pandas DataFrame and I'm having a bit of a hard time.</p>
<h3>Visual example (code below)</h3>
<p>Here is a sample dataset to help explain exactly what it is I'm trying to do. There is code below to recreate this dataset yourself, if you'd like.</p>
<p><a href="https://i.sstatic.net/V7TBihth.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/V7TBihth.png" alt="Original table" /></a></p>
<p>Suppose I want to group this table by <code>Col1</code> and figure out which unique value of <code>Col2</code> has the most rows (within each group of <code>Col1</code>). Further, I don't want to just know which group is the largest - I want to find a way to select the rows from the original DataFrame that match that description.</p>
<p>So, in this case, we can easily see that, for <code>Col1=="Group A"</code>, the value of <code>Col2</code> with most rows is <code>"Type 3"</code>, and for <code>Col1=="Group B"</code>, the value of <code>Col2</code> with most rows is <code>"Type 6"</code>.</p>
<p>That means that I want to select the rows with <code>RowID in [10005, 10006, 10007, 10008, 10009, 10010, 10011, 10012, 10013, 10014, 10015]</code>.</p>
<p>Therefore, the output I'm looking for would be the following:</p>
<p><a href="https://i.sstatic.net/6qewvCBM.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/6qewvCBM.png" alt="expected result" /></a></p>
<h2>My clumsy attempt</h2>
<p>I found a solution, but it is tremendously convoluted. Here is a step-by-step explanation of what I did:</p>
<p><strong>Step 1</strong>: First, for each group of <code>Col1</code>, I want to tally up the number of rows that exist for each unique value of <code>Col2</code>. That's quite easy, I can just do a simple <code>groupby(['Col1','Col2'])</code> and see the size of each grouping.</p>
<p>Here is how that looks:</p>
<p><a href="https://i.sstatic.net/LRuIh2pd.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/LRuIh2pd.png" alt="result of step 1" /></a></p>
<p>Notice that for <code>Col1=="Group A"</code>, <code>Col2=="Type 1"</code> has 2 observations, <code>Col2=="Type 2"</code> has 2 observations, and <code>Col2=="Type 3"</code> has 6 observations - as expected from our original data.</p>
<p><strong>Step 2</strong>: This is trickier: for each group of <code>Col1</code>, I want to find the value of <code>Col2</code> that has the biggest number of rows from Step 1.</p>
<p>Here is how that looks:</p>
<p><a href="https://i.sstatic.net/A2YKPxR8.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/A2YKPxR8.png" alt="result of step 2" /></a></p>
<p>Notice that we only see the cases with "max rows".</p>
<p><strong>Step 3</strong>: Lastly, I want to filter the original data to show ONLY the rows that fit that specific grouping: the ones found in Step 2.</p>
<p><a href="https://i.sstatic.net/6qewvCBM.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/6qewvCBM.png" alt="final result" /></a></p>
<h3>Reproducible example and code</h3>
<p>Here's some code to illustrate my example:</p>
<pre class="lang-py prettyprint-override"><code># Importing the relevant library
import pandas as pd
# Creating my small reproducible example
my_df = pd.DataFrame({'RowID':[10001,10002,10003,10004,10005,10006,10007,10008,10009,10010,10011,10012,10013,10014,10015,10016,10017,10018,10019,10020],
'Col1':['Group A','Group A','Group A','Group A','Group A','Group A','Group A','Group A','Group A','Group A','Group B','Group B','Group B','Group B','Group B','Group B','Group B','Group B','Group B','Group B'],
'Col2':['Type 1','Type 1','Type 2','Type 2','Type 3','Type 3','Type 3','Type 3','Type 3','Type 3','Type 6','Type 6','Type 6','Type 6','Type 6','Type 3','Type 3','Type 2','Type 2','Type 2'],
'Col3':[100,200,300,400,500,600,700,800,900,1000,2000,1900,1800,1700,1600,1500,1400,1300,1200,1100],
'Col4':['Alice','Bob','Carl','Dave','Earl','Fred','Greg','Henry','Iris','Jasmine','Kris','Lonnie','Manny','Norbert','Otis','Pearl','Quaid','Randy','Steve','Tana']})
# Solving Step 1: finding the unique groupings and their relative sizes
temp1 = my_df.groupby(['Col1','Col2']).agg({'RowID':'count'}).reset_index()
# Solving Step 2: finding which grouping is the largest
temp2 = temp1.groupby(['Col1']).agg({'RowID':'max'}).reset_index()
# Solving Step 3: finding which rows of the original DataFrame match what was
# found in Step 2
# Step 3 Part 1: Finding the actual combination of `Col1` & `Col2` that let to
# the largest number of rows
temp3 = (temp1
.rename(columns={'RowID':'RowID_count'})
.merge(temp2
.rename(columns={'RowID':'RowID_max'}),
how='left',
on='Col1')
.assign(RowID_ismax = lambda _df: _df['RowID_count']== _df['RowID_max'])
.query('RowID_ismax')
.drop(columns=['RowID_count','RowID_max']))
# Step 3 Part 2: Finding the matching rows in the original dataset and
# filtering it down
result = (my_df
.merge(temp3,
how='left',
on=['Col1','Col2'])
.assign(RowID_ismax = lambda _df: _df['RowID_ismax'].fillna(False))
.query('RowID_ismax')
.reset_index(drop=True)
.drop(columns=['RowID_ismax']))
</code></pre>
<p>The solution above is EXTREMELY convoluted, full of <code>assign</code> and <code>lambda</code> statements alongside several sequential <code>groupby</code>s and <code>reset_index</code>s, which suggest to me I'm approaching this the wrong way.</p>
<p>Any help on this would be greatly appreciated.</p>
|
<python><pandas><dataframe>
|
2024-08-16 14:42:08
| 1
| 1,291
|
Felipe D.
|
78,879,558
| 200,663
|
Update airflow config without restarting scheduler with LocalExecutor
|
<p>I have a bunch of tasks running and want to update airflow.cfg to enable more tasks to run simultaneously. My understanding is that I need to restart the scheduler for these updates to take place. However, when I try to restart the scheduler, I get this warning:</p>
<blockquote>
<p>INFO - Shutting down LocalExecutor; waiting for running tasks to finish. Signal again if you don't want to wait.</p>
</blockquote>
<p>Is there any way for me to update the config without killing ongoing jobs or having to wait (potentially days) for the currently running jobs to finish?</p>
|
<python><airflow><config>
|
2024-08-16 14:18:00
| 1
| 1,450
|
Tim
|
78,879,249
| 7,941,309
|
sympy matrix scientific notation
|
<p>I'm trying to display a sympy matrix in scientific notation, and it is only working for values less than 1. I can't understand why <a href="https://github.com/sympy/sympy/blob/2197797741156d9cb73a8d1462f7985598e9b1a9/sympy/matrices/matrixbase.py#L2089-L2110" rel="nofollow noreferrer"><code>applyfunc</code></a> is behaving differently. Is there a better way to do this?</p>
<pre><code>import numpy as np
from sympy import Matrix
from sympy.printing import latex
from IPython.display import display
C = np.array([
[390, 145, ],
[145, 0, ],
])*1e9
S_ij = np.linalg.inv(C)
S_scientific = Matrix(S_ij).applyfunc(lambda x: '{:.2e}'.format(float(x)))
print('this prints as desired:')
display(S_scientific) #m^2 / N
def g(x):
#shouldn't be necessary since 0 handles fine above
if abs(float(x.evalf())) < 1e-10:
return '0'
else:
return f'{float(x.evalf(8)):.2e}'
C_scientific = Matrix(C).applyfunc(g)
print()
print('this is not print in scientific notation:')
display(C_scientific)
print(C_scientific)
</code></pre>
<p>And the output is, with a check on the function <code>g</code>:
<a href="https://i.sstatic.net/fzKQ7AH6.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/fzKQ7AH6.png" alt="console output" /></a></p>
|
<python><sympy>
|
2024-08-16 12:58:46
| 2
| 353
|
Erik Iverson
|
78,879,247
| 445,810
|
Ignoring "undefined symbol" errors in ctypes library load
|
<p>I'm loading a not-owned-by-me library with Python's <code>ctypes</code> module as <code>ctypes.CDLL("libthirdparty.so")</code> which produces an error <code>undefined symbol: g_main_context_push_thread_default</code> because <code>libthirdparty.so</code> was overlinking a lot of unneeded / unused stuff like <code>glib</code>.</p>
<p>In this particular case, I can work around this problem successfully by <code>LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libglib-2.0.so.0 python ...</code>-ing <code>glib</code>, but I'm curious in two generic related questions touching on how <code>ctypes</code> works:</p>
<ol>
<li><p>Is it possible to ask <code>ctypes</code> / <code>dlopen</code> to ignore undefined symbols, given that I know that these undefined symbols are not used on the code path I'm interested in (or otherwise I would be okay if it crashed in a hard way)?</p>
</li>
<li><p>Is it possible to ask <code>ctypes</code> to load several libraries at once or emulate <code>LD_PRELOAD</code>-ing? I tried to do <code>ctypes.CDLL("/usr/lib/x86_64-linux-gnu/libglib-2.0.so.0")</code> in attempt to force-load <code>glib</code> in the Python's process before loading <code>ctypes.CDLL("libthirdparty.so")</code>, but it did not help.</p>
</li>
</ol>
<p>Thanks!</p>
|
<python><ctypes><ld-preload>
|
2024-08-16 12:57:56
| 1
| 1,164
|
Vadim Kantorov
|
78,879,232
| 16,725,431
|
tkinter auto joining thread
|
<p>I am writing a tkinter app and is using threads for performance (computing-intensive tasks)</p>
<p>Threads need to be joined, but I am lazy.</p>
<p>I don't really like the idea of constantly checking if a thread is alive.</p>
<p>I created a class to handle join automatically when the job is done. However, it still has the risk of having race conditions (that's what GPT said)</p>
<pre class="lang-py prettyprint-override"><code>class RunInThreadHandler(ctk.CTkFrame):
def __init__(self, master: ctk.CTkBaseClass,
target: Callable,
args: tuple = (),
func_end_callback: Optional[Callable] = None,
kwargs: Optional[dict[str, Any]] = None):
super().__init__(master)
self._func: Callable = target
self._args: tuple = args
self._kwargs: dict[str, Any] = kwargs if kwargs is not None else {}
self._func_end_callback: Optional[Callable] = func_end_callback
self._thread: Optional[Thread] = Thread(target=self._thread_func)
self._thread.start()
def _thread_func(self):
try:
self._func(*self._args, **self._kwargs)
except BaseException as exc:
print(exc)
self.after(1000, self._thread.join)
if self._func_end_callback is not None:
self.after(1000, self._func_end_callback)
</code></pre>
<p>Usage:</p>
<pre class="lang-py prettyprint-override"><code>RunInThreadHandler(self, target=foo) # runs foo in thread on the spot
</code></pre>
<p>Q: Any better ways?</p>
|
<python><multithreading><tkinter>
|
2024-08-16 12:53:05
| 1
| 444
|
Electron X
|
78,879,448
| 11,233,365
|
Validating file paths to satisfy GitHub CodeQL's "Uncontrolled data used in path expression" alert
|
<p>I'm writing functions for a Python package to register files from a file system to an SQL database, and GitHub's CodeQL has flagged that the file paths are a potential security risk.</p>
<p>I have constructed a basic validator to make sure that only file paths that exist and start with a given base path when resolved are accepted for subsequent processing. However, CodeQL still views this as being insufficient.</p>
<p>Is this a false positive, or can my validation check be further enhanced? Note that I use <code>resolve</code> so that I can get and compare the start of the file paths.</p>
<p><strong>Example Code</strong></p>
<pre><code># Python version: 3.9.19
# OS: GNU/Linux RHEL8 4.18.0-553.5.1.el8_10.x86_64
from pathlib import Path
# The storage path is defined internally by an environment variable; here is a placeholder
storage_path = Path("/path/to/where/files/are/stored")
# Define a function to validate the file path provided
def validate_file(file: Path) -> bool:
file = Path(file) if isinstance(file, str) else file # Pre-empt accidental string inputs
file = file.resolve() # Get full path for validation
# Fail if file doesn't exist
if not file.exists():
return False
# Use path to storage location as reference
basepath = list(storage_path.parents)[-2] # This can be made stricter eventually
if str(file).startswith(str(basepath)):
return True
else:
return False
# How it's used in the script
incoming_file = Path("some_file.txt") # Can be partial path, or full path on system
if validate_file(incoming_file) is True:
"""
Run code here to store the file in the database
"""
return True
else:
raise Exception("This file failed the validation check")
</code></pre>
|
<python><codeql><file-inclusion>
|
2024-08-16 12:49:08
| 1
| 301
|
TheEponymousProgrammer
|
78,878,639
| 1,489,009
|
Pymongo: create_collection error after updating python to 3.12.5
|
<p>I'm using Mongo db from Python.</p>
<p>Creating collections using this code:</p>
<pre><code>self.client = MongoClient(MONGODB_CONNECT)
self.db = self.client[MONGODB_NAME]
self.db.create_collection(collection_name, options)
</code></pre>
<p>Where option is a dictionary like:</p>
<pre><code>option = {
"timeseries": {
"timeField": "event_time",
"metaField": "metadata",
"granularity": "minutes"
},
"validator": event_validator, // another dictionary
}
</code></pre>
<p>This was fine yesterday.</p>
<p>For a deployment evolution reason I've updated Python from version 3.12.4 to 3.12.5.</p>
<p>I now have the following error on the 'create_collection' line:</p>
<blockquote>
<p>codec_options must be an instance of bson.codec_options.CodecOptions</p>
</blockquote>
<p>Indeed <a href="https://pymongo.readthedocs.io/en/stable/api/pymongo/database.html#pymongo.database.Database.create_collection" rel="nofollow noreferrer">the documentation</a> shows an optional <strong>codec_options</strong> parameter that I've never used.</p>
<p>I'm using PyMongo 4.8.0 and don't think I've ever change this version.</p>
<p>I'm quite new to python so maybe I'm missing something obvious here...</p>
<p>I'm wondering why a Python update can cause such an error and how we should create a collection with an option dictionary on python 3.12.5.</p>
<p><strong>EDIT (new try) :</strong>
I've seen example where validators are given with named parameter like so</p>
<pre><code>self.db.create_collection(collection_name, validators=validators)
</code></pre>
<p>No success:</p>
<blockquote>
<p>parameter validators is disallowed in create command, full error: {'ok': 0, 'errmsg': 'parameter validators is disallowed in create command', 'code': 8000, 'codeName': 'AtlasError'}</p>
</blockquote>
|
<python><pymongo><python-3.12>
|
2024-08-16 10:09:37
| 1
| 4,836
|
Guian
|
78,878,468
| 3,767,239
|
What is the rationale behind `TransformedTargetRegressor` always cloning the given `regressor` and how to prevent this behavior?
|
<p>The docs of <a href="https://scikit-learn.org/stable/modules/generated/sklearn.compose.TransformedTargetRegressor.html" rel="nofollow noreferrer"><code>sklearn.compose.TransformedTargetRegressor</code></a> state that:</p>
<blockquote>
<p><strong>regressor object, default=None</strong></p>
<p>Regressor object such as derived from <code>RegressorMixin</code>. This regressor will automatically be cloned each time prior to fitting. If <code>regressor is None</code>, <code>LinearRegression</code> is created and used.</p>
</blockquote>
<p>What is the rationale behind cloning the given <code>regressor</code> each time prior to fitting? Why would this be useful?</p>
<p>This behavior prevents, for example, the following code from working:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestRegressor
from sklearn.pipeline import Pipeline
from sklearn.compose import TransformedTargetRegressor
X = np.random.default_rng(seed=1).normal(size=(100,3))
y = np.random.default_rng(seed=1).normal(size=100)
model = RandomForestRegressor()
pipeline = Pipeline(
steps=[
('normalize', StandardScaler()),
('model', model),
],
)
tt = TransformedTargetRegressor(regressor=pipeline, transformer=StandardScaler())
tt.fit(X, y)
print(model.feature_importances_)
</code></pre>
<p>It results in:</p>
<pre><code>Traceback (most recent call last):
File "/tmp/test.py", line 21, in <module>
print(model.feature_importances_)
[...]
sklearn.exceptions.NotFittedError: This RandomForestRegressor instance is not fitted yet. Call 'fit' with appropriate arguments before using this estimator.
</code></pre>
<p>which is not surprising given that the <code>model</code> object is cloned by the <code>TransformedTargetRegressor</code>.</p>
<p>So, is there a way to prevent this cloning behavior and make the above code work?</p>
|
<python><scikit-learn>
|
2024-08-16 09:28:48
| 2
| 36,629
|
a_guest
|
78,878,466
| 3,732,793
|
relative import for class fails
|
<p>not sure why I always struggle with relative imports...</p>
<p>usually I have this structure</p>
<pre><code>- project
- package1
some.py
- package2
- tests
tests_package1.py
</code></pre>
<p>where tests_package1.py starts with</p>
<pre><code>from ..packe1.some import some
</code></pre>
<p>however I get "attempted relative import with no known parent package" and depening on where I have which <strong>init</strong>.py other errors.</p>
<p>here I found many suggestions but all fail in one or the other way</p>
<p>how to correctly import a class some in some.py from the tets_package1.py ?</p>
<p>Changed the question to make clear I want to run a test of some class in some.py called from tests in test_package1.py.</p>
|
<python>
|
2024-08-16 09:28:17
| 2
| 1,990
|
user3732793
|
78,878,331
| 15,358,800
|
Numpy: UFuncBinaryResolutionError: ufunc 'add' cannot use operands with types dtype('<M8[D]') and dtype('<M8[D]')
|
<p>One of my function generates list of dates in <code>numpy</code> array like so and iam just trying to apply median function on results...Finding median in such arrays is invalid or Iam missing something??</p>
<p><strong>Reproducable</strong></p>
<pre><code>import numpy as np
dt_array = np.array([np.datetime64('2024-08-16'), np.datetime64('2024-08-15')]) #dt_array = ['2024-08-16' '2024-08-15']
np.median(dt_array)
</code></pre>
<p>Error</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\ACENTAURI-1009\Desktop\pdf.py", line 5, in <module>
np.median(dt_array)
File "C:\Users\ACENTAURI-1009\AppData\Local\Programs\Python\Python312\Lib\site-packages\numpy\lib\function_base.py", line 3927, in median
return _ureduce(dt_array, func=_median, keepdims=keepdims, axis=axis, out=out,
File "C:\Users\ACENTAURI-1009\AppData\Local\Programs\Python\Python312\Lib\site-packages\numpy\lib\function_base.py", line 3823, in _ureduce
r = func(dt_array , **kwargs)
File "C:\Users\ACENTAURI-1009\AppData\Local\Programs\Python\Python312\Lib\site-packages\numpy\lib\function_base.py", line 3979, in _median
rout = mean(part[indexer], axis=axis, out=out)
File "C:\Users\ACENTAURI-1009\AppData\Local\Programs\Python\Python312\Lib\site-packages\numpy\core\fromnumeric.py", line 3504, in mean
return _methods._mean(dt_array, axis=axis, dtype=dtype,
File "C:\Users\ACENTAURI-1009\AppData\Local\Programs\Python\Python312\Lib\site-packages\numpy\core\_methods.py", line 118, in _mean
ret = umr_sum(arr, axis, dtype, out, keepdims, where=where)
numpy.core._exceptions._UFuncBinaryResolutionError: ufunc 'add' cannot use operands with types dtype('<M8[D]') and dtype('<M8[D]')
</code></pre>
|
<python><numpy>
|
2024-08-16 08:51:01
| 2
| 4,891
|
Bhargav
|
78,878,107
| 4,508,605
|
How to add file name pattern in AWS Glue ETL job python script
|
<p>I wanted to add file name pattern in <code>AWS Glue ETL</code> job python script where it should generate the files in s3 bucket with pattern <code>dostrp*.csv.gz</code> but could not find way how to provide this file pattern in python script :</p>
<pre><code>import sys
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.job import Job
args = getResolvedOptions(sys.argv, ['target_BucketName', 'JOB_NAME'])
sc = SparkContext()
glueContext = GlueContext(sc)
spark = glueContext.spark_session
job = Job(glueContext)
job.init(args['JOB_NAME'], args)
outputbucketname = args['target_BucketName']
# Script generated for node AWS Glue Data Catalog
AWSGlueDataCatalog_node188777777 = glueContext.create_dynamic_frame.from_catalog(database="xxxx", table_name="xxxx", transformation_ctx="AWSGlueDataCatalog_node887777777")
# Script generated for node Amazon S3
AmazonS3_node55566666 = glueContext.write_dynamic_frame.from_options(frame=AWSGlueDataCatalog_node8877777777, connection_type="s3", format="csv", format_options={"separator": "|"}, connection_options={"path": outputbucketname, "compression": "gzip", "partitionKeys": []}, transformation_ctx="AmazonS3_node5566677777")
job.commit()
</code></pre>
|
<python><amazon-s3><aws-glue><filepattern>
|
2024-08-16 07:44:27
| 1
| 4,021
|
Marcus
|
78,878,048
| 26,843,912
|
Shaky zoom with opencv python
|
<p>I want to apply zoom in and out effect on a video using opencv, but as opencv doesn't come with built in zoom, I try cropping the frame to the interpolated value's width, height, x and y and than resize back the frame to the original video size, i.e. 1920 x 1080.</p>
<p>But when I rendered the final video, there is shakiness in the final video. I am not sure why its happening, I want a perfect smooth zoom in and out from the specific time</p>
<p>I built a easing function that would give interpolated value for each frame for zoom in and out :-</p>
<pre class="lang-py prettyprint-override"><code>import cv2
video_path = 'inputTest.mp4'
cap = cv2.VideoCapture(video_path)
fps = int(cap.get(cv2.CAP_PROP_FPS))
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter('output_video.mp4', fourcc, fps, (1920, 1080))
initialZoomValue={
'initialZoomWidth': 1920,
'initialZoomHeight': 1080,
'initialZoomX': 0,
'initialZoomY': 0
}
desiredValues = {
'zoomWidth': 1672,
'zoomHeight': 941,
'zoomX': 200,
'zoomY': 0
}
def ease_out_quart(t):
return 1 - (1 - t) ** 4
async def zoomInInterpolation(initialZoomValue, desiredZoom, start, end, index):
t = (index - start) / (end - start)
eased_t = ease_out_quart(t)
interpolatedWidth = round(initialZoomValue['initialZoomWidth'] + eased_t * (desiredZoom['zoomWidth']['width'] - initialZoomValue['initialZoomWidth']), 2)
interpolatedHeight = round(initialZoomValue['initialZoomHeight'] + eased_t * (desiredZoom['zoomHeight'] - initialZoomValue['initialZoomHeight']), 2)
interpolatedX = round(initialZoomValue['initialZoomX'] + eased_t * (desiredZoom['zoomX'] - initialZoomValue['initialZoomX']), 2)
interpolatedY = round(initialZoomValue['initialZoomY'] + eased_t * (desiredZoom['zoomY'] - initialZoomValue['initialZoomY']), 2)
return {'interpolatedWidth': int(interpolatedWidth), 'interpolatedHeight': int(interpolatedHeight), 'interpolatedX': int(interpolatedX), 'interpolatedY': int(interpolatedY)}
def generate_frame():
while cap.isOpened():
code, frame = cap.read()
if code:
yield frame
else:
print("bailsdfing")
break
for i, frame in enumerate(generate_frame()):
if i >= 1 and i <= 60:
interpolatedValues = zoomInInterpolation(initialZoomValue, desiredValues, 1, 60, i)
crop = frame[interpolatedValues['interpolatedY']:(interpolatedValues['interpolatedHeight'] + interpolatedValues['interpolatedY']), interpolatedValues['interpolatedX']:(interpolatedValues['interpolatedWidth'] + interpolatedValues['interpolatedX'])]
zoomedFrame = cv2.resize(crop,(1920, 1080), interpolation = cv2.INTER_CUBIC)
out.write(zoomedFrame)
# Release the video capture and close windows
cap.release()
cv2.destroyAllWindows()
</code></pre>
<p>But the final video I get is shaking :-</p>
<p><a href="https://i.imgur.com/wODwDON.mp4" rel="nofollow noreferrer">Final Video</a></p>
<p>I want the video to be perfectly zoom in and out, don't want to any shakiness</p>
<hr />
<p>Here is graph of the interpolated values :-
<a href="https://i.sstatic.net/v8naH9Ao.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/v8naH9Ao.png" alt="GRAPH" /></a></p>
<p>This is a graph if I don't round the number too early and return the integer value only :- <a href="https://i.sstatic.net/iVMkcPzj.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/iVMkcPzj.png" alt="GRAPH for Integer return" /></a></p>
<p>As OpenCV would only accept whole numbers for cropping, its not possible to return the values from the interpolation function in decimals</p>
|
<python><opencv><image-processing><video-processing>
|
2024-08-16 07:33:21
| 1
| 323
|
Zaid
|
78,877,805
| 219,153
|
Calculating an average of multiple polygons
|
<p>I would like to "average" several polygons having a substantial intersection, e.g. these three:</p>
<p><a href="https://i.sstatic.net/vT84Twro.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/vT84Twro.png" alt="enter image description here" /></a></p>
<p>Preferably using a Python library, e.g. Shapely. I don't see a suitable function there, which can be used directly. I'm not set on any formal definition of polygon averaging, just anything which looks intuitively acceptable. Any suggestions?</p>
|
<python><computational-geometry><shapely>
|
2024-08-16 06:11:32
| 4
| 8,585
|
Paul Jurczak
|
78,877,560
| 5,565,100
|
liboqs-python throws AttributeError: module 'oqs' has no attribute 'get_enabled_kem_mechanisms'
|
<p>I'm trying to get this Open Quantum Safe example working:
<a href="https://github.com/open-quantum-safe/liboqs-python/blob/main/examples/kem.py" rel="nofollow noreferrer">https://github.com/open-quantum-safe/liboqs-python/blob/main/examples/kem.py</a></p>
<p>I'm getting this error:</p>
<pre class="lang-none prettyprint-override"><code>(myenv) user@mx:~
$ python3 '/home/user/Documents/Dev/quantum_algo_tests/# Key encapsulation Python example.py'
Enabled KEM mechanisms:
Traceback (most recent call last):
File "/home/user/Documents/Dev/quantum_algo_tests/# Key encapsulation Python example.py", line 9, in <module>
kems = oqs.get_enabled_kem_mechanisms()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: module 'oqs' has no attribute 'get_enabled_kem_mechanisms'
(myenv) user@mx:~
$
</code></pre>
<p>Running inspect to list functions I get:</p>
<pre><code>ExpressionInput
FunctionNode
OQSInterpreter
oqs_engine
</code></pre>
<p>I tried a basic example from following the documentation:</p>
<pre class="lang-py prettyprint-override"><code>import oqs
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
import os
import base64
# Message to be encrypted
message = "Hello world!"
# Step 1: Key Encapsulation using Kyber
kemalg = "Kyber512"
with oqs.KeyEncapsulation(kemalg) as client:
# Client generates keypair
public_key = client.generate_keypair()
# Server (could be another party) encapsulates secret with client's public key
with oqs.KeyEncapsulation(kemalg) as server:
ciphertext, shared_secret_server = server.encap_secret(public_key)
# Client decapsulates to get the same shared secret
shared_secret_client = client.decap_secret(ciphertext)
# The shared secret is now the same for both client and server and will be used as the encryption key
assert shared_secret_client == shared_secret_server, "Shared secrets do not match!"
# Step 2: Encrypt the message using AES-GCM with the shared secret
iv = os.urandom(12)
cipher = Cipher(algorithms.AES(shared_secret_client), modes.GCM(iv), backend=None)
encryptor = cipher.encryptor()
ciphertext = encryptor.update(message.encode()) + encryptor.finalize()
# The tag ensures the integrity of the message
tag = encryptor.tag
# Combine the IV, ciphertext, and tag into a single encrypted package
encrypted_message = base64.b64encode(iv + ciphertext + tag)
print(f"Encrypted message: {encrypted_message.decode()}")
# Step 3: Decryption process (using the shared secret derived from Kyber)
# Decrypt the message
decryptor = Cipher(algorithms.AES(shared_secret_server), modes.GCM(iv, tag), backend=None).decryptor()
decrypted_message = decryptor.update(ciphertext) + decryptor.finalize()
print(f"Decrypted message: {decrypted_message.decode()}")
</code></pre>
<p>I get the same error:</p>
<pre class="lang-none prettyprint-override"><code>$ python3 /home/user/Documents/Dev/quantum_algo_tests/hello_world_example.py
Traceback (most recent call last):
File "/home/user/Documents/Dev/quantum_algo_tests/hello_world_example.py", line 11, in <module>
with oqs.KeyEncapsulation(kemalg) as client:
^^^^^^^^^^^^^^^^^^^^
AttributeError: module 'oqs' has no attribute 'KeyEncapsulation'
</code></pre>
<p>Why is such a simple program throwing this error?</p>
|
<python><post-quantum-cryptography>
|
2024-08-16 03:53:06
| 1
| 2,371
|
Emily
|
78,877,520
| 11,627,201
|
gspread exceeded api call quota even though I only run it once per minute?
|
<p>I am using google drive with google colab. Here is the code (basically, login to google drive, read a spreadsheet with some data, process that data, and write it to another spread sheet)</p>
<pre><code>from google.colab import drive
drive.mount('/content/drive')
import gspread
from google.colab import auth
auth.authenticate_user()
from google.auth import default
creds, _ = default()
gc = gspread.authorize(creds)
worksheet = gc.open_by_key('some_key').sheet1
import pandas as pd
dataframe = pd.DataFrame(worksheet.get_all_records())
aslist = dataframe.values.tolist()
# do some stuff with the data
from pprint import pprint
pprint(gc.list_spreadsheet_files())
sheet = gc.open_by_key('some_other_key')
sheet.values_update(
'Sheet1!A1',
params={'valueInputOption': 'RAW'},
body={'values': newlist}
)
</code></pre>
<p>Here is the error:</p>
<pre><code>APIError: {
'code': 429,
'message': "Quota exceeded for quota metric 'Read requests' and limit 'Read requests per minute' of service 'sheets.googleapis.com' for consumer 'project_number:some_id'.",
'status': 'RESOURCE_EXHAUSTED',
'details': [
{
'@type': 'type.googleapis.com/google.rpc.ErrorInfo',
'reason': 'RATE_LIMIT_EXCEEDED',
'domain': 'googleapis.com',
'metadata': {
'quota_limit': 'ReadRequestsPerMinutePerProject',
'quota_location': 'global',
'consumer': 'projects/some_id',
'quota_metric': 'sheets.googleapis.com/read_requests',
'service': 'sheets.googleapis.com',
'quota_limit_value': '1500'
}
},
{
'@type': 'type.googleapis.com/google.rpc.Help',
'links': [
{
'description': 'Request a higher quota limit.',
'url': 'https://cloud.google.com/docs/quota#requesting_higher_quota'
}
]
}
]
}
</code></pre>
<p>I tried to check my Google Cloud, but I can't even find the project id and the Google Sheets API is not even enabled (and even after I enabled it, there is not information in there)</p>
<p>Edit: not sure where I can find the usage metrics, this is the only thing I saw on google cloud
<a href="https://i.sstatic.net/Q8pbWSnZ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Q8pbWSnZ.png" alt="enter image description here" /></a></p>
|
<python><google-cloud-platform><google-colaboratory><google-sheets-api><gspread>
|
2024-08-16 03:22:19
| 0
| 798
|
qwerty_99
|
78,877,335
| 6,743,618
|
SQLAlchemy: multiple one-to-many relationships between the same 2 models
|
<p>This is a simplified version of my models. Say I have a User model with many billing addresses and many shipping addresses. Both correspond to the Address model.</p>
<pre class="lang-py prettyprint-override"><code>from sqlalchemy import ForeignKey
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
class Base(DeclarativeBase):
pass
class Address(Base):
__tablename__ = "addresses"
id: Mapped[int] = mapped_column(primary_key=True)
address: Mapped[str]
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"))
user = relationship("User")
class User(Base):
__tablename__ = "users"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str]
billing_addresses = relationship("Address", back_populates="user")
shipping_addresses = relationship("Address", back_populates="user")
</code></pre>
<p>If I simply do, for example:</p>
<pre class="lang-py prettyprint-override"><code>u = User()
</code></pre>
<p>Why do I get the following warning? And how do I resolve it?</p>
<blockquote>
<p>:1: SAWarning: relationship 'User.shipping_addresses' will copy column users.id to column addresses.user_id, which conflicts with relationship(s): 'User.billing_addresses' (copies users.id to addresses.user_id). If this is not the intention, consider if these relationships should be linked with back_populates, or if viewonly=True should be applied to one or more if they are read-only. For the less common case that foreign key constraints are partially overlapping, the orm.foreign() annotation can be used to isolate the columns that should be written towards. To silence this warning, add the parameter 'overlaps="billing_addresses"' to the 'User.shipping_addresses' relationship. (Background on this warning at: <a href="https://sqlalche.me/e/20/qzyx" rel="nofollow noreferrer">https://sqlalche.me/e/20/qzyx</a>) (This warning originated from the <code>configure_mappers()</code> process, which was invoked automatically in response to a user-initiated operation.)</p>
</blockquote>
<p>Thanks in advance!</p>
|
<python><sqlalchemy><orm>
|
2024-08-16 01:13:51
| 0
| 895
|
Javier López
|
78,877,314
| 14,761,117
|
NotNullViolation Error When Inserting Data into PostgreSQL Table with Non-Nullable ID Column
|
<p>I'm working on inserting data from a Pandas DataFrame into a PostgreSQL table using Python. The table structure is as follows:</p>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE sales (
id BIGINT NOT NULL, -- Primary Key
tahun INTEGER NOT NULL,
bulan NUMERIC NOT NULL,
v_kod VARCHAR(10) NOT NULL,
o_kod VARCHAR(10) NOT NULL,
amaun_rm NUMERIC NOT NULL,
dt_updated TIMESTAMP WITHOUT TIME ZONE NOT NULL
);
</code></pre>
<p>Here is my Python code:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import psycopg2
# Load the CSV data
forecast_results = pd.read_csv("sales.csv")
# Filter the DataFrame to include only rows from September 2024 onward
filtered_forecast_results = forecast_results[(forecast_results['tahun'] > 2024) |
((forecast_results['tahun'] == 2024) & (forecast_results['bulan'] >= 9))]
# Define the vot_kod value to be inserted
vot_kod_value = 'AAA'
# Connect to PostgreSQL
conn = psycopg2.connect(
dbname="my_database",
user="my_user",
password="my_password",
host="localhost",
port="5432"
)
cur = conn.cursor()
for index, row in filtered_forecast_results.iterrows():
# Convert the year and month to integers, but keep o_kod as a string
tahun = int(row['tahun'])
bulan = int(row['bulan'])
o_kod = str(row['o_kod '])
# Check if the row already exists
cur.execute("""
SELECT 1 FROM sales
WHERE tahun = %s AND bulan = %s AND v_kod = %s AND o_kod = %s
""", (tahun, bulan, v_kod_value, o_kod))
exists = cur.fetchone()
if not exists:
# If the row does not exist, insert it
sql_query = """
INSERT INTO sales (tahun, bulan, v_kod, o_kod, amaun_rm, dt_updated)
VALUES (%s, %s, %s, %s, %s, NOW())
"""
values = (
tahun,
bulan,
v_kod_value,
o_kod,
round(row['predicted_amaun_rm'], 2)
)
cur.execute(sql_query, values)
# Commit the transaction
conn.commit()
# Close the cursor and connection
cur.close()
conn.close()
</code></pre>
<p>When I run this code, I encounter the following error:</p>
<pre><code>NotNullViolation: null value in column "id" of relation "sales" violates not-null constraint
DETAIL: Failing row contains (null, 2024, 9, AAA, 123, 2931.48, 2024-08-16 08:39:52.462847).
</code></pre>
<p><strong>What I’ve Tried:</strong></p>
<ul>
<li>Excluding the id Column: I tried to exclude the id column from the INSERT statement, assuming PostgreSQL would auto-generate it. However, this led to the NotNullViolation error.</li>
<li>Manual ID Generation: I haven’t manually specified an id because I thought it should be auto-incremented.</li>
</ul>
<p><strong>Questions:</strong></p>
<ol>
<li>How can I properly insert the data while ensuring that the id column is populated correctly?</li>
<li>Should the id column be set up as an auto-incrementing column in PostgreSQL? If so, how can I modify the table to achieve this?</li>
<li>Is there a way to fetch and use the next available ID value within my Python code before insertion?</li>
</ol>
|
<python><database><postgresql><auto-increment>
|
2024-08-16 00:56:51
| 1
| 331
|
AmaniAli
|
78,877,275
| 16,725,431
|
Python class mimic makefile dependency
|
<p><strong>Q: Is there a better way to do this, or the idea itself is wrong</strong></p>
<p>I have a processing class that creates something with multiple construction steps, such that the next function depends on the previous ones.</p>
<p>I want to have dependencies specified like those in a <code>makefile</code>, and when the dependency does not exist, construct it.</p>
<p>I currently use a decorator to achieve it but it feels non pythonic.</p>
<p>Please take a look</p>
<pre><code>from typing import *
from functools import wraps
def step_method(dependency: Optional[dict[str, Callable]] = None):
if dependency is None:
dependency = {}
def decorator(method):
@wraps(method)
def wrapper(self, *args, **kwargs):
for attr, func in dependency.items():
if not getattr(self, attr):
func(self)
ret = method(self, *args, **kwargs)
return ret
return wrapper
return decorator
class StepClass:
def __init__(self, base_val:int):
self.base_val: int = base_val
self.a = None
self.b = []
self.c = None
self.d = []
@step_method({})
def gen_a(self):
self.a = self.base_val * 2
@step_method({'a': gen_a})
def create_b(self):
self.b = [self.a] * 3
@step_method({
'a': gen_a,
'b': create_b
})
def gen_c(self):
self.c = sum(self.b) * self.a
@step_method({'c': gen_c})
def generate_d(self):
self.d = list(range(self.c))
sc = StepClass(10)
sc.base_val = 7 # allow changes before generating starts
sc.b = [1, 2, 3] # allow dependency value injection
sc.generate_d()
print(sc.a, sc.b, sc.c, sc.d, sep='\n')
</code></pre>
<p>I also wonder if it's possible to detect the usage of variables automatically and generate them through a prespecified <code>dict</code> of function if they don't exist yet</p>
|
<python><python-3.x><makefile><python-decorators>
|
2024-08-16 00:29:29
| 1
| 444
|
Electron X
|
78,877,239
| 3,022,254
|
Pytorch MemoryMappedTensors causing Bus Error, possibly insufficient memory
|
<p>I'm loading some data using PyTorch's MemoryMappedTensor (version==2.4.0+cu118) and getting a Bus Error. I'm running the code using WSL2 on Windows 10:</p>
<blockquote>
<pre><code> Operating System: Windows 10 Pro 64-bit (10.0, Build 19045) (19041.vb_release.191206-1406)
Language: English (Regional Setting: English)
System Manufacturer: ASUS
BIOS: 3603 (type: UEFI)
Processor: AMD Ryzen 9 5950X 16-Core Processor (32 CPUs), ~3.4GHz
Memory: 65536MB RAM
Available OS Memory: 65436MB RAM
Page File: 7675MB used, 67487MB available
DirectX Version: DirectX 12
Card name: NVIDIA TITAN RTX
Manufacturer: NVIDIA
Chip type: NVIDIA TITAN RTX
DAC type: Integrated RAMDAC
Display Memory: 56985 MB
Dedicated Memory: 24268 MB
Shared Memory: 32717 MB
</code></pre>
</blockquote>
<p>It seems most likely to me that this Bus Error is being caused by insufficient memory; however, I can't understand why this would be an issue when all of my operations are on memory-mapped data, and I have plenty of memory to go around.</p>
<p>Here is the loop in which the error occurs:</p>
<pre><code> # Populate the empty tensors from .npy files on disk.
batch = num_output_sensors // 4
dl = torch.utils.data.DataLoader(disk_dataset, batch_size=batch, num_workers=0)
i = 0
pbar = tqdm.tqdm(total=len(disk_dataset))
for c1, c2, f, kappa, output, sensor_coords in dl:
_batch = c1.shape[0]
pbar.update(_batch)
#
# =============
# PROBLEM CODE:
# =============
#
# data[i : i + _batch] = cls(
# f=f,
# c1=c1,
# c2=c2,
# kappa=kappa,
# output=output,
# sensor_coords=sensor_coords,
# batch_size=[_batch]
# )
i += _batch
</code></pre>
<p>and here it is in context:</p>
<pre><code>@tensorclass
class MemoryMappedTensorDataset:
# Tensors to be memmapped
# =======================
f: torch.Tensor
kappa: torch.Tensor
c1: torch.Tensor
c2: torch.Tensor
output: torch.Tensor
sensor_coords: torch.Tensor
# Dict keys for metadata
# ======================
NUM_DATA = "num_data"
NUM_INPUT_SENSORS_2D = "num_input_sensors_2D"
NUM_OUTPUT_SENSORS_1D = "num_output_sensors"
NO_VELOCITY = "no_velocity"
ALL_KEYWORDS = [NUM_DATA, NUM_INPUT_SENSORS_2D, NUM_OUTPUT_SENSORS_1D, NO_VELOCITY]
@classmethod
def from_data_directory(cls, data_dir:Path):
( num_data,
num_input_sensors_2D,
num_input_sensors_total,
num_output_sensors,
no_velocity ) = cls._extract_meta_data(data_dir)
# Fix shape of data tensors
# NOTE: If there is no velocity, c1 and c2 are identically zero;
# however, the current implementation still passes these
# variables. So for now, I'll include them as a constant,
# stored once per data point
# NOTE: output_shape includes data for u, du/dx, and du/dy
input_shape_constant = (num_data, 1)
input_shape_2D = (num_data, *num_input_sensors_2D)
input_shape_flattened = (num_data, num_input_sensors_total, 1)
output_shape = (num_data, 3)
coord_shape = (num_data, 2)
c_shape = input_shape_constant if no_velocity else input_shape_2D
# Creates empty memmapped tensors
data = cls(
f = MemoryMappedTensor.empty(input_shape_flattened, dtype=torch.float),
kappa = MemoryMappedTensor.empty(input_shape_2D, dtype=torch.float),
c1 = MemoryMappedTensor.empty(c_shape, dtype=torch.float),
c2 = MemoryMappedTensor.empty(c_shape, dtype=torch.float),
output = MemoryMappedTensor.empty(output_shape, dtype=torch.float),
sensor_coords = MemoryMappedTensor.empty(coord_shape, dtype=torch.float),
batch_size=[num_data]
)
# Locks the tensorclass and ensures that is_memmap() will return True.
data.memmap_()
# Collect data from disk
disk_dataset = cls._extract_data(data_dir)
# Populate the empty tensors from .npy files on disk.
batch = num_output_sensors // 4
dl = torch.utils.data.DataLoader(disk_dataset, batch_size=batch, num_workers=0)
i = 0
pbar = tqdm.tqdm(total=len(disk_dataset))
for c1, c2, f, kappa, output, sensor_coords in dl:
_batch = c1.shape[0]
pbar.update(_batch)
#
# =============
# PROBLEM CODE:
# =============
#
# data[i : i + _batch] = cls(
# f=f,
# c1=c1,
# c2=c2,
# kappa=kappa,
# output=output,
# sensor_coords=sensor_coords,
# batch_size=[_batch]
# )
i += _batch
return disk_dataset
@classmethod
def _extract_data(cls, data_dir:Path):
npy_dir = data_dir / "npy_data"
if not npy_dir.exists():
raise RuntimeError(
"No numpy data directory found for the dataset at %s. "
"Aborting!" % npy_dir.as_posix()
)
for filename in ["c1", "c2", "f", "kappa", "output"]:
data_path = npy_dir / ("%s.npy" % filename)
if not data_path.exists():
raise RuntimeError(
"No numpy data file found at %s. "
"Aborting!" % data_path.as_posix()
)
c1 = torch.from_numpy(np.load(npy_dir / "c1.npy", mmap_mode="r+"))
c2 = torch.from_numpy(np.load(npy_dir / "c2.npy", mmap_mode="r+"))
f = torch.from_numpy(np.load(npy_dir / "f.npy", mmap_mode="r+"))
kappa = torch.from_numpy(np.load(npy_dir / "kappa.npy", mmap_mode="r+"))
output = torch.from_numpy(np.load(npy_dir / "output.npy", mmap_mode="r+"))
sensor_coords = torch.from_numpy(np.load(npy_dir / "sensor_coords.npy", mmap_mode="r+"))
return torch.utils.data.TensorDataset(
c1,
c2,
f,
kappa,
output,
sensor_coords
)
@classmethod
def _extract_meta_data(cls, data_dir:Path):
meta_data_file_path = data_dir / "meta.yaml"
if not meta_data_file_path.exists():
raise RuntimeError(
"No metadata found for the dataset at %s. "
"Aborting!" % meta_data_file_path.as_posix()
)
meta_data:dict
with meta_data_file_path.open(mode="r") as yml_file:
meta_data = yaml.safe_load(yml_file)
try:
num_data = meta_data[cls.NUM_DATA]
num_input_sensors_2D = meta_data[cls.NUM_INPUT_SENSORS_2D]
num_output_sensors_1D = meta_data[cls.NUM_OUTPUT_SENSORS_1D]
no_velocity = meta_data[cls.NO_VELOCITY]
except KeyError:
tabbed_keywords = "\n\t-".join(['']+cls.ALL_KEYWORDS)
raise RuntimeError(
f"One or more of the required metadata are missing from {(data_dir / 'metadata.yaml').as_posix()}:"
f"{tabbed_keywords}\nAborting!"
)
try:
num_input_sensors_total = num_input_sensors_2D[0] * num_input_sensors_2D[1]
except IndexError:
raise RuntimeError(
f"Expected {cls.NUM_INPUT_SENSORS_2D} to be a tuple in {(data_dir / 'metadata.yaml').as_posix()}, "
f"but got {str(num_input_sensors_2D)} instead. \nAborting!"
)
return num_data, num_input_sensors_2D, num_input_sensors_total, num_output_sensors_1D, no_velocity
</code></pre>
<p>The bus error only occurs if I uncomment the "PROBLEM CODE" that I've called out above, and it always occurs at 80% of completion. If it is caused by insufficient memory, I'm at a loss as to why:</p>
<ul>
<li>Shouldn't the memory use be fairly constant between iterations? Why would it increase?</li>
<li>And for that matter, the memory required to store an individual batch should not be especially large; is there a reason the memory use might be larger than expected?</li>
<li>Is it possible the Bus Error is being caused, not by insufficient memory, but insufficient virtual disk space on WSL2? If so, why wouldn't that happen when I first instantiate the MemoryMappedTensors?</li>
<li>Is there another obvious possibility that I'm overlooking?</li>
</ul>
|
<python><pytorch><memory-mapped-files><bus-error>
|
2024-08-16 00:10:47
| 0
| 1,372
|
Mackie Messer
|
78,876,815
| 2,171,348
|
FastAPI - Pydantic model does not allow space in value of string Enum value?
|
<pre><code>python 3.12.5
pydantic 2.8.2
fastapi 0.111.1
</code></pre>
<p>Running in a docker container on WSL2 Ubuntu 22.04 LTS.</p>
<p>Here is the model class definition:</p>
<pre class="lang-py prettyprint-override"><code>from enum import Enum
from app.models.common.base import DomainModel
class ProjectState(str, Enum):
ACTIVE = "active"
ARCHIVED = "archived"
class ProjectType(str, Enum):
MIGRATION_CONFIG = "Migration Config"
MIGRATION_CLEANUP = "Migration_Cleanup"
class Project(DomainModel):
name: str
type: ProjectType.MIGRATION_CONFIG
customer_id: str
state: ProjectState = ProjectState.ACTIVE
</code></pre>
<p>The value for enum <code>ProjectType.MIGRATION_CONFIG</code> has a space character in it. This space character prevents fastapi server from starting because of the following error:</p>
<pre><code>SyntaxError: Forward reference must be an expression -- got <ProjectType.MIGRATION_CONFIG: 'Migration Config'>
</code></pre>
<p>If I change the space character to underscore character, then fastapi server has no problem to startup.</p>
<p>I don't quite understand the message in the SyntaxError. It doesn't seem to be problem in python without pydantic.</p>
|
<python><enums><fastapi><pydantic>
|
2024-08-15 20:57:33
| 1
| 481
|
H.Sheng
|
78,876,658
| 7,577,930
|
Strange timing and order of prints to log
|
<p>I ran the following program through a Slurm job:</p>
<pre class="lang-python prettyprint-override"><code>import datetime
print(f'Program started at {datetime.datetime.now()}.')
# More imports here.
print(f'Modules finished loading at {datetime.datetime.now()}.')
seed_everything(7253, workers=True)
</code></pre>
<p><code>seed_everything</code> is defind at <a href="https://github.com/Lightning-AI/pytorch-lightning/blob/1551a16b94f5234a4a78801098f64d0732ef5cb5/src/lightning/fabric/utilities/seed.py#L20" rel="nofollow noreferrer">PyTorch Lightning</a> and prints using the <code>logging</code> module.</p>
<p>The program produced the following log file:</p>
<pre><code>[rank: 0] Seed set to 7253
Program started at 2024-08-15 16:20:52.034715.
Modules finished loading at 2024-08-15 16:21:01.970554.
</code></pre>
<p>All lines got printed to the log file at around the same time, at 16:21:04.</p>
<p>Why wasn't the "Program started" line printed at 16:20:52, when <code>print</code> was called?</p>
<p>And how did the "Seed set" line manage to get printed first?</p>
|
<python><logging><slurm><pytorch-lightning>
|
2024-08-15 19:54:49
| 1
| 346
|
Moon
|
78,876,255
| 8,537,770
|
mypy function signature matching for **kwargs argument and different kinds of return types
|
<p>I have a class that I am trying to make as an interface. For simplicity, I've only included one of the abstract methods (see below).</p>
<pre class="lang-py prettyprint-override"><code>class MyInterface(metaclass=abc.ABCMeta):
@classmethod
def __subclasshook__(cls, subclass):
return (hasattr(subclass, "do_stuff") and callable(subclass.do_stuff))
@abc.abstractmethod
def do_stuff(self, input: str, output: str, **kwargs) -> Union[str, list[str]]:
raise NotImplementedError
</code></pre>
<p>In a subclasses that inherit this, I'd like the <code>**kwargs</code> to be an optional thing we can add. I also would like the return type to be either a string or list of strings not both, so four use cases</p>
<pre class="lang-py prettyprint-override"><code>class ImpClass1(MyInterface):
def do_stuff(self, input: str, output: str, **kwargs) -> str: ...
class ImpClass2(MyInterface):
def do_stuff(self, input: str, output: str, **kwargs) -> list[str]: ...
class ImpClass3(MyInterface):
def do_stuff(self, input: str, output: str) -> str: ...
class ImpClass4(MyInterface):
def do_stuff(self, input: str, output: str) -> list[str]: ...
</code></pre>
<p>mypy throws an error currently when I use the third use case, so I assume the rest will fail similarly</p>
<pre class="lang-py prettyprint-override"><code>src/tests/parser/test_interface.py:43: error: Signature of "do_stuff" incompatible with supertype "MyInterface" [override]
src/tests/parser/test_interface.py:43: note: Superclass:
src/tests/parser/test_interface.py:43: note: def do_stuff(self, input: str, output: str, **kwargs: Any) -> Union[str, list[str]]
src/tests/parser/test_interface.py:43: note: Subclass:
src/tests/parser/test_interface.py:43: note: def do_stuff(self, input: str, output: str) -> str
</code></pre>
<p>How do I have mypy catch breaks of the signature but not for the cases that I've listed above?</p>
|
<python><python-typing><mypy>
|
2024-08-15 17:38:03
| 0
| 663
|
A Simple Programmer
|
78,876,137
| 610,569
|
How to disable string processing in wikipedia-1.4.0 API?
|
<p>When using the <a href="https://pypi.org/project/wikipedia/" rel="nofollow noreferrer">https://pypi.org/project/wikipedia/</a> API, <code>wikipedia==1.4.0</code>, it seems that when accessing the page, the library would first do some string processing to alter the inputs, e.g.</p>
<pre><code>import wikipedia
wikipedia.page('Backstreet Boys')
</code></pre>
<p>[out]:</p>
<pre><code>PageError Traceback (most recent call last)
Cell In[3], line 1
----> 1 wikipedia.page('Backstreet Boys')
File ~/miniconda3/lib/python3.9/site-packages/wikipedia/wikipedia.py:276, in page(title, pageid, auto_suggest, redirect, preload)
273 except IndexError:
274 # if there is no suggestion or search results, the page doesn't exist
275 raise PageError(title)
--> 276 return WikipediaPage(title, redirect=redirect, preload=preload)
277 elif pageid is not None:
278 return WikipediaPage(pageid=pageid, preload=preload)
File ~/miniconda3/lib/python3.9/site-packages/wikipedia/wikipedia.py:299, in WikipediaPage.__init__(self, title, pageid, redirect, preload, original_title)
296 else:
297 raise ValueError("Either a title or a pageid must be specified")
--> 299 self.__load(redirect=redirect, preload=preload)
301 if preload:
302 for prop in ('content', 'summary', 'images', 'references', 'links', 'sections'):
File ~/miniconda3/lib/python3.9/site-packages/wikipedia/wikipedia.py:345, in WikipediaPage.__load(self, redirect, preload)
343 if 'missing' in page:
344 if hasattr(self, 'title'):
--> 345 raise PageError(self.title)
346 else:
347 raise PageError(pageid=self.pageid)
PageError: Page id "back street boys" does not match any pages. Try another id!
</code></pre>
<p>How to disable string processing in wikipedia-1.4.0 API?</p>
|
<python><wikipedia><wikipedia-api>
|
2024-08-15 17:02:06
| 1
| 123,325
|
alvas
|
78,876,123
| 2,808,020
|
GitHub file search by name results differ from web when using API or pyGitHub
|
<p>I have a large git repo with multiple .Net solutions in it (in the example repo there is only one). I want to return the paths of all the <code>Directory.Packages.props</code> files within that specific repo. I am trying to use the code below:</p>
<pre><code>from github import Github
token = '<my token>'
# Create a GitHub instance using the token
g = Github(token)
# Search for the file
result = g.search_code('Xcaciv/Xcaciv.Command', qualifiers={'path': '**/Directory.Packages.props'})
# Print the file content
print(result.totalCount)
</code></pre>
<p>I have tried several combinations for the parameters to <code>search_code()</code> without success. I feel like I am missing something simple but cannot see it. I have tried putting <code>repo:Xcaciv/Xcacive.Command</code> for the first parameter. I have tried to just use the string <code>repo:Xcaciv/Xcaciv.Command path:**/Directory.Packages.props</code> with no success. I have also tried calling the API directly in this same manner without success.</p>
<p>Each time I try I get HTTP 200 with a result of <code>0</code> (no results).</p>
<p>I appreciate any guidance.</p>
|
<python><github-api><pygithub>
|
2024-08-15 16:57:55
| 1
| 704
|
AC4
|
78,875,978
| 5,287,011
|
Error using LlmFactory with "TheBloke/OpenHermes-2.5-Mistral-7B-GGUF" Huggingface
|
<p>I tried replicating a simple Python code to create a small LLM model.</p>
<p>I have macOS M1 machine.
I created a separate environment where I installed Pytorch and llama-cpp-python. The code:</p>
<pre><code>from llmflex import LlmFactory
# Load the model from Huggingface
try:
# Instantiate the model with the correct identifier
model = LlmFactory("TheBloke/OpenHermes-2.5-Mistral-7B-GGUF")
# Configure parameters directly if the object itself is callable
#llm = model(temperature=0.7, max_new_tokens=512)
# Disable Metal and run on CPU
llm = model(temperature=0.7, max_new_tokens=512, use_metal=False)
# Generate a response
response = llm.generate("Hello, how are you?")
print(response)
except AttributeError as e:
print(f"Attribute error: {e}")
except AssertionError as e:
print(f"Assertion error: {e}")
except Exception as e:
print(f"An error occurred: {e}")
</code></pre>
<p>As you can see, I tried with and without Metal, but I received the same error (the last portion of the output):</p>
<pre><code>llm_load_vocab: special tokens definition check successful ( 261/32002 ).
llm_load_print_meta: format = GGUF V3 (latest)
llm_load_print_meta: arch = llama
llm_load_print_meta: vocab type = SPM
llm_load_print_meta: n_vocab = 32002
llm_load_print_meta: n_merges = 0
llm_load_print_meta: n_ctx_train = 32768
llm_load_print_meta: n_embd = 4096
llm_load_print_meta: n_head = 32
llm_load_print_meta: n_head_kv = 8
llm_load_print_meta: n_layer = 32
llm_load_print_meta: n_rot = 128
llm_load_print_meta: n_gqa = 4
llm_load_print_meta: f_norm_eps = 0.0e+00
llm_load_print_meta: f_norm_rms_eps = 1.0e-05
llm_load_print_meta: f_clamp_kqv = 0.0e+00
llm_load_print_meta: f_max_alibi_bias = 0.0e+00
llm_load_print_meta: n_ff = 14336
llm_load_print_meta: n_expert = 0
llm_load_print_meta: n_expert_used = 0
llm_load_print_meta: rope scaling = linear
llm_load_print_meta: freq_base_train = 10000.0
llm_load_print_meta: freq_scale_train = 1
llm_load_print_meta: n_yarn_orig_ctx = 32768
llm_load_print_meta: rope_finetuned = unknown
llm_load_print_meta: model type = 7B
llm_load_print_meta: model ftype = Q2_K
llm_load_print_meta: model params = 7.24 B
llm_load_print_meta: model size = 2.87 GiB (3.41 BPW)
llm_load_print_meta: general.name = teknium_openhermes-2.5-mistral-7b
llm_load_print_meta: BOS token = 1 '<s>'
llm_load_print_meta: EOS token = 32000 '<|im_end|>'
llm_load_print_meta: UNK token = 0 '<unk>'
llm_load_print_meta: PAD token = 0 '<unk>'
llm_load_print_meta: LF token = 13 '<0x0A>'
llm_load_tensors: ggml ctx size = 0.11 MiB
llm_load_tensors: mem required = 2939.69 MiB
llama_new_context_with_model: n_ctx = 4096
llama_new_context_with_model: freq_base = 10000.0
llama_new_context_with_model: freq_scale = 1
llama_new_context_with_model: KV self size = 512.00 MiB, K (f16): 256.00 MiB, V (f16): 256.00 MiB
llama_build_graph: non-view tensors processed: 676/676
ggml_metal_init: allocating
ggml_metal_init: found discrete device: Apple M1
ggml_metal_init: picking device: Apple M1
ggml_metal_init: default.metallib not found, loading from source
ggml_metal_init: GGML_METAL_PATH_RESOURCES = nil
ggml_metal_init: error: could not use bundle path to find ggml-metal.metal, falling back to trying cwd
ggml_metal_init: loading 'ggml-metal.metal'
ggml_metal_init: error: Error Domain=NSCocoaErrorDomain Code=260 "The file “ggml- metal.metal” couldn’t be opened because there is no such file." UserInfo=. {NSFilePath=ggml-metal.metal, NSUnderlyingError=0x600002eeb2a0 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}
llama_new_context_with_model: ggml_metal_init() failed
AVX = 0 | AVX2 = 0 | AVX512 = 0 | AVX512_VBMI = 0 | AVX512_VNNI = 0 | FMA = 0 | NEON = 1 | ARM_FMA = 1 | F16C = 0 | FP16_VA = 1 | WASM_SIMD = 0 | BLAS = 1 | SSE3 = 0 | SSSE3 = 0 | VSX = 0 |
Assertion error:
</code></pre>
<p>Obviously, something is wrong, but I cannot pinpoint the error because I am new to this.</p>
<p>I do not want to use CUDA; I want to use the CPU.</p>
<p>Please, help</p>
<p>Here is some additional information: <a href="https://huggingface.co/TheBloke/OpenHermes-2.5-Mistral-7B-GGUF" rel="nofollow noreferrer">https://huggingface.co/TheBloke/OpenHermes-2.5-Mistral-7B-GGUF</a></p>
|
<python><pytorch><metal><large-language-model><huggingface>
|
2024-08-15 16:11:45
| 1
| 3,209
|
Toly
|
78,875,935
| 5,738,150
|
Aligning a 3D face mesh to face the camera
|
<p>I'm working on aligning a 3D face mesh using PyVista for visualization. My goal is to position the nose tip at the origin (0, 0, 0) and ensure that the eyes are aligned along the Y-axis so that the face is directly facing the camera. Here's what I'm aiming to achieve:</p>
<p>I have already extracted the nose tip, left eye, and right eye coordinates and attempted to translate the mesh so that the nose tip is at the origin. However, aligning the face properly with the eyes on the Y-axis has been challenging. Here is what I achieved so far:</p>
<pre><code>import pyvista as pv
import numpy as np
import yaml
from scipy.spatial.transform import Rotation as R
# Path to the OBJ file
obj_file = "checkpoints/custom/results/examples/epoch_20_000000/000002.obj"
# Load the points from the YAML file
with open('selected_point_ids.yaml', 'r') as file:
data = yaml.safe_load(file)
point_ids = data['point_ids']
# Read the OBJ file
mesh = pv.read(obj_file)
# Retrieve the coordinates of the selected points from the mesh
selected_points = mesh.points[point_ids]
# Assume the points are [nose_tip, left_eye, right_eye]
nose_tip = selected_points[0]
left_eye = selected_points[1]
right_eye = selected_points[2]
# Translation: Move the nose tip to the origin (0, 0, 0)
translation_vector = -nose_tip
translated_mesh = mesh.copy()
translated_mesh.points = mesh.points + translation_vector
</code></pre>
<p>I need help for rotating the mesh. Or at least some directions to look after.</p>
|
<python><geometry><spatial><vtk><pyvista>
|
2024-08-15 16:00:59
| 1
| 728
|
colt.exe
|
78,875,922
| 3,327,344
|
How to read and input data into a table graph in an template word file using python docx
|
<p>I have a docx file with table graph which can not recognized by doc.tables.
Here is the file:
<a href="https://github.com/python-openxml/python-docx/files/1867861/non_readable_table.docx" rel="nofollow noreferrer">https://github.com/python-openxml/python-docx/files/1867861/non_readable_table.docx</a></p>
<p>Same issue was encountered <a href="https://github.com/python-openxml/python-docx/issues/488" rel="nofollow noreferrer">here</a>. But no answer was given. Please let me know if you have any solution.</p>
<pre><code>from docx import Document
doc = Document("non_readable_table.docx")
print(doc.tables)
def iter_tables(block_item_container):
"""Recursively generate all tables in `block_item_container`."""
for t in block_item_container.tables:
yield t
for row in t.rows:
for cell in row.cells:
yield from iter_tables(cell)
dfs = []
for t in iter_tables(doc):
table = t
df = [['' for i in range(len(table.columns))] for j in range(len(table.rows))]
for i, row in enumerate(table.rows):
for j, cell in enumerate(row.cells):
if cell.text:
df[i][j] = cell.text.replace('\n', '')
dfs.append(pd.DataFrame(df))
print(dfs)
</code></pre>
|
<python><ms-word><python-docx>
|
2024-08-15 15:58:35
| 1
| 509
|
xie186
|
78,875,846
| 11,065,874
|
how to maintain the order of logs when using python's subprocess to call other processes
|
<p>I have <code>a.sh</code> as below</p>
<pre><code>#!/bin/bash
echo 100
python3 b.py
if [ $? -ne 0 ]; then
exit 1
fi
echo "this will not be printed"
</code></pre>
<p>and <code>b.py</code> as below</p>
<pre><code>import subprocess
print("101")
result = subprocess.run(["bash", "c.sh"], capture_output=True, text=True)
print(result.stderr)
print(result.stdout)
if result.check_returncode:
raise Exception("")
</code></pre>
<p>and <code>c.sh</code> as below:</p>
<pre><code>#!/bin/bash
echo 102 >&2
echo 103
echo 104 >&2
exit 1
echo "this will not be printed"
</code></pre>
<p>In a bash terminal I run bash a.sh and the result is</p>
<pre><code>100
101
102
104
103
Traceback (most recent call last):
File "/Users/abamavad/ssc-github/ssce/cmn-deployment/b.py", line 9, in <module>
raise Exception("")
Exception
</code></pre>
<p>I am looking for a way to keep the order of the logs so that I get</p>
<pre><code>100
101
102
103
104
Traceback (most recent call last):
File "/Users/abamavad/ssc-github/ssce/cmn-deployment/b.py", line 9, in <module>
raise Exception("")
Exception
</code></pre>
<p>I know where my problem is:</p>
<pre><code>result = subprocess.run(["bash", "c.sh"], capture_output=True, text=True)
print(result.stderr)
print(result.stdout)
</code></pre>
<p>but don't know how to fix it. how should I maintain the order of the log whether or not they are stdout or stdin</p>
|
<python><linux><subprocess>
|
2024-08-15 15:38:55
| 1
| 2,555
|
Amin Ba
|
78,875,771
| 4,247,599
|
python `(datetime.datetime.now() - datetime.datetime.now()).seconds` does not return 0 seconds
|
<p>I'm working with python 3.12.4 and using the standard library datetime.</p>
<p>I am expecting the difference between two datetime.now to be zero. Instead I get a number like <code>86399</code>.</p>
<pre><code>import datetime
print((datetime.datetime.now() - datetime.datetime.now()).seconds) # returns 86399
</code></pre>
<p>Anyone knows why this is happening technically?</p>
<p>If I run something like this</p>
<pre><code>a = dt.datetime.now()
b = dt.datetime.now()
print((b - a).seconds) # returns 0
</code></pre>
<p>then the result is zero as expected.</p>
|
<python><datetime>
|
2024-08-15 15:19:26
| 1
| 4,299
|
SeF
|
78,875,770
| 6,597,296
|
How to use startTLS in Twisted?
|
<p>I want to establish a non-encrypted connection to a server and then, upon sending an agreed-upon command, to switch to a TLS-encrpted connection. It seems that Twisted's <code>startTLS</code> is meant exactly for this purpose - except I can't make it to work, not even the very examples given in Twisted's <a href="https://docs.twisted.org/en/stable/core/howto/ssl.html#using-starttls" rel="nofollow noreferrer">official documentation</a>.</p>
<p>Obviously, these examples depend on an external file, called <code>server.pem</code>. Higher on that page of the documentation, it says that this file is "private key and self-signed certificate together". So, I used OpenSSL to create it:</p>
<pre><code>openssl req -x509 -newkey rsa:4096 -keyout serverkey.pem -out servercert.pem -sha256 -days 3650 -nodes -subj "/CN=localhost"
copy serverkey.pem+servercert.pem server.pem
</code></pre>
<p>If I now run the server example, <code>starttls_server.py</code>, it works fine - but if I run the client example, <code>starttls_client.py</code>, it crashes with a stack trace and the error</p>
<pre class="lang-py prettyprint-override"><code>service_identity.exceptions.CertificateError: Certificate does not contain any `subjectAltName`s.
</code></pre>
<p>I have no idea what this means (and googling didn't help) but it seems strange to me that both the client and the server are using the same <code>server.pem</code> file. Although I can't see anything theoretically wrong with the idea, in practice it would virtually impossible for both the client and the server to have the same private key, so maybe <code>pyOpenSSL</code> contains some kind of check to report such an oddity as an error.</p>
<p>So, I created yet another private key and self-signed certificate, stored them in a file named <code>client.pem</code></p>
<pre><code>openssl req -x509 -newkey rsa:4096 -keyout clientkey.pem -out clientcert.pem -sha256 -days 3650 -nodes -subj "/CN=localhost"
copy clientkey.pem+clientcert.pem client.pem
</code></pre>
<p>and modified the file <code>starttls_client.py</code> to use <code>client.pem</code> instead of <code>server.pem</code>.</p>
<p>The result sort of works, in the sense that the client doesn't crash any more - but it doesn't really work, because it doesn't do what it is supposed to do.</p>
<p>Looking at the code, the server is supposed to print every line sent by the client and, if this line is <code>STARTTLS</code>, to print <code>-- Switching to TLS</code>, send the line <code>READY</code> to the client, and call <code>startTLS</code>.</p>
<p>The client, upon establishing a connection to the server, is supposed to send the line <code>plain text</code>, then <code>STARTTLS</code>. If it receives the line <code>READY</code> from the server, it is supposed to call <code>startTLS</code>, then send the line <code>secure text</code> to the server.</p>
<p>There is what actually happens:</p>
<p>The server prints</p>
<pre><code>received: b'plain text'
received: b'STARTTLS'
-- Switching to TLS
</code></pre>
<p>meaning that it did receive the plantext line from the client, then the command to switch to TLS-encrypted connection, and has called <code>startTLS</code>.</p>
<p>The client prints only</p>
<pre><code>received: b'READY'
</code></pre>
<p>and exits. That is, at this point it has established a non-encrypted communication with the server, has send the command to switch to TLS-encrypted communication, and has received the (plaintext) acknowledgement from the server. At this point, the communication is supposed to be TLS-encrypted, so the client has, pesumably, sent the line <code>secure text</code> to the server and exits.</p>
<p>Except the server never prints <code>secure text</code>, so clearly it has not received this line.</p>
<p>I am stumped at this point. I was expecting at least the examples from the Twisted documentation to work "as is" but, apparently, this is not the case. Any ideas what might be wrong? Is there some problem with my generation of the private keys and self-signed certificates? The PEM files are the only thing I have created myself instead of using literally what is in Twisted's documentation.</p>
|
<python><twisted>
|
2024-08-15 15:19:17
| 1
| 578
|
bontchev
|
78,875,714
| 13,088,678
|
Non Spark code (Plain Python) run on Spark cluster
|
<p>As per the doc (<a href="https://docs.databricks.com/en/optimizations/spark-ui-guide/spark-job-gaps.html" rel="nofollow noreferrer">https://docs.databricks.com/en/optimizations/spark-ui-guide/spark-job-gaps.html</a>), Any execution of code that is not Spark will show up in the timeline as gaps.For example, <code>you could have a loop in Python which calls native Python functions. This code is not executing in Spark</code> and it can show up as a gap in the timeline.</p>
<p>Where does the non spark code (plain python code) runs? Is it on any worker or Driver?</p>
|
<python><apache-spark><databricks>
|
2024-08-15 15:04:32
| 1
| 407
|
Matthew
|
78,875,711
| 1,277,239
|
Concatenate matrices and vectors in Python
|
<p>I am a MATLAB user, and trying to convert a rotation/translation code into Python:</p>
<pre><code>from functools import reduce
import numpy as np
import matplotlib as plt
from math import pi as PI
from math import sin as sin
from math import cos as cos
# plt.close('all')
# coordinate in old system
x0 = np.array([ [10],
[5],
[0],])
x = x0
# translation
# origin of old coordinate system in relative to the new coordinate system
T = np.array([ [10],
[0],
[0]])
## rotation
# rotate alpha, beta, and gamme about x-axis, y-axis, and z- axis,
# respectively, in relative to the new coordinate system
alpha = 0
beta = 0
gamma = PI/2
# rotation matrices
Rx = np.array([ [1, 0, 0],
[0, cos(alpha), -sin(alpha)],
[0, sin(alpha), cos(alpha)] ])
Ry = np.array([ [cos(beta), 0, sin(beta)],
[0, 1, 0],
[-sin(beta), 0, cos(beta)]])
Rz = np.array([ [cos(gamma), -sin(gamma), 0],
[sin(gamma), cos(gamma), 0],
[0, 0, 1] ])
# R = Rz*Ry*Rx
R = reduce(np.dot, [Rz, Ry, Rx])
RT = np.array([ [R, T],
[0, 0, 0, 1]])
</code></pre>
<p>The last line trying to create a homogeneous 4X4 matrix <code>RT</code> by stacking a 3X3 rotation matrix <code>R</code> and 3X1 translation vector <code>T</code>. The [0,0,0,1] at the bottom of the matrix is just to turn the transformation matrix <code>RT</code> into a homogeneous format.</p>
<p>The code have problem stack the <code>R</code>, <code>T</code> and <code>[0,0,0,1]</code> together. I am trying understand what is the proper way to do it? Thanks!!</p>
|
<python><matrix>
|
2024-08-15 15:03:32
| 1
| 2,912
|
Nick X Tsui
|
78,875,646
| 4,913,254
|
When adding planes to my 3D scatter plot, one plane is not shown (Plotly)
|
<p>I am creating three plots in one HTML file. The third plot is a 3D scatter plot in which I want to add two planes. For a reason the same approach add the second plane but not the first. I though that the second plane overwrite the first but this is not the case.</p>
<p>This is the whole script of my script</p>
<pre><code>import pandas as pd
import plotly.express as px
import plotly.io as pio
import plotly.graph_objs as go
# Load the merged data
merged_data = pd.read_csv('Merged_Variants_with_TP_FP_and_Data_origin.csv')
# Apply the first filter to select only 'PASS' variants in the 'Original filter' column
filtered_data_original = merged_data[merged_data['Original filter'] == 'PASS']
# Apply the second filter to select only SNPs (where the length of REF and ALT is 1)
filtered_data_original['Mutation_Type'] = filtered_data_original.apply(
lambda row: 'SNP' if len(row['REF']) == 1 and len(row['ALT']) == 1 else 'indel', axis=1)
filtered_data_original = filtered_data_original[filtered_data_original['Mutation_Type'] == 'SNP']
# Split the 'AD' column into two new columns 'AD_REF' and 'AD_ALT'
filtered_data_original[['Number of REF reads', 'Number of ALT reads']] = filtered_data_original['AD'].str.split(',', expand=True)
# Convert the new columns to integers
filtered_data_original['Number of REF reads'] = pd.to_numeric(filtered_data_original['Number of REF reads'])
filtered_data_original['Number of ALT reads'] = pd.to_numeric(filtered_data_original['Number of ALT reads'])
# Create a new column for the combined TP and Data_origin for the legend
filtered_data_original['Legend_Group'] = filtered_data_original['TP'] + " " + filtered_data_original['Data_origin']
filtered_data_original["MBQ_diff"] = pd.to_numeric(filtered_data_original["MBQ_REF"], errors='coerce') - pd.to_numeric(filtered_data_original["MBQ_ALT"], errors='coerce')
filtered_data_original["MMQ_dif"] = pd.to_numeric(filtered_data_original["MMQ_REF"], errors='coerce') - pd.to_numeric(filtered_data_original["MMQ_ALT"], errors='coerce')
# Filter the DataFrame for additional classification
Detected_False_positive_MBQ = filtered_data_original.loc[
filtered_data_original['New filter'].str.contains("high_diff_MBQ", na=False)]
Detected_False_positive_MMQ = filtered_data_original.loc[
filtered_data_original['New filter'].str.contains("high_diff_MMQ", na=False)]
Detected_False_positive = filtered_data_original.loc[
filtered_data_original['New filter'] != "PASS"]
# Create the first plot: Variant Frequency vs. Difference in MBQ
fig1 = px.scatter(
data_frame=filtered_data_original,
x='VF',
y='MBQ_diff',
color='TP',
symbol='Data_origin',
title="Variant Frequency vs. Difference in MBQ",
labels={'VF': 'Variant Frequency (VF)', 'MBQ_diff': 'Difference in MBQ (MBQ_diff)'},
color_discrete_map={'TP': 'green', 'FP': 'red'},
symbol_map={'Somatic_training_data': 'star', 'Ssrep_training_data': 'circle'},
hover_data={
'Sample': True,
'Chrom': True,
'Pos': True,
'REF': True,
'ALT': True,
'QUAL': True,
'Original filter': True,
'DP': True,
'VF': True,
'TP': True,
'Mutation_Type': True,
'MMQ_dif': True,
'MBQ_diff': True,
'Data_origin': True,
'Number of REF reads': True,
'Number of ALT reads': True,
'New filter': True,
}
)
# Add the subset (False Positives) to the first plot
fig1.add_trace(px.scatter(
data_frame=Detected_False_positive_MBQ,
x='VF',
y='MBQ_diff',
color_discrete_sequence=['black'], # Color the dots black
symbol_sequence=['circle'], # Use small dots
hover_data={
'Sample': True,
'Chrom': True,
'Pos': True,
'REF': True,
'ALT': True,
'QUAL': True,
'Original filter': True,
'DP': True,
'VF': True,
'TP': True,
'Mutation_Type': True,
'MMQ_dif': True,
'MBQ_diff': True,
'Data_origin': True,
'Number of REF reads': True,
'Number of ALT reads': True,
'New filter': True,
},
size_max=1
).update_traces(marker=dict(size=5, opacity=0.8), name='False Positives').data[0])
# Create the second plot: Variant Frequency vs. Difference in MMQ
fig2 = px.scatter(
data_frame=filtered_data_original,
x='VF',
y='MMQ_dif',
color='TP',
symbol='Data_origin',
title="Variant Frequency vs. Difference in MMQ",
labels={'VF': 'Variant Frequency (VF)', 'MMQ_dif': 'Difference in MMQ (MMQ_dif)'},
color_discrete_map={'TP': 'green', 'FP': 'red'},
symbol_map={'Somatic_training_data': 'star', 'Ssrep_training_data': 'circle'},
hover_data={
'Sample': True,
'Chrom': True,
'Pos': True,
'REF': True,
'ALT': True,
'QUAL': True,
'Original filter': True,
'DP': True,
'VF': True,
'TP': True,
'Mutation_Type': True,
'MMQ_dif': True,
'MBQ_diff': True,
'Data_origin': True,
'Number of REF reads': True,
'Number of ALT reads': True,
'New filter': True,
}
)
# Add the subset (False Positives) to the second plot
fig2.add_trace(px.scatter(
data_frame=Detected_False_positive_MMQ,
x='VF',
y='MMQ_dif',
color_discrete_sequence=['black'], # Color the dots black
symbol_sequence=['circle'], # Use small dots
hover_data={
'Sample': True,
'Chrom': True,
'Pos': True,
'REF': True,
'ALT': True,
'QUAL': True,
'Original filter': True,
'DP': True,
'VF': True,
'TP': True,
'Mutation_Type': True,
'MMQ_dif': True,
'MBQ_diff': True,
'Data_origin': True,
'Number of REF reads': True,
'Number of ALT reads': True,
'New filter': True,
},
size_max=1
).update_traces(marker=dict(size=5, opacity=0.8), name='False Positives').data[0])
# Create the 3D plot: Variant Frequency vs. Difference in MBQ and MMQ
fig3 = px.scatter_3d(
data_frame=filtered_data_original,
x='VF',
y='MBQ_diff',
z='MMQ_dif',
color='TP',
symbol='Data_origin',
title="3D Plot: Variant Frequency vs. Difference in MBQ and MMQ",
labels={'VF': 'Variant Frequency (VF)', 'MBQ_diff': 'Difference in MBQ (MBQ_diff)', 'MMQ_dif': 'Difference in MMQ (MMQ_dif)'},
color_discrete_map={'TP': 'green', 'FP': 'red'},
symbol_map={'Somatic_training_data': 'star', 'Ssrep_training_data': 'circle'},
hover_data={
'Sample': True,
'Chrom': True,
'Pos': True,
'REF': True,
'ALT': True,
'QUAL': True,
'Original filter': True,
'DP': True,
'VF': True,
'TP': True,
'Mutation_Type': True,
'MMQ_dif': True,
'MBQ_diff': True,
'Data_origin': True,
'Number of REF reads': True,
'Number of ALT reads': True,
'New filter': True,
}
)
# Reduce the size of the dots in the main 3D plot
fig3.update_traces(marker=dict(size=3)) # Set the marker size to 3
import plotly.graph_objs as go
# Define the x, y, and z range
x_range = [min(filtered_data_original['VF']), max(filtered_data_original['VF'])]
y_range = [min(filtered_data_original['MBQ_diff']), max(filtered_data_original['MBQ_diff'])]
z_range = [min(filtered_data_original['MMQ_dif']), max(filtered_data_original['MMQ_dif'])]
# Plane at MBQ_Diff = 8.03 (parallel to the XZ plane)
plane1 = go.Mesh3d(
x=[x_range[0], x_range[1], x_range[1], x_range[0]], # 4 corners in x
y=[8.03, 8.03, 8.03, 8.03], # Constant y for the plane
z=[z_range[0], z_range[0], z_range[1], z_range[1]], # 4 corners in z
opacity=0.5,
color='red',
name='Plane MBQ_Diff 8.03'
)
# Plane at MMQ_Diff = 4.58 (parallel to the XY plane)
plane2 = go.Mesh3d(
x=[x_range[0], x_range[1], x_range[1], x_range[0]], # 4 corners in x
y=[y_range[0], y_range[0], y_range[1], y_range[1]], # 4 corners in y
z=[4.58, 4.58, 4.58, 4.58], # Constant z for the plane
opacity=0.5,
color='red',
name='Plane MMQ_Diff 4.58'
)
# Add the planes to the 3D figure
fig3.add_trace(plane1)
fig3.add_trace(plane2)
# Save all plots in the same HTML file
file_path = "combined_plots_with_3d_and_planes.html"
with open(file_path, "w") as f:
f.write(pio.to_html(fig1, full_html=False)) # First plot without full HTML
f.write(pio.to_html(fig2, full_html=False)) # Second plot without full HTML
f.write(pio.to_html(fig3, full_html=True)) # Third plot with full HTML to close the document
</code></pre>
<p>Why the first plane is not shown??</p>
<p>EDIT:</p>
<p>This is the 3D plot
<a href="https://i.sstatic.net/53iTx0AH.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/53iTx0AH.png" alt="enter image description here" /></a>
The red one is fig3 and the one I have painted is the missing plane I am not able to plot.</p>
|
<python><3d><plotly>
|
2024-08-15 14:49:25
| 0
| 1,393
|
Manolo Dominguez Becerra
|
78,875,567
| 19,838,568
|
Using default_namespace argument of ElementTree.tostring throws error
|
<p>I want to use ElementTree to modify an XML-document and to keep it comparable, I want to have the same namespace-prefixes in the new file as in the old file.</p>
<p>However, the <code>default_namespace=</code> argument of <code>ET.tostring</code> and <code>ET.write</code> causes errors with even simple documents.</p>
<p>Here is an example:</p>
<p>Example <code>test.xml</code> file:</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0"?>
<test xmlns="http://www.example.com/blabla/">
<item name="first" />
</test>
</code></pre>
<p>Test:</p>
<pre><code>Python 3.11.5 (tags/v3.11.5:cce6ba9, Aug 24 2023, 14:38:34) [MSC v.1936 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import xml.etree.ElementTree as ET
>>> xml = ET.parse("test.xml")
>>> ET.tostring(xml, default_namespace="http://www.example.com/blabla/")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python311\Lib\xml\etree\ElementTree.py", line 1098, in tostring
ElementTree(element).write(stream, encoding,
File "C:\Python311\Lib\xml\etree\ElementTree.py", line 741, in write
qnames, namespaces = _namespaces(self._root, default_namespace)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python311\Lib\xml\etree\ElementTree.py", line 856, in _namespaces
add_qname(key)
File "C:\Python311\Lib\xml\etree\ElementTree.py", line 833, in add_qname
raise ValueError(
ValueError: cannot use non-qualified names with default_namespace option
</code></pre>
<p>Is there any way to write the XML-File the way it is shown?</p>
|
<python><xml><elementtree>
|
2024-08-15 14:27:44
| 1
| 2,406
|
treuss
|
78,875,554
| 1,384,464
|
Configuring Django and MinIO using HTTPS on same server
|
<p>I have set up MinIO as my Django app object storage and integrate the functionality of this module on my the same server. I followed the instruction in <code>django-minio-backend</code>, but I got the below error.</p>
<pre><code>urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='subdomain.domain.org', port=9000): Max retries exceeded with url: /django-backend-dev-public (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1006)')))
</code></pre>
<p>A few contextual issues for the setup environment:</p>
<ol>
<li><p>The server runs <code>Ubuntu</code> 22.04 LTS operating system. the <code>MinIO</code> version is 2024-08-03T04-33-23Z. The <code>Django</code> version is 5.0.6</p>
</li>
<li><p>The MinIO setup worked perfectly when I had set it up to use unsecured connections (http), and Django running was running on the server unsecured. The Django web app could be able to upload files and images to MinIO server without any issue.</p>
</li>
<li><p>The error started when I updated the MinIO setup to work using secured connections only. On the WebUI, the server loads using https perfectly (i.e. I can log onto the console using <a href="https://subdomain.domain.org:9000" rel="nofollow noreferrer">https://subdomain.domain.org:9000</a>)</p>
</li>
<li><p>The secure setup is done through linking the MinIO to the SSL certificate folder on the server (/opt/minio/certs) that contains both the <code>public.crt</code> and <code>private.key</code></p>
</li>
</ol>
<p>The relevant lines for MinIO setup for my Django web-app in my settings.py are as follows:</p>
<pre><code>ALLOWED_HOSTS = [
'localhost',
'127.0.0.1',
'subdomain.domain.org'
]
CSRF_TRUSTED_ORIGINS = [
'https://subdomain.domain.org',
'https://127.0.0.1',
'https://localhost'
]
CSRF_ALLOWED_ORIGINS = ["https://subdomain.domain.org", "https://localhost"]
CORS_ORIGINS_WHITELIST = ["https://subdomain.domain.org", "https://localhost"]
INTERNAL_IPS = ['127.0.0.1', 'localhost', 'subdomain.domain.org']
MINIO_CONSISTENCY_CHECK_ON_START = True
MINIO_ENDPOINT = 'subdomain.domain.org:9000'
MINIO_EXTERNAL_ENDPOINT = 'subdomain.domain.org:9000'
MINIO_EXTERNAL_ENDPOINT_USE_HTTPS = True
MINIO_REGION = 'eu-west-1' # Default is set to None, current is Ireland
MINIO_ACCESS_KEY = 'XXXXXX'
MINIO_SECRET_KEY = 'YYYYY'
MINIO_USE_HTTPS = True
MINIO_URL_EXPIRY_HOURS = timedelta(
days=1) # Default is 7 days (longest) if not defined
MINIO_PRIVATE_BUCKETS = ['django-backend-dev-private', ]
MINIO_PUBLIC_BUCKETS = ['django-backend-dev-public', ]
MINIO_POLICY_HOOKS: List[Tuple[str, dict]] = []
MINIO_MEDIA_FILES_BUCKET = 'bridge-media-files-bucket'
MINIO_PRIVATE_BUCKETS.append(MINIO_MEDIA_FILES_BUCKET)
MINIO_STATIC_FILES_BUCKET = 'bridge-static-files-bucket'
MINIO_PRIVATE_BUCKETS.append(MINIO_STATIC_FILES_BUCKET)
MINIO_BUCKET_CHECK_ON_SAVE = True
# SSL
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 31536000 # 1 year
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
</code></pre>
<p>Might anyone have an idea why the secure configuration is throwing the error <code>urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='subdomain.domain.org', port=9000): Max retries exceeded with url: /django-backend-dev-public (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1006)')))</code></p>
|
<python><django><ubuntu><ssl><minio>
|
2024-08-15 14:24:41
| 1
| 1,033
|
Timothy Tuti
|
78,875,297
| 4,451,315
|
"horizontal sum" in DuckDB?
|
<p>In Polars I can do:</p>
<pre class="lang-py prettyprint-override"><code>import polars as pl
df = pl.DataFrame({'a': [1,2,3], 'b': [4, 5, 6]})
df.select(pl.sum_horizontal('a', 'b'))
shape: (3, 1)
┌─────┐
│ a │
│ --- │
│ i64 │
╞═════╡
│ 5 │
│ 7 │
│ 9 │
└─────┘
</code></pre>
<p>Is there a way to do this with DuckDB?</p>
|
<python><python-polars><duckdb>
|
2024-08-15 13:23:35
| 2
| 11,062
|
ignoring_gravity
|
78,875,237
| 4,520,520
|
Disable Django admin buttons after click
|
<p>Is there any easy way in Django change forms to disable buttons after submit. I want to prevent users from submitting the form twice at the same instant!</p>
|
<python><python-3.x><django><django-forms>
|
2024-08-15 13:04:23
| 3
| 2,218
|
mohammad
|
78,875,181
| 9,897,331
|
How to optimise parallelisation of nested numba loops
|
<p>I'm having issues figuring out how to optimise the parallelisation of nested loops with numba. As a basic example I've written a 2D convolution algorithm which relies on multiple nested loops. Obviously there are better options for calculating a 2D convolution, this is just for illustration. As you can see in the code below, I've written three versions of this algorithm, all of which are identical except for the loop implementation:</p>
<ol>
<li>convolve_numba_0p: Every loop is using the standard Python range function</li>
<li>convolve_numba_2p: Only the image height and width use numba's prange function</li>
<li>convolve_numba_allp: Every loop uses numba's prange function</li>
</ol>
<pre><code>import numba as nb
import numpy as np
import time
@nb.njit(parallel=True)
def convolve_numba_0p(image, kernel, out):
for img_b in range(image.shape[0]): # batch
for k_c in range(kernel.shape[0]): # kernel channel
for img_c in range(image.shape[1]): # image channel
for out_i in range(out.shape[2]): # image height
for out_j in range(out.shape[3]): # image width
for k_i in range(kernel.shape[1]): # kernel height
for k_j in range(kernel.shape[2]): # kernel width
out[img_b, k_c, out_i, out_j] += (
image[img_b, img_c, out_i + k_i, out_j + k_j] * kernel[k_c, k_i, k_j]
)
return out
@nb.njit(parallel=True)
def convolve_numba_2p(image, kernel, out):
for img_b in range(image.shape[0]): # batch
for k_c in range(kernel.shape[0]): # kernel channel
for img_c in range(image.shape[1]): # image channel
for out_i in nb.prange(out.shape[2]): # image height
for out_j in nb.prange(out.shape[3]): # image width
for k_i in range(kernel.shape[1]): # kernel height
for k_j in range(kernel.shape[2]): # kernel width
out[img_b, k_c, out_i, out_j] += (
image[img_b, img_c, out_i + k_i, out_j + k_j] * kernel[k_c, k_i, k_j]
)
return out
@nb.njit(parallel=True)
def convolve_numba_allp(image, kernel, out):
for img_b in nb.prange(image.shape[0]): # batch
for k_c in nb.prange(kernel.shape[0]): # kernel channel
for img_c in range(image.shape[1]): # image channel
for out_i in nb.prange(out.shape[2]): # image height
for out_j in nb.prange(out.shape[3]): # image width
for k_i in nb.prange(kernel.shape[1]): # kernel height
for k_j in nb.prange(kernel.shape[2]): # kernel width
out[img_b, k_c, out_i, out_j] += (
image[img_b, img_c, out_i + k_i, out_j + k_j] * kernel[k_c, k_i, k_j]
)
return out
if __name__ == "__main__":
# Prepare variables
shape_image = (1, 3, 10000, 10000)
image = np.random.randint(0, 65535, shape_image).astype(np.float32)
kernel = np.random.rand(2, 3, 3)
kernel -= np.mean(kernel, axis=(1, 2))[:, None, None]
padding = kernel.shape[0] // 2
image_padded = np.pad(image, ((0, 0), (0, 0), (padding, padding), (padding, padding)))
# Precompile functions
_ = convolve_numba_0p(image_padded, kernel, out=np.zeros(shape_image))
_ = convolve_numba_2p(image_padded, kernel, out=np.zeros(shape_image))
_ = convolve_numba_allp(image_padded, kernel, out=np.zeros(shape_image))
# Time functions
start = time.time()
out_numba_0p = convolve_numba_0p(image_padded, kernel, out=np.zeros(shape_image))
print(f"Numba 0p: {time.time()-start}")
start = time.time()
out_numba_2p = convolve_numba_2p(image_padded, kernel, out=np.zeros(shape_image))
print(f"Numba 2p: {time.time()-start}")
start = time.time()
out_numba_allp = convolve_numba_allp(image_padded, kernel, out=np.zeros(shape_image))
print(f"Numba allp: {time.time()-start}")
</code></pre>
<p>Times using different number of CPU threads:</p>
<pre><code># 1 thread
Numba 0p: 9.103097200393677
Numba 2p: 7.535120010375977
Numba allp: 6.83448052406311
# 2 threads
Numba 0p: 9.253679990768433
Numba 2p: 4.163503646850586
Numba allp: 6.80088472366333
# 10 threads
Numba 0p: 9.133044004440308
Numba 2p: 0.9814767837524414
Numba allp: 6.881485939025879
# 50 Threads
Numba 0p: 9.317977905273438
Numba 2p: 0.5669231414794922
Numba allp: 6.787745952606201
</code></pre>
<p>As you can see, using a couple of prange loops improves performance significantly, but using it for all loops results in a performance drop so dramatic that it's almost as slow as using none. In fact, using all prange seems to always result in the same performance, regardless of the number of threads available. I'm aware that more workers could result in more overhead which could limit the benefits of more paralellisation, but considering that every operation is independent and that the number of operations is orders of magnitude higher than the number of threads, I would've expected at worst no significant difference with 2p.</p>
<p>Also, to reiterate: I'm very aware that relying only on nested loops is often not the best approach. The algorithm used as example here is not the point and it is specifically meant to represent situations where nested loops is the only option.</p>
<p>My questions are:</p>
<p>Q1) What could be causing such a drop in performance for a higher number of nested prange loops?</p>
<p>Q2) Is there something wrong in my implementation of numba here? I'm not talking about the algorithm, but the implementation itself, e.g. wrong parameters.</p>
<p>Q3) Is there a better method to optimise the paralellisation of nested loops?</p>
|
<python><for-loop><parallel-processing><numba>
|
2024-08-15 12:52:59
| 1
| 365
|
Felipe Moser
|
78,875,128
| 9,343,043
|
How to merge dictionary of dataframes and make key values a column in merged dataframe
|
<p>I have a dictionary of about 600 dataframes for connectome metrics for those 600 participants. I'm making a dummy dictionary though for conciseness. The dataframes all have 1 row. Ignore the fact that the actual meaning of "mean" as the column names are not what is of the row samples I give below, they're just the column names of all the dataframes I want to merge. Each of the keys are unique.</p>
<p>Two example dataframes would look like this:</p>
<pre><code>Key = "Sonic"
Value_df =
mean median stdev min max count
1 3 7 9 22 11
Key = "Tails"
Value_df =
mean median stdev min max count
3 5 11 22 33 14
</code></pre>
<p>where...</p>
<p><code>{"Sonic":Dataframe, "Tails":Dataframe}</code></p>
<p>How do I merge the dictionary's dataframe and make the key values its own column in the final dataframe?</p>
<pre><code>Subject mean median stdev min max count
Sonic 1 3 7 9 22 11
Tails 3 5 11 22 33 14
</code></pre>
<p>I've tried <code>from_dict</code> and I didn't have any luck.</p>
|
<python><pandas><dataframe><dictionary>
|
2024-08-15 12:38:55
| 1
| 871
|
florence-y
|
78,875,000
| 4,265,257
|
How to highlight traces on legend hover events
|
<p>I'm plotting lines from variable data, the items can sometimes have identical data points so need a way to see which lines are stacked. I'd like to implement something similar to the mplcursors highlight feature which highlights figures as you hover them in the legend.</p>
<p>In Seaborn using dodge on a catplot works quite well to show that you're not looking at a single line. I ended up using Plotly because it has has some nice defaults like hover annotations and show/hide figures by clicking the corresponding legend item. I've tried mplcursors with Seaborn to add hover annotations but <a href="https://github.com/anntzer/mplcursors/issues/80https://" rel="nofollow noreferrer">it seems buggy</a>.</p>
<p>The bottom line in the following screenshot has all of the items in the legend stacked except the other two. I can click through the legend until I've removed the top two to know which ones are stacked but it's not very efficient.</p>
<p><a href="https://i.sstatic.net/YFUSkbBx.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/YFUSkbBx.png" alt="Plotly plot using variable data" /></a></p>
<p>The code currently looks like this:</p>
<pre><code> df = pd.DataFrame(pandas_dict_for_dataframe)
dfm = df.melt('Date', var_name='Item', value_name='Price')
fig = px.line(dfm, x="Date", y="Price", color='Item', markers=True)
fig.update_xaxes(type='category')
fig.show()
</code></pre>
|
<python><plotly>
|
2024-08-15 12:06:45
| 0
| 349
|
Arno
|
78,874,855
| 736,662
|
how to represent null and true i json payload Python
|
<p>I have a payload in my request against an endpoint having values null and true. In Pycharm I get red-dotted line below the two respectively. How can I "define null and true inside my json payloads setmethod in Python?</p>
<pre><code>def setpayload_set():
myjson = {
"hpsId": 10034,
"powerPlants": null,
"units": [{"componentId": 78111,
"timeSeries": [{"name": "ts.start_bids_allowed",
"dtssId": "", "tsv": {"pfx": true,
"data": [[1723647600,
1]]}}]}]
}
return myjson
</code></pre>
|
<python><json>
|
2024-08-15 11:21:15
| 1
| 1,003
|
Magnus Jensen
|
78,874,845
| 5,618,856
|
Pandas read_sql with SQLAlchemy from Oracle Database with many parameters
|
<p>I have a working setup to read sql data into a pandas dataframe:</p>
<pre class="lang-py prettyprint-override"><code>connect_string = f"DSN={config.DB};UID={credentials['UID']};PWD={credentials['pwd']};DBQ={config.DB_server};DBA=W;APA=T;EXC=F;FEN=T;QTO=F;FRC=10;FDL=10;LOB=T;BTD=F;BNF=F;TABLE={config.table}"
select_string = f"SELECT * FROM {config.table} WHERE Foo LIKE '{config.bar}%'"
connection = pyodbc.connect(connect_string)
data = pd.read_sql(select_string, connection)
</code></pre>
<p>but I get the complaint
<code>UserWarning: pandas only supports SQLAlchemy connectable...</code>
So I tried to use SQLAlchemy with <code>oracledb</code>. But how can I pass the connection parameters? I tried as <a href="https://python-oracledb.readthedocs.io/en/latest/user_guide/connection_handling.html#using-the-connectparams-builder-class" rel="nofollow noreferrer">explained in the docs</a></p>
<pre><code>cp = oracledb.ConnectParams(dba="W", apa="T", exc="F", fen="T", qto="F", frc=10, fdl=10, lob="T", btd="F", bnf="F", table=config.table)
</code></pre>
<p>but this gives the error <code>TypeError: ConnectParams.__init__() got an unexpected keyword argument 'dba'</code></p>
|
<python><pandas><oracle-database><sqlalchemy><python-oracledb>
|
2024-08-15 11:18:20
| 2
| 603
|
Fred
|
78,874,712
| 1,860,314
|
What could even be an error when loading a pickled file in Python?
|
<p>The pickled file is <a href="https://github.com/sjy1203/GAMENet/blob/master/data/voc_final.pkl" rel="nofollow noreferrer">voc_final.pkl</a>, in the source code used in the paper <a href="https://arxiv.org/abs/1809.01852" rel="nofollow noreferrer">GAMENet</a>.</p>
<p>I tried to load it:</p>
<pre><code>import dill
voc = dill.load(open("voc_final.pkl", 'rb'))
</code></pre>
<p>But got the error:</p>
<pre><code>TypeError: code expected at least 16 arguments, got 15
</code></pre>
<p>That's weird because even if the pickled file contains an unknown class in another library, which is not available in my computer. The loading of the pickled file should be fine. I tested this scenario as:</p>
<p>Writing pickle:</p>
<pre><code>import dill
class XYZ():
def __init__(self, i):
self.x = i
self.y = {}
def do_something(k):
return k + 10
p = XYZ(10)
with open('test.pkl','wb') as output:
dill.dump(obj={"aaa": p}, file=output)
</code></pre>
<p>Loading pickle <strong>in another Python session</strong>:</p>
<pre><code>import dill
with open('test.pkl','rb') as input:
kkk = dill.load(input)
</code></pre>
<p>This works just <strong>fine</strong>!</p>
<p>I wonder what could be possibly an error when loading a pickled file? Of course, not trivial error like "file not found", "file being used", etc.</p>
<p>Maybe because of different Python version as <a href="https://www.digitalocean.com/community/tutorials/python-pickle-example#important-notes-on-python-pickle" rel="nofollow noreferrer">here</a> said: "<em>There is also no guarantee of compatibility between different versions of Python because not every Python data structure can be serialized by the module.</em>"?</p>
<h3>Reproducibility</h3>
<ul>
<li>Windows 10 x64</li>
<li>Python 3.11.7</li>
</ul>
|
<python><serialization><deserialization><pickle><dill>
|
2024-08-15 10:43:09
| 1
| 1,077
|
JoyfulPanda
|
78,874,684
| 16,869,946
|
Python scipy quad and nqaud giving different answers
|
<p>I am not sure if this is more suitable for math stackexchange or stack overflow, but since the mathematical proofs look alright to me, I suspect its the code that's the issue and hence I will post it here:</p>
<p><a href="https://i.sstatic.net/19KiGQj3.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/19KiGQj3.png" alt="enter image description here" /></a></p>
<p>The first formula (formula 1) is straight by definition:
<a href="https://i.sstatic.net/eAwuASWv.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/eAwuASWv.png" alt="enter image description here" /></a></p>
<p>and here's my code for formula 1:</p>
<pre><code>import scipy.integrate as integrate
from scipy.integrate import nquad
from scipy.stats import norm
import math
def normalcdf(x):
return (1+math.erf(x/math.sqrt(2)))/2
def normalpdf(x):
return math.exp(-x*x/2)/math.sqrt(2*math.pi)
def integrand12345(x1,x2,x3,x4,x5,theta1,theta2,theta3,theta4,theta5):
return normalpdf(x1 - theta1) * normalpdf(x2 - theta2) * normalpdf(x3 - theta3) * normalpdf(x4 - theta4) * normalpdf(x5 - theta5)
def range_x1(theta1,theta2,theta3,theta4,theta5):
return [-np.inf, np.inf]
def range_x2(x1,theta1,theta2,theta3,theta4,theta5):
return [x1, np.inf]
def range_x3(x2,x1,theta1,theta2,theta3,theta4,theta5):
return [x2, np.inf]
def range_x4(x3,x2,x1,theta1,theta2,theta3,theta4,theta5):
return [x3, np.inf]
def range_x5(x4,x3,x2,x1,theta1,theta2,theta3,theta4,theta5):
return [x4, np.inf]
def pi_12345(theta1,theta2,theta3,theta4,theta5):
return (nquad(integrand12345, [range_x5, range_x4, range_x3, range_x2, range_x1], args=(theta1,theta2,theta3,theta4,theta5)))[0]
</code></pre>
<p>The second formula (formula 2) is using double integration:
<a href="https://i.sstatic.net/WibTWIBw.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/WibTWIBw.png" alt="enter image description here" /></a>
and here is the code for formula 2:</p>
<pre><code>def integrandforpi_12(x1, x2, t1, t2, *theta):
prod = 1
for ti in theta:
prod = prod * (1 - normalcdf(x2 - ti))
return prod * normalpdf(x1 - t1) * normalpdf(x2 - t2)
def range_x1(t1, t2, *theta):
return [-np.inf, np.inf]
def range_x2(x1, t1, t2, *theta):
return [x1, np.inf]
def pi_12(t1, t2, *theta):
return (nquad(integrandforpi_12, [range_x2, range_x1], args=(t1, t2, *theta)))[0]
</code></pre>
<p>My third formula (formula 3) is based on Bayes' theorem:
<a href="https://i.sstatic.net/JLz6332C.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/JLz6332C.png" alt="enter image description here" /></a></p>
<p>and my code for formula 3 is:</p>
<pre><code>def integrandforpi_i(xi, ti, *theta):
prod = 1
for t in theta:
prod = prod * (1 - normalcdf(xi - t))
return prod * normalpdf(xi - ti)
def pi_i(ti, *theta):
return integrate.quad(integrandforpi_i, -np.inf, np.inf, args=(ti, *theta))[0]
</code></pre>
<p>So pi_i computes the probability that X_i is the smallest among the theta_i’s.</p>
<p>However, when I run my code using the 3 different formulas, they all give different answers and I have no idea why. I am not sure if there is a flaw in my derivation of the formula or if there's a mistake in my code. Any help would be appreciated.</p>
<p>Here is an example:</p>
<pre><code>t1,t2,t3,t4,t5 = 0.83720022,0.61704171,1.21121701,0,1.52334078
p12345 = pi_12345(t1,t2,t3,t4,t5)
p12354 = pi_12345(t1,t2,t3,t5,t4)
p12435 = pi_12345(t1,t2,t4,t3,t5)
p12453 = pi_12345(t1,t2,t4,t5,t3)
p12534 = pi_12345(t1,t2,t5,t3,t4)
p12543 = pi_12345(t1,t2,t5,t4,t3)
print('p12345=',p12345)
print('p12354=',p12354)
print('p12435=',p12435)
print('p12453=',p12453)
print('p12534=',p12534)
print('p12543=',p12543)
print('formula 1 gives', p12345+p12354+p12435+p12453+p12534+p12543)
print('formula 2 gives', pi_12(t1,t2,t3,t4,t5))
print('formula 3 gives', pi_i(t2,t3,t4,t5) * pi_i(t1,t2,t3,t4,t5))
</code></pre>
<p>and the output is</p>
<pre><code>p12345= 0.0027679276698449086
p12354= 0.008209750140618218
p12435= 0.0016182955786153714
p12453= 0.001921206801273682
p12534= 0.009675713474375739
p12543= 0.003904872716765966
formula 1 gives 0.028097766381493885
formula 2 gives 0.21897431741874426
formula 3 gives 0.0418669679120933
</code></pre>
<p>Remark: Formula 1 is extremely slow, it takes about 3 hours to run on my poor old laptop. Formula 2 and 3 are instant.</p>
|
<python><scipy><probability><scipy.stats><quad>
|
2024-08-15 10:33:15
| 2
| 592
|
Ishigami
|
78,874,506
| 5,758,423
|
How can I avoid interface repetition in Python function signatures and docstrings?
|
<p>I'm looking for a standard, lightweight (preferably built-in) way to handle the problem of <strong>interface repetition</strong>—where the same parameters (with annotations, defaults, and docs) are repeated across multiple functions that share common functionality. Is there a way to centralize the parameter definitions and docs without manually duplicating them?</p>
<p>Here's an example to illustrate the issue. The code is kept short and simple to avoid verbosity, and yes, in this particular case, a decorator could handle it. However, please focus on the <strong>repetition of signature elements and documentation</strong> as the real problem, not the specific logic of the functions.</p>
<h3>Example Code:</h3>
<pre class="lang-py prettyprint-override"><code># Core function f
def f(a: str, b=1) -> str:
"""
Repeats the string `a` `b` times.
Args:
a (str): The string to be repeated.
b (int, optional): Number of repetitions. Defaults to 1.
...
"""
return a * b
# Higher-level function g
def g(x, *, a: str, b=1) -> str:
"""
Calls `f` to repeat `a`, appends `x` to the result.
Args:
x: Value to append to the repeated string.
a (str): The string to be repeated.
b (int, optional): Number of repetitions. Defaults to 1.
...
"""
result = f(a, b)
return result + str(x)
# Higher-level function h (different from g)
def h(y, *, a: str, b=2) -> int:
"""
Calls `f` to repeat `a`, appends `y`, and returns the length of the result.
Args:
y: Value to append to the repeated string.
a (str): The string to be repeated.
b (int, optional): Number of repetitions. Defaults to 2.
...
"""
result = f(a, b) + str(y)
return len(result)
</code></pre>
<h3>The Problem</h3>
<p>In this scenario, I find myself repeating parameter definitions (<code>a</code>, <code>b</code>) and their types and defaults across multiple functions. Similarly, the documentation for each parameter is repeated in each function's docstring. This leads to:</p>
<ul>
<li><strong>Visual noise</strong>: Repetition clutters the code, making it harder to maintain.</li>
<li><strong>DRY violation</strong>: If I need to change the default of <code>b</code> or update the docs, I must do it in multiple places.</li>
<li><strong>Harder maintenance</strong>: Changes in one place can lead to inconsistencies if I forget to update all the functions.</li>
</ul>
<h3>Mitigation Approaches</h3>
<p>Some solutions I've considered (e.g. <a href="https://i2mint.github.io/i2/module_docs/i2/signatures.html" rel="nofollow noreferrer">i2.signatures</a>, which we developed with my previous team, to address this issue, and more) include:</p>
<ul>
<li><strong>Using decorators</strong> to centralize parameter handling. For example, a decorator could handle default values and inject common parameters across functions.</li>
<li><strong>Using <code>inspect</code></strong> to dynamically copy the signature from one function to another, reducing duplication.</li>
</ul>
<p>However, these approaches still add complexity and don’t seem like an ideal solution for every case. They also don't fully address the problem of duplicating docs.</p>
<h3>What I'm Looking For</h3>
<p>Is there a <strong>standard or lightweight solution</strong> (preferably built-in) that addresses this <strong>interface repetition</strong> problem in Python? Ideally, it would avoid repetition of both parameter signatures and docstrings, while keeping the code as simple and readable as possible.</p>
<p>Any suggestions or best practices are welcome!</p>
|
<python><dry>
|
2024-08-15 09:41:26
| 1
| 2,432
|
thorwhalen
|
78,874,499
| 3,972,291
|
Influxdb: store data into influxdb from oracle database using apache airflow
|
<p>I am using Apache airflow for storing data in influxdb from oracle database. I need to store all data from oracle database into influxdb. But it insert last row of data only each company_id. Other data not insert. Here is oracle data set:</p>
<p><a href="https://i.sstatic.net/O99n2Q71.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/O99n2Q71.jpg" alt="enter image description here" /></a></p>
<p>Here is the python code :</p>
<pre><code> from airflow import DAG
from airflow.operators.python import PythonOperator
from airflow.providers.influxdb.hooks.influxdb import InfluxDBHook
from airflow.providers.oracle.hooks.oracle import OracleHook
from influxdb_client.client.write_api import SYNCHRONOUS
from datetime import datetime,timedelta,timezone
import influxdb_client
import traceback
bucket = "myBucket"
org = "city"
token = "LsOE3PsZjive2ENtJnM3Pv2UmxcygaLymDPpR2YJO0XBZa0eA=="
url = "http://influxdb:8086"
def get_data_from_oracle(**kwargs):
oracle_hook = OracleHook(oracle_conn_id='oracle_default')
sql = """
SELECT COMPANY_ID,
CREDIT_AMOUNT,
CREDIT_ACCOUNT_NUMBER,
DEBIT_ACCOUNT_NUMBER
FROM gtt_transaction
WHERE COMPANY_ID IN (969, 116)
AND TRUNC (INSERT_DATE) = '15-AUG-2024'
AND TRX_REFERENCE IN ('15082445361298', '15082439504163')
"""
data = oracle_hook.get_pandas_df(sql)
return data
def transform_oracle_data(ti):
data = ti.xcom_pull(task_ids='getDataFromOracle_task')
return data
current_time = datetime.now(timezone.utc)
def insert_data_into_influxdb(ti):
data = ti.xcom_pull(task_ids='transanformOracleData_task')
print("insert_data_into_influxdb--data-",data)
if data is None:
print("No data received from transform_oracle_data_task")
return # Exit gracefully if no data
try:
client = influxdb_client.InfluxDBClient(url=url, token=token, org=org)
write_api = client.write_api(write_options=SYNCHRONOUS)
points = []
for count, row in enumerate(data.to_records(index=False)):
timestamp = current_time + timedelta(microseconds=count)
print("timestamp--",timestamp)
point = influxdb_client.Point("oracle_transactions_3") \
.tag("company_id", row.COMPANY_ID) \
.field("credit_amount", float(row.CREDIT_AMOUNT)) \
.field("credit_account_number", str(row.CREDIT_ACCOUNT_NUMBER)) \
.field("debit_account_number", str(row.DEBIT_ACCOUNT_NUMBER)) \
.time(timestamp, influxdb_client.WritePrecision.NS)
points.append(point)
write_api.write(bucket=bucket, org=org, record=points)
except Exception as e:
print(f"Error: {traceback.format_exc()}")
# DAG definition
with DAG(
dag_id='oracle_to_influxdb_line_protocol',
start_date=datetime(2024, 8, 13),
schedule_interval='*/50 * * * *',
catchup=False,
) as dag:
get_data_from_oracle_task = PythonOperator(
task_id='getDataFromOracle_task',
python_callable=get_data_from_oracle,
)
transform_oracle_data_task = PythonOperator(
task_id='transanformOracleData_task',
python_callable=transform_oracle_data,
)
insert_data_into_influxdb_task = PythonOperator(
task_id='insertIntoFluxDb_task',
python_callable=insert_data_into_influxdb,
)
# Task dependencies
get_data_from_oracle_task >> transform_oracle_data_task >> insert_data_into_influxdb_task
</code></pre>
<p>What is reason for inserting only one row?
I want to store all data found in query.</p>
<p>what is the wrong of my code?</p>
<p>Please help me...</p>
|
<python><airflow><influxdb>
|
2024-08-15 09:40:05
| 1
| 5,095
|
Enamul Haque
|
78,874,155
| 508,236
|
How to create a single CSV file with specified file name Spark in Databricks?
|
<p>I know how to use Spark in Databricks to create a CSV, but it always has lots of side effects.</p>
<p>For example, here is my code:</p>
<pre class="lang-py prettyprint-override"><code>file_path = “dbfs:/mnt/target_folder/file.csv”
df.write.mode("overwrite").csv(file_path, header=True)
</code></pre>
<p>Then what I got is</p>
<ul>
<li>A folder with name file.csv</li>
<li>In the folder there are addtional files called <code>_committed_xxxx</code>, <code>_started_xxxx</code>, <code>_SUCCESS</code></li>
<li>Multiple files with <code>part-xxxx</code></li>
</ul>
<p>What I want is only a <strong>SINGLE CSV file</strong> with the name <code>file.csv</code>, how can I achieve this?</p>
<p>I tried to use <code>pandas.to_csv</code> function, but it’s not working on Databricks notebook, the error is</p>
<blockquote>
<p>OSError: Cannot save file into a non-existent directory</p>
</blockquote>
|
<python><csv><apache-spark><databricks>
|
2024-08-15 08:00:20
| 1
| 15,698
|
hh54188
|
78,874,114
| 14,808,637
|
Visualizing multiple graphs in a single figure while conserving space and maintaining clarity
|
<p>I'm visualizing a graph using the given code, where each pair of nodes connected by a comma represents an edge, and the numeric value represents the intensity of that edge. Here is the code for a graph:</p>
<pre><code>import matplotlib.pyplot as plt
import networkx as nx
import os
import matplotlib.colors as mcolors
data = {
('A', 'B'): 0.71,
('M', 'B'): 0.67,
('N', 'B'): 0.64,
('A', 'O'): 0.62,
('O', 'B'): 0.60,
('N', 'O'): 0.53,
('M', 'O'): 0.46,
('A', 'N'): 0.18,
('M', 'N'): 0.11
}
G = nx.Graph()
for key, value in data.items():
G.add_edge(*key, weight=value)
fig, axe = plt.subplots()
pos = nx.spring_layout(G, seed=123456)
# Define the base color
base_color = (0, 0, 1) # Blue color
base_color = mcolors.to_rgb('tab:red')# Blue color
# Get the edge weights
weights = nx.get_edge_attributes(G, 'weight')
# Create a function to adjust the color intensity
def adjust_color_intensity(base_color, weight):
""" Adjust color intensity based on weight. """
return tuple(weight * x + (1 - weight) * 1 for x in base_color)
# Generate the edge colors based on weights
edge_colors = [adjust_color_intensity(base_color, weight) for weight in weights.values()]
rgb_color = (1,0,0)
nx.draw_networkx_nodes(G, pos, ax=axe, node_color='tab:blue')
nx.draw_networkx_edges(G, pos, ax=axe, edge_color=edge_colors)
nx.draw_networkx_labels(G, pos, font_size=12, ax=axe)
plt.show()
plt.clf()
plt.close(fig)
</code></pre>
<p>Now, I'd like to add more graphs to the image while ensuring that it doesn't take up too much space and that the edges, visualization, and node fonts remain clear. The graphs I want to add are:</p>
<pre><code>Graph2: ('ABC', 'ADC'): 0.53
Graph3: ('CDE', 'CFH'): 0.28
Graph4: ('GHI', 'GMI'): 0.20
Graph5: ('XYZ', 'XWZ'): 0.17
</code></pre>
<p>Can anyone help me with visualizing multiple graphs in a single figure?</p>
|
<python><matplotlib><networkx>
|
2024-08-15 07:46:21
| 2
| 774
|
Ahmad
|
78,873,745
| 14,808,637
|
Visualization of Weighted Graph with NetworkX and Matplotlib: Addressing Node Overlapping Issue
|
<p>I am visualizing a graph where each pair of nodes connected by a comma represents an edge, and the numeric value represents the intensity of that edge. Here is the code:</p>
<pre><code>import matplotlib.pyplot as plt
import networkx as nx
data = {
('A', 'B'): 0.71,
('M', 'B'): 0.67,
('N', 'B'): 0.64,
('A', 'O'): 0.62,
('O', 'B'): 0.60,
('N', 'O'): 0.53,
('M', 'O'): 0.46,
('A', 'N'): 0.18,
('M', 'N'): 0.11
}
G = nx.Graph()
for key, value in data.items():
G.add_edge(*key, weight=value)
fig, axe = plt.subplots()
pos = nx.spring_layout(G, seed=123456)
nx.draw_networkx_nodes(G, pos, ax=axe)
nx.draw_networkx_edges(G, pos, ax=axe)
nx.draw_networkx_labels(G, pos, font_size=12, ax=axe)
nx.draw_networkx_edge_labels(G, pos, nx.get_edge_attributes(G, "weight"), ax=axe)
</code></pre>
<p>However, I encountered the issue of overlapping nodes. I have attached the output image generated by the code for your reference.</p>
<p><a href="https://i.sstatic.net/657xgMtB.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/657xgMtB.png" alt="enter image description here" /></a></p>
<p>Is there any solution to handle this problem?</p>
|
<python><matplotlib><networkx>
|
2024-08-15 05:28:19
| 0
| 774
|
Ahmad
|
78,873,680
| 4,609,089
|
How to create a function call tool to analyse CSV in LLM Long-chain with all columns definition predefined
|
<p><em><strong>Context</strong></em></p>
<p>I would like to create an GPT Agent. This Agent should be able to fetch data from 3 predefined CSV files. Hence I would like to create 3 function tools for each CSV file.</p>
<p><em><strong>Expectation</strong></em></p>
<p>AI Agent should understand what does each CSV do exactly. And what are the columns and data exactly agent can get from each CSV file.</p>
<p>Because, I think providing the CSV structure and column definitions when creating the tool will make the LLM result much more efficient and accurate.</p>
<p><em><strong>Problem Statement</strong></em></p>
<p>How to properly define the CSV structure and column definitions?</p>
<p>The code is I tried is listed below.</p>
<pre><code>csv1_inspection_tool = StructuredTool.from_function(
func=get_first_n_rows,
name="InspectCSVFile",
description="Explore the contents and structure of a table document, displaying its column names and the first n rows, with n defaulting to 3.",
)
</code></pre>
<pre><code>import pandas as pd
def get_csv_filename(
filename: str
) -> str:
"""Get CSV file name"""
# Read the CSV file
csv_file = pd.read_csv(filename)
# Since there's no sheet name, we just return the filename
return f"The file name of the CSV is '{filename}'"
def get_column_names(filename: str) -> str:
"""Get all column names from a CSV file"""
# Read the CSV file
df = pd.read_csv(filename)
column_names = '\n'.join(df.columns.to_list())
result = f"The File '{filename}' has columns:\n\n{column_names}"
return result
def get_first_n_rows(
filename: str,
n: int = 3
) -> str:
"""Get CSV File First N Lines"""
result = get_csv_filename(filename) + "\n\n"
result += get_column_names(filename) + "\n\n"
df = pd.read_csv(filename)
n_lines = '\n'.join(
df.head(n).to_string(index=False, header=True).split('\n')
)
result += f"This file '{filename}' has first {n} lines of sample:\n\n{n_lines}"
return result
</code></pre>
|
<python><openai-api><langchain><large-language-model><gpt-4>
|
2024-08-15 04:55:11
| 0
| 833
|
John
|
78,873,598
| 143,397
|
How to wrap a PyDict in PyO3 with a constructor that takes a new parameter?
|
<p>I am using PyO3 (v0.22.2) / Rust to write something a little similar to <code>defaultdict</code>, but with an integer default rather than a callback:</p>
<pre><code>>>> from my_package.pyo3_ext import PyDefaultDict
>>> d = PyDefaultDict(42, a=1, b=2)
>>> d['a']
1
>>> d['z']
42
</code></pre>
<p>I am trying to subclass the built-in Python <code>dict</code> with <code>extends=PyDict</code>, as per examples:</p>
<pre class="lang-rust prettyprint-override"><code>use pyo3::prelude::*;
use pyo3::types::PyDict;
#[pyclass(extends=PyDict)]
pub struct PyDefaultDict {
x: i32,
}
#[pymethods]
impl PyDefaultDict {
#[new]
#[pyo3(signature = (x, *_args, **_kwargs))]
fn new(x: i32, _args: &Bound<'_, PyAny>, _kwargs: Option<&Bound<'_, PyAny>>) -> Self {
Self { x }
}
fn get_x(&self) -> i32 {
self.x
}
}
</code></pre>
<p>This compiles, but when I try to call the constructor in Python, I get the following error:</p>
<pre><code>>>> x = PyDefaultDict(42)
TypeError: 'int' object is not iterable
</code></pre>
<p>I am referring to the <a href="https://pyo3.rs/main/class#inheritance" rel="nofollow noreferrer">PyO3 user guide::Inheritance</a> section. This actually has an example of ensuring that <code>_args</code> and <code>_kwargs</code> are passed through to the base class, but it does not demonstrate how to provide a custom <code>__init__()</code> parameter via <code>new()</code>.</p>
<p>Note that even if I remove <code>x</code> from my struct, so that all I'm doing is accepting an <code>i32</code> parameter in <code>new()</code>, and not trying to assign it to anything, I still get the same error.</p>
<p>I also tried accepting a <code>PyAny</code> and then extracting to an <code>i32</code>:</p>
<pre class="lang-rust prettyprint-override"><code> fn new(x: &Bound<'_, PyAny>, _args: &Bound<'_, PyAny>, _kwargs: Option<&Bound<'_, PyAny>>) -> Self {
Self { _x: x.extract().unwrap() }
}
</code></pre>
<p>Alas, this gives me the same error.</p>
<p>What's the little piece of knowledge I am missing here, to help solve this?</p>
<hr />
<p>Note, the base example, without the new parameter <code>x</code>, works just like a normal <code>dict</code>, so I'm basing my work on this:</p>
<pre class="lang-rust prettyprint-override"><code>#[pyclass(extends=PyDict)]
pub struct PyDefaultDict {}
#[pymethods]
impl PyDefaultDict {
#[new]
#[pyo3(signature = (*_args, **_kwargs))]
fn new(_args: &Bound<'_, PyAny>, _kwargs: Option<&Bound<'_, PyAny>>) -> Self {
Self {}
}
}
</code></pre>
|
<python><inheritance><rust><python-extensions><pyo3>
|
2024-08-15 04:01:51
| 0
| 13,932
|
davidA
|
78,873,362
| 20,295,949
|
Optimize Python Web Scraping Script Using concurrent.futures to Reduce Execution Time
|
<p>I'm currently working on a web scraping script in Python that extracts table data from multiple pages of a website using urllib, BeautifulSoup, and pandas. The script is designed to handle content encoding like gzip and brotli, and it retries on certain HTTP errors such as 429 (Too Many Requests) with exponential backoff.</p>
<p>I've implemented concurrent processing with ProcessPoolExecutor to speed up the process. However, the script still takes a significant amount of time to run, around 395 seconds. I believe there is room for vast optimization.</p>
<p>Below is the full script I'm using:</p>
<pre><code>import urllib.request
from bs4 import BeautifulSoup
import pandas as pd
import gzip
import brotli
import io
import time
import traceback
from concurrent.futures import ProcessPoolExecutor, as_completed
import logging
# Setup logger
logger = logging.getLogger()
logger.setLevel(logging.INFO)
log_stream = io.StringIO()
handler = logging.StreamHandler(log_stream)
formatter = logging.Formatter('%(asctime)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
def get_page_content(url):
req = urllib.request.Request(url, headers={
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate, br',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1'
})
response = urllib.request.urlopen(req)
if response.info().get('Content-Encoding') == 'gzip':
buf = io.BytesIO(response.read())
data = gzip.GzipFile(fileobj=buf).read()
elif response.info().get('Content-Encoding') == 'br':
data = brotli.decompress(response.read())
else:
data = response.read()
return data
def extract_table_data(page_url, page_number):
try:
webpage = get_page_content(page_url)
soup = BeautifulSoup(webpage, 'html.parser')
div_element = soup.find('div', class_='tw-mb-6 lg:tw-mb-12')
if div_element:
html_table = div_element.find('table')
if html_table:
df = pd.read_html(io.StringIO(str(html_table)))[0]
df = df.loc[:, df.columns[1:-1]]
df['Page Number'] = page_number
return df
else:
logger.info(f"No table found in the specified div for URL: {page_url}")
else:
logger.info(f"Specified div element not found for URL: {page_url}")
except urllib.error.HTTPError as e:
if e.code == 404:
logger.info(f"HTTP Error 404 on page {page_number}. Stopping scraping.")
raise e
logger.error(f"HTTP Error on page {page_number}: {str(e)}")
traceback.print_exc()
except Exception as e:
logger.error(f"An error occurred for URL {page_url}: {str(e)}")
traceback.print_exc()
return None
def process_page(page):
logger.info(f"Starting to process page {page}")
try:
url = base_url + str(page)
logger.info(f"Fetching URL: {url}")
retries = 0
while retries < max_retries:
try:
df = extract_table_data(url, page)
if df is not None:
return df
else:
logger.info(f"No data found on page {page}, stopping.")
return None
except urllib.error.HTTPError as e:
if e.code == 404:
raise e
elif e.code == 429:
logger.warning(f"HTTP Error 429 on page {page}: Too Many Requests. Retrying after delay...")
retries += 1
time.sleep(retry_delay * retries)
else:
logger.info(f"HTTP Error on page {page}: {e.code}. Retrying...")
retries += 1
time.sleep(retry_delay)
except Exception as e:
logger.error(f"An error occurred on page {page}: {str(e)}. Retrying...")
traceback.print_exc()
retries += 1
time.sleep(retry_delay)
except Exception as e:
logger.error(f"Failed to process page {page}: {str(e)}")
traceback.print_exc()
logger.info(f"Finished processing page {page}")
return None
base_url = 'https://www.coingecko.com/en/coins/1/markets/spot?page='
all_data = pd.DataFrame()
start_page = 1
max_retries = 3
retry_delay = 5
max_consecutive_errors = 5
start_time = time.time()
with ProcessPoolExecutor(max_workers=2) as executor:
futures = {}
consecutive_errors = 0
current_page = start_page
while True:
try:
future = executor.submit(process_page, current_page)
futures[future] = current_page
current_page += 1
completed_futures = [future for future in as_completed(futures) if future.done()]
for future in completed_futures:
page = futures.pop(future)
try:
df = future.result()
if df is not None:
all_data = pd.concat([all_data, df], ignore_index=True)
consecutive_errors = 0
else:
consecutive_errors += 1
except urllib.error.HTTPError as e:
if e.code == 404:
logger.info("Reached a page that does not exist. Stopping.")
break
consecutive_errors += 1
except Exception as e:
logger.error(f"An error occurred while processing page {page}: {str(e)}")
consecutive_errors += 1
if consecutive_errors >= max_consecutive_errors:
logger.info(f"Stopping due to {max_consecutive_errors} consecutive errors.")
break
if consecutive_errors >= max_consecutive_errors or 'HTTP Error 404' in log_stream.getvalue():
break
except Exception as e:
logger.error(f"Process pool encountered an error: {str(e)}")
break
end_time = time.time()
duration = end_time - start_time
logger.info(f"Total time taken: {duration:.2f} seconds")
print(f"Total time taken: {duration:.2f} seconds")
save_path = r'C:\Users\hamid\Downloads\Crypto_Data_Table.csv'
all_data.to_csv(save_path, index=False)
logger.info(f"All data saved to '{save_path}'")
</code></pre>
<p>Are there any specific adjustments or optimizations that could significantly speed up the execution time? Would using another concurrency method, like ThreadPoolExecutor or a different library, help? Or is there a way to optimize the data fetching and processing in a way that reduces the overall time? Any suggestions for reducing the execution time would be greatly appreciated.</p>
|
<python><web-scraping><beautifulsoup><python-requests><multiprocessing>
|
2024-08-15 01:24:13
| 1
| 319
|
HamidBee
|
78,873,304
| 1,601,580
|
How to sample multiple completions (n) directly from Claude API without a for loop
|
<p>I'm using the Anthropic Claude API and I'm trying to generate multiple completions (n completions) for a given prompt in a single API call. OpenAI's API provides an n parameter in their sampling settings to achieve this, but I can't find an equivalent option in the Claude API.</p>
<h3>My Current Approach:</h3>
<p>I'm currently using a retry mechanism to handle potential errors during API calls, which looks like this:</p>
<pre class="lang-py prettyprint-override"><code>from tenacity import retry, stop_after_attempt, wait_exponential
def before_sleep(retry_state):
print(f"(Tenacity) Retry, error that caused it: {retry_state.outcome.exception()}")
def retry_error_callback(retry_state):
exception = retry_state.outcome.exception()
exception_str = str(exception)
if "prompt is too long" in exception_str and "400" in exception_str:
raise exception
return 'No error that requires us to exit early.'
@retry(stop=stop_after_attempt(20), wait=wait_exponential(multiplier=2, max=256),
before_sleep=before_sleep, retry_error_callback=retry_error_callback)
def call_to_anthropic_client_api_with_retry(gen: AnthropicGenerator, prompt: str) -> dict:
response = gen.llm.messages.create(
model=gen.model,
max_tokens=gen.sampling_params.max_tokens,
system=gen.system_prompt,
messages=[
{"role": "user", "content": [{"type": "text", "text": prompt}]}
],
temperature=gen.sampling_params.temperature,
top_p=gen.sampling_params.top_p,
n=gen.sampling_params.n, # Intended to generate multiple completions
stop_sequences=gen.sampling_params.stop[:3],
)
return response
</code></pre>
<p>Problem:</p>
<p>I can't find an n parameter in the Anthropic API documentation that allows generating multiple completions in one request.</p>
<p>Does the Claude API support generating multiple completions (n completions) directly within a single API call? If not, how can I achieve this without resorting to looping multiple requests?</p>
<p>cross discord: <a href="https://discord.com/channels/1072196207201501266/1213976011998498816/threads/1273440866861846549" rel="nofollow noreferrer">https://discord.com/channels/1072196207201501266/1213976011998498816/threads/1273440866861846549</a>
cross: <a href="https://dev.to/brando90/how-to-sample-multiple-completions-n-directly-from-claude-api-without-a-for-loop-2m1e" rel="nofollow noreferrer">https://dev.to/brando90/how-to-sample-multiple-completions-n-directly-from-claude-api-without-a-for-loop-2m1e</a></p>
<hr />
<p>For now doing this:</p>
<pre class="lang-py prettyprint-override"><code>@retry(stop=stop_after_attempt(20), wait=wait_exponential(multiplier=2, max=256),
before_sleep=before_sleep, retry_error_callback=retry_error_callback)
def call_to_anthropic_client_api_with_retry(gen: AnthropicGenerator, prompt: str) -> dict:
# max_tokens=8192, # max_tokens for Claude 3.5 https://docs.anthropic.com/en/docs/about-claude/models#model-comparison
# client = anthropic.Anthropic(api_key=gen.api_key)
# response = client.messages.create(
# response_text: str = gen.llm.messages.create(
# model=gen.sampling_params.model,
# max_tokens=gen.sampling_params.max_tokens,
# # temperature=temperature, # note the prompt generator doesn't give this as an input
# system=gen.sampling_params.system,
# messages=[
# {"role": "user", "content": [{"type": "text", "text": prompt}]}
# ],
# temperature=gen.sampling_params.temperature,
# top_p=gen.sampling_params.top_p,
# n=gen.sampling_params.n,
# stop=gen.sampling_params.stop[:3],
# ).content[0].text
if not hasattr(gen.sampling_params, 'n'):
gen.sampling_params.n = 1
content: list[dict] = []
for _ in range(gen.sampling_params.n):
response = gen.llm.messages.create(
model=gen.model,
max_tokens=gen.sampling_params.max_tokens,
system=gen.system_prompt,
messages=[
{"role": "user", "content": [{"type": "text", "text": prompt}]}
],
temperature=gen.sampling_params.temperature,
top_p=gen.sampling_params.top_p,
n=gen.sampling_params.n,
stop_sequences=gen.sampling_params.stop[:3],
)
content.append(response)
response = dict(content=content)
# message example: https://docs.anthropic.com/en/api/messages-examples
return response
</code></pre>
|
<python><machine-learning><nlp><large-language-model><claude>
|
2024-08-15 00:37:53
| 0
| 6,126
|
Charlie Parker
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.