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 ⌀ |
|---|---|---|---|---|---|---|---|---|
77,037,288 | 4,994,337 | How does numpy.array choose default data type? | <p>The <code>numpy.array()</code> function seems to behave rather strangely when some numbers in the order of <code>2**64</code> are involved and no data type is specified. Can anyone explain this behavior? Is it a bug or is it expected?</p>
<pre><code>$ python3
Python 3.10.8 (main, Nov 30 2022, 10:05:23) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> np.__version__
'1.23.5'
>>> np.array([2**63-1]).dtype
dtype('int64')
>>> np.array([2**64-1]).dtype
dtype('uint64')
</code></pre>
<p>So far, I think it makes sense, <code>int64</code> is probably the default, but it can't represent <code>2**64-1</code> so it switches to <code>uint64</code>.</p>
<pre><code>>>> np.array([2**64-1, 2**63-1]).dtype
dtype('float64')
</code></pre>
<p>Now that I've added some other number, which perfectly fits in <code>uint64</code> as well, it suddently changes to <code>float64</code>.</p>
<pre><code>>>> np.array([2**65-1]).dtype
dtype('O')
</code></pre>
<p>OK, <code>2**65-1</code> requires some kind of larger integer representation.</p>
<pre><code>>>> np.array([2**64-1, 2**65-1]).dtype
dtype('O')
</code></pre>
<p>This isn't just weird, but it also affects precision:</p>
<pre><code>>>> int(np.round(np.array([2**64-1])[0]))
18446744073709551615
>>> int(np.round(np.array([2**64-1, 2**63-1])[0]))
18446744073709551616
>>> int(np.round(np.array([2**64-1, 2**65-1])[0]))
18446744073709551615
</code></pre>
<p>In these 3 expressions, the 1st and 3rd are evaluated without loss of precision, but the 2nd one gets rounded due to the conversion to float and back to int. Why is the 2nd expression using floats while a perfectly accurate integer type is clearly available?</p>
| <python><arrays><numpy><types> | 2023-09-04 11:19:47 | 1 | 579 | PieterNuyts |
77,037,112 | 12,415,855 | Text from dt-tag is not outputted? | <p>i try to get a text from a website using the following code:</p>
<pre><code>import time
import os
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
if __name__ == '__main__':
os.environ['WDM_LOG'] = '0'
options = Options()
# options.add_argument('--headless=new')
options.add_argument("start-maximized")
options.add_experimental_option("prefs", {"profile.default_content_setting_values.notifications": 1})
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('excludeSwitches', ['enable-logging'])
options.add_experimental_option('useAutomationExtension', False)
options.add_argument('--disable-blink-features=AutomationControlled')
srv=Service()
driver = webdriver.Chrome (service=srv, options=options)
wLink = "https://www.medimops.de/agatha-christie-agatha-christie-ein-schritt-ins-leere-why-didn-t-they-ask-evans-der-komplette-vierteiler-mit-starbesetzung-blu-ray-blu-ray-M0B0BW28MKKR.html"
driver.get (wLink)
time.sleep(3)
soup = BeautifulSoup (driver.page_source, 'lxml')
wTitle = soup.find("div", {"class": "detail-page__title"}).text.strip()
worker = soup.find("dl", {"class": "product-attributes__table"})
worker = worker.find("template")
wDT = worker.find("dt")
print(wDT)
print(wDT.text)
print(list(wDT.stripped_strings))
driver.quit()
</code></pre>
<p>I get this as output for the print-statements:</p>
<pre><code><dt class="product-attributes__definition">EAN / ISBN-<!-- -->:</dt>
[]
</code></pre>
<p>Why is the text ("EAN / ISBN") from the dt-tag not outputted?</p>
| <python><selenium-webdriver><beautifulsoup> | 2023-09-04 10:49:25 | 1 | 1,515 | Rapid1898 |
77,036,990 | 13,100,938 | How do you ensure Dataflow Pipeline synchronicity in Apache Beam? | <p>The Dataflow pipeline I've written ingests data that has been published synchronously. The order of this data does not matter, but it is published every second.</p>
<p>I need to output the result of the pipeline synchronously too, but at the moment I'm seeing inconsistent delays between the outputs of the pipeline.</p>
<p>I believe this can be solved with timers and triggers, but I can't workout how to use them correctly.</p>
<pre class="lang-py prettyprint-override"><code>| "Window"
>> beam.WindowInto(
window.FixedWindows(self.window_length),
trigger=trigger.AfterProcessingTime(2),
accumulation_mode=beam.trigger.AccumulationMode.ACCUMULATING,
# if message late by 700ms, still accept
allowed_lateness=window.Duration(seconds=0.7)
)
</code></pre>
<p>The above method works but is still not synchronous. I had to add the processing time trigger to allow my other steps to run before the data is written to Firestore. It is a hacky workaround, and I need something more concrete.</p>
<p>The issue with my current implementation is that data is collected inside the window, with an allowed lateness of 700ms. Instead of the DoFn being in control of when data is emitted to Firestore, the window technically controls it. This means that it is not synchronous and the data does not arrive in Firestore every second.</p>
<p>Pipeline steps:</p>
<pre><code>Step Group: Raw Data Processing
1. Read from PubSub
2. Deserialise message from Protobuf
3. Add message timestamp (window.TimestampedValue)
Raw Data Processing Step Group Branches to:
- Write data to BigQuery
- Step Group: Extra Processing
Step Group: Extra Processing
1. Add Key to data (for grouping)
2. Window data (as above)
3. Group data (GroupByKey())
4. Transform Data (custom ParDo())
Extra Processing Step Group Branches To:
- Write to Firestore (DoFn)
- Publish to PubSub topic
</code></pre>
<p>Is there any way of ensuring that my pipeline emits data to Firestore at exactly 1 second intervals?</p>
| <python><google-cloud-platform><google-cloud-firestore><google-cloud-dataflow><apache-beam> | 2023-09-04 10:32:37 | 0 | 2,023 | Joe Moore |
77,036,960 | 710,955 | How do I get the page URL of a wiki page with mwclient? | <p>I'm using <a href="https://github.com/mwclient/mwclient" rel="nofollow noreferrer">mwclient</a> and I want to get the URL of the page loaded.</p>
<pre><code>import mwclient
site = mwclient.Site('fr.wikipedia.org')
page = site.Pages['Curling aux Jeux olympiques de 2022']
</code></pre>
<p>Is it possible to get the url of the page? ⇒ 'https://fr.wikipedia.org/wiki/Curling_aux_Jeux_olympiques_de_2022'</p>
| <python><wikipedia><wikipedia-api><mwclient> | 2023-09-04 10:27:52 | 0 | 5,809 | LeMoussel |
77,036,837 | 9,516,820 | How to select only certain div elements in a list of div elements with selenium | <p>I have a list of divs as follows</p>
<p><a href="https://i.sstatic.net/xIsGx.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/xIsGx.png" alt="enter image description here" /></a></p>
<p>From the list of divs given below, I only want to extract certain data from divs between <code>data-index=3</code> and <code>data-index=10</code>.</p>
<p>Currently I am able to extract all the divs using XPATH. But I don't want that. I want to only target specific divs.</p>
<p>How do I do that? Thank you</p>
| <python><html><selenium-webdriver><xpath> | 2023-09-04 10:08:41 | 2 | 972 | Sashaank |
77,036,672 | 6,458,245 | Post-trained TransformerEncoder model is nondeterministic? | <p>I don't understand why running my model which is a single transformer encoder layer is deterministic but after I train it, it becomes non deterministic?</p>
<pre><code>import torch
from torch import nn
import torch.optim as optim
class MyModel(nn.Module):
def __init__(self):
super().__init__()
self.encoder_layer = nn.TransformerEncoderLayer(d_model=1, nhead=1, dim_feedforward=2)
self.trans = nn.TransformerEncoder(self.encoder_layer, num_layers=1)
def forward(self, x):
y = self.trans(x)
y = torch.flatten(y)
y = nn.Linear(2,1)(y)
return y
model = MyModel()
model.train()
optimizer = optim.Adam(model.parameters(), lr=0.01)
for epoch in range(1):
training = torch.rand(size=(2,1))
labels = training[0] + 1
optimizer.zero_grad()
outputs = model(training)
loss = nn.MSELoss()(outputs, labels)
# print(loss)
loss.backward()
optimizer.step()
model.eval()
x = torch.tensor([[1.],[1.]])
print(model(x))
</code></pre>
<p>If I run the last line multiple times I get different output. Why?</p>
| <python><pytorch> | 2023-09-04 09:45:15 | 1 | 2,356 | JobHunter69 |
77,036,669 | 17,561,414 | Databricks Autoloader writing stream | <p>I have multiple tables (csv files per table) loaded in azure datalake and would like to use autoloader to load everytable in Databricks Delta table.</p>
<p>I have a python code where I use the <code>for loop</code> to create the schema per table, create the <code>df</code> and then <code>writeStream</code> the <code>df</code>.</p>
<p>I also have the function <code>update_insert</code>, where I do some data manipulation and also included the <code>merge</code> function to update insert the delta tables.</p>
<p>This is my function code:</p>
<pre><code>def update_insert(df, epochId, cdm):
# clean only 100% identical rows'
print("------------------- " + cdm)
df = df.dropDuplicates()
w = Window.partitionBy("Id").orderBy(F.col("modifiedon").desc())
df = df.withWatermark("modifiedon", "1 day").withColumn("rn", F.row_number().over(w)).where(F.col("rn") == 1).drop('rn')
# final =df.join(agg, on=["id", "modifiedon"], how="right")
dfUpdates = df.withColumnRenamed("id","BK_id")
p = re.compile('^BK_')
list_of_columns = dfUpdates.columns
list_of_BK_columns = [ s for s in dfUpdates.columns if p.match(s) ]
string = ''
for column in list_of_BK_columns:
string += f'table.{column} = newData.{column} and '
string_insert = ''
for column in list_of_BK_columns:
string_insert += f'table.{column} = newData.{column} and '
string_insert[:-4]
dictionary = {}
for key in list_of_columns:
dictionary[key] = f'newData.{key}'
print("printing " + cdm + " columns")
print(dfUpdates.columns)
deltaTable = DeltaTable.forPath(spark,f"abfss://bronze@datalake01p.dfs.core.windows.net/D365/{cdm}"+"_autoloader_nodups")
deltaTable.alias('table') \
.merge(dfUpdates.alias("newData"),
string
) \
.whenMatchedUpdate(set =
dictionary
) \
.whenNotMatchedInsert(values =
dictionary
) \
.execute()
</code></pre>
<p>Above function is used below in the autoloader's <code>foreachBatch</code>:</p>
<pre><code>for entity in manifest.collect()[0]['entities']:
cdm = entity.asDict()['name']
print(cdm)
schema = StructType()
length = len(entity.asDict()['attributes']) - 1
for index1, attribute in enumerate(entity.asDict()['attributes']):
if (attribute.asDict()['dataType'] in ('int32', 'time')) and (index1 != length):
field = StructField(attribute.asDict()['name'],IntegerType(),True)
schema.add(field)
elif attribute.asDict()['dataType'] in ('dateTime') and (index1 != length):
field = StructField(attribute.asDict()['name'],TimestampType(),True)
schema.add(field)
elif attribute.asDict()['dataType'] in ('string') and (index1 != length):
field = StructField(attribute.asDict()['name'],StringType(),True)
schema.add(field)
elif attribute.asDict()['dataType'] in ('int64') and (index1 != length):
field = StructField(attribute.asDict()['name'],LongType(),True)
schema.add(field)
elif attribute.asDict()['dataType'] in ('decimal') and (index1 != length):
field = StructField(attribute.asDict()['name'],DecimalType(38, 20),True)
schema.add(field)
elif index1 == length:
field = StructField(attribute.asDict()['name'],StringType(),True)
schema.add(field)
LastColumnName = attribute.asDict()['name']
LastColumnDataType = attribute.asDict()['dataType']
else:
field = StructField(attribute.asDict()['name'],StringType(),True)
schema.add(field)
# Define variables
checkpoint_directory = f"abfss://bronze@datalake01p.dfs.core.windows.net/D365/checkpoints/{cdm}"
data_source = f"abfss://dataverse@append01p.dfs.core.windows.net/*/{cdm}/*.csv"
source_format = "csv"
# Configure Auto Loader to ingest csv data to a Delta table
print("schema for " + cdm)
# print(schema)
df = (
spark.readStream
.option("delimiter", ",")
.option("quote", '"')
.option("mode", "permissive")
.option("lineSep", "\r\n")
.option("multiLine", "true")
.format("cloudFiles")
.option("cloudFiles.format", source_format)
# .option("cloudFiles.schemaLocation", checkpoint_directory)
.option("cloudFiles.inferColumnTypes","true")
.option("header", "false")
.option("escape", '"')
.schema(schema)
.load(data_source)
)
print("writing " + cdm)
# print(df.columns)
df.writeStream.format("delta").foreachBatch(lambda df, epochId: update_insert(df, epochId, cdm)).option("checkpointLocation", checkpoint_directory).trigger(availableNow=True).start()
</code></pre>
<p>The problem is that for each loop is not working as it is supposed to work. I have added the print statments to the code to see which <code>df</code> are created for which tables.</p>
<p>For example:</p>
<ol>
<li>it starts with prinitng the <code>print(cdm)</code> (<code>cdm</code> is the name of the table) and output is <code>msdyn_workorder</code></li>
<li>then is should <code>print("schema for " + cdm)</code> and output is <code>schema for msdyn_workorder</code></li>
<li>next print is <code>print("writing " + cdm</code> and out put is <code>writing msdyn_workorder</code></li>
</ol>
<p>This is where it goes wrong as the next print should give the outpur of the print which is inside the function <code>print("------------------- " + cdm)</code>. Instead what it does is printing the next table name <code>print(cdm)</code> which is <code>nrq_customerassetproperty</code>, so starting for loop again (i have only two tables in so <code>for loop</code> should run twice).</p>
<p>Then it continues same sequence of printing statements</p>
<ol>
<li><code>print("schema for " + cdm)</code> and output is <code>schema for nrq_customerassetproperty</code></li>
<li>next print is <code>print("writing " + cdm</code> and out put is writing nrq_customerassetproperty</li>
</ol>
<p>And here it started to print things which are in the <code>def</code> like : <code>print("------------------- " + cdm)</code>, <code>print("schema for " + cdm)</code> has the out <code>printing nrq_customerassetproperty columns</code>.</p>
<p>With the next print it gets interested that when I ask to <code>print(dfUpdates.columns)</code> which should be <code>df</code> I read in the <code>for each</code> loop. It prints the columns of the previous <code>df</code>. in this case columns of the <code>msdyn_workorder</code>.</p>
<p>I dont know where it goes wrong. Is it that streaming data has some problems with <code>for loop</code>s?</p>
<p><strong>Screenshot of print statements.</strong>
note that its printing <code>printing nrq_customerassetproperty columns</code> but the columns does correspond to <code>msdyn_workorder</code> table.</p>
<p><a href="https://i.sstatic.net/SmcHo.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/SmcHo.png" alt="enter image description here" /></a></p>
| <python><for-loop><spark-streaming><azure-databricks><databricks-autoloader> | 2023-09-04 09:44:27 | 1 | 735 | Greencolor |
77,036,640 | 4,268,976 | Django Celery Beat Periodic Tasks Running Twice | <p>I trying to send scheduled emails to users but my Django celery periodic tasks running 2 times within a half-hour span. Every day I scheduled my email task at 7.00 AM but it is running 1st task at 7.00 AM and the same task is running at 7.30 AM also.</p>
<p>Here is my celery app</p>
<pre><code># coding=utf-8
from __future__ import absolute_import
import os
from celery import Celery
from django.conf import settings
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app_name.settings")
app = Celery("app_name")
app.config_from_object("app_name.celeryconfig")
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
@app.task(bind=True)
def debug_task(self):
print ("Request: {0!r}".format(self.request))
</code></pre>
<p>Celery app config</p>
<pre><code># coding=utf-8
import os
PROJECT_APP_PATH = os.path.dirname(os.path.abspath(__file__))
# Celery Config
BROKER_URL = 'redis://redis_server:6379'
CELERY_RESULT_BACKEND = 'redis://redis_server:6379'
CELERY_TASK_SERIALIZER = 'json'
CELERY_ACCEPT_CONTENT = ['application/json'] # Ignore other content
CELERY_RESULT_SERIALIZER = 'json'
CELERY_ENABLE_UTC = True
CELERY_TASK_RESULT_EXPIRES = 0 # Never expire task results
CELERY_IGNORE_RESULT = True
CELERY_TRACK_STARTED = True
CELERY_IMPORTS = (
"module.tasks"
)
</code></pre>
<p>Periodic Tasks scheduled in Django admin panel
<a href="https://i.sstatic.net/5ElzL.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/5ElzL.png" alt="enter image description here" /></a></p>
<p>To run the celery app and celery beat I used following command</p>
<p><code>celery -A app_name worker -l INFO </code></p>
<p><code>celery -A app_name beat --loglevel=debug --scheduler django_celery_beat.schedulers:DatabaseScheduler --pidfile=</code></p>
<p>Functionality working fine but these tasks are running twice daily for 2 to 3 days after that, it will run once but if I restart celery then It will start running tasks again twice for some days.</p>
<p>Please let me know If I'm missing in celery configuration.</p>
| <python><django><celery><django-celery><django-celery-beat> | 2023-09-04 09:40:16 | 0 | 4,122 | NIKHIL RANE |
77,036,411 | 22,496,572 | PyTorch matrix multiplication does not respect slicing | <p>I got to this by having to batch long inputs for transfomer models, noticing difference between batched and non-batched results. I finally isolated the first discrepancy I noticed, resulting in the following:</p>
<pre><code>import torch
n = 20
vec = torch.rand(n, 20)
a = torch.rand(30, 20)
for i in range(1, n+1):
print(i, torch.equal(
torch.nn.functional.linear(vec, a)[:i],
torch.nn.functional.linear(vec[:i], a)))
</code></pre>
<p>yielding the output:</p>
<pre><code>1 False
2 False
3 False
4 True
5 True
6 True
7 False
8 False
9 False
10 True
11 True
12 True
13 False
14 False
15 False
16 True
17 True
18 True
19 True
20 True
</code></pre>
<p>This is just one operation, when combined multiple times (as in a transformer), it might cause large divergence, enlarging the atol for which torch.allclose outputs True. Why is that, and can one do something about it?</p>
| <python><pytorch><precision><huggingface-transformers><torch> | 2023-09-04 09:03:40 | 1 | 371 | Sasha |
77,036,406 | 1,652,219 | Pandas queries to SQL queries (Python equivalent to R's dplyr) | <h2>Question</h2>
<p>At my company people would like to build dataframe/table queries in Python as the Python syntax is often much more clear and easier to work with than SQL queries as you can chain together your operations.</p>
<p>In <strong>R</strong> it easy to translate between R dataframe operations and SQL because of the <strong>tidyverse</strong> and <strong>dplyr</strong> libraries. Is there anything similar in Python?</p>
<h2>Example of what I want (written in R)</h2>
<p>Here I show in <strong>R</strong> what I would like to be able to do in Python/Pandas, which is basically 1) place data in database, 2) make fancy dataframe operations, 3) carry out those operations in database.</p>
<pre><code># Importing library
library(dplyr)
# Connecting to database
con <- DBI::dbConnect(RMariaDB::MariaDB(),
host = "database.rstudio.com",
user = "hadley",
password = rstudioapi::askForPassword("Database password")
)
# Placing some data in the database
copy_to(con, nycflights13::flights, "flights",
temporary = FALSE,
indexes = list(
c("year", "month", "day"),
"carrier",
"tailnum",
"dest"
)
)
</code></pre>
<p>Now to the "hard" problem I would like to perform in Python.</p>
<pre><code># Making fancy operations on data using tidyverse chaining
tailnum_delay_db <- flights_db %>%
group_by(tailnum) %>%
summarise(
delay = mean(arr_delay),
n = n()
) %>%
arrange(desc(delay)) %>%
filter(n > 100)
# Getting SQL code to perform same operation!!!!
tailnum_delay_db %>% show_query()
> <SQL>
> SELECT `tailnum`, AVG(`arr_delay`) AS `delay`, COUNT(*) AS `n`
> FROM `flights`
> GROUP BY `tailnum`
> HAVING (COUNT(*) > 100.0)
> ORDER BY `delay` DESC
</code></pre>
<h2>Example in Pandas</h2>
<p>Let's try to do the same in Pandas, where we just make some more simple data.</p>
<pre><code># Import pandas library
import pandas as pd
import sqlite3
# Creating a local Pandas DataFrame with some data
df = pd.DataFrame({'A': [10,20,30,40,50,60], 'B': ['A', 'A', 'B', 'B', 'C', 'C']})
# Connecting to database
conn = sqlite3.connect('test_database')
c = conn.cursor()
# Writing dataframe to database
df.to_sql('df', conn, if_exists='replace', index = False)
</code></pre>
<p>So far so good! Next I make some "fancy" pandas operations that I want to translate to SQL.</p>
<pre><code># Making a groupby
df.groupby('B').mean().reset_index()
</code></pre>
<p>Now, is there any way to get the SQL for carrying out this operation?</p>
<h2>The Obvious Solution (which I am NOT looking for)!</h2>
<p>One could just:</p>
<ol>
<li>Read SQL data into Pandas Dataframe</li>
<li>Make transformations in Pandas locally</li>
<li>Write Pandas Dataframe to SQL table</li>
</ol>
<p>But I don't want to pull ALL my data into Python because I have memory constraints. I would e.g. like to read 1000 lines, build my fancy and complicated query, translate it to SQL and the execute the SQL query remotely on the database.</p>
| <python><sql><pandas><dplyr><translate> | 2023-09-04 09:02:57 | 0 | 3,944 | Esben Eickhardt |
77,036,375 | 9,261,322 | When to call subprocess.communicate()? | <p>I run a process and read the first line from <code>stderr</code> and check exit code:</p>
<pre><code>import subprocess
p = subprocess.Popen(['time', '-p', 'ls'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(p.stderr.readline().decode('utf-8'))
streamdata = p.communicate()[0]
print(f'exitcode: {p.returncode}')
</code></pre>
<p>is this code correct? Do I call <code>p.communicate()</code> in a right place?</p>
| <python> | 2023-09-04 08:58:19 | 0 | 4,405 | Alexey Starinsky |
77,036,354 | 11,329,736 | Run command when creating Conda environment with Snakemake | <p>I am using <code>snakemake</code> to run a workflow. One of my rules uses the following <code>yaml</code> file to create the <code>Conda</code> env:</p>
<pre><code>name: macs2
channels:
- conda-forge
- bioconda
- defaults
dependencies:
- macs2=2.2.9.1
- homer=4.11
</code></pre>
<p>For the <code>homer</code> package I need to install a data base, which I have included in the first line of the shell command of this rule:</p>
<pre><code>rule annotate_peaks:
input:
"peaks/{sample_ip}_vs_{sample_input}/{sample_ip}_peaks.bed"
output:
"peaks/{sample_ip}_vs_{sample_input}/{sample_ip}_peaks_annotated.txt"
params:
genome=config["general"]["genome"],
regions=config["chip-seq"]["macs2"]["regions"],
threads: config["resources"]["macs2"]["cpu"]
resources:
runtime=config["resources"]["macs2"]["time"]
conda:
"envs/macs2.yaml"
shell:
"perl $CONDA_PREFIX/share/homer*/configureHomer.pl -install {params.genome}; "
"annotatePeaks.pl {input} {params.genome} > {output}"
</code></pre>
<p>The problem with this approach is that the first shell command will download the data for the chosen data base which are very large files and it takes a while to complete.</p>
<p>For each iteration of the rule this information will be downloaded again, which will slow down the analysis.</p>
<p>Is there a way to run <code>perl $CONDA_PREFIX/share/homer*/configureHomer.pl -install {params.genome}</code> when <code>snakemake</code> creates the "macs2" <code>Conda</code> env so that this only has to be done once?</p>
| <python><conda><snakemake><virtual-environment> | 2023-09-04 08:55:08 | 1 | 1,095 | justinian482 |
77,036,229 | 20,830,264 | trying to install label-studio with Python | <p>I'm trying to install label-studio library following the web-site information:
<a href="https://labelstud.io/guide/install" rel="nofollow noreferrer">enter link description here</a></p>
<p>In particular I'm using the following commands:</p>
<pre><code>pip install label-studio --user
</code></pre>
<p>The module is correctly installed in the folder: c:\users*******\appdata\roaming\python\python311\site-packages.</p>
<p>But I get the following error when I run the command <code>label-studio start</code>:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>label-studio : The term 'label-studio' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or
if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ label-studio
+ ~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (label-studio:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException</code></pre>
</div>
</div>
</p>
<p>Or if I run <code>python -m label-studio</code>, I get this error:</p>
<pre><code>C:\Python311\python.exe: No module named label-studio
</code></pre>
<p>I also tried with the following installation method:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>python3 -m venv c:\path\to\myenv
c:\path\to\myenv\Scripts\activate.bat
python -m pip install label-studio --user</code></pre>
</div>
</div>
</p>
<p>But when I run the command <code>label-studio</code> I get the same error.</p>
<p>Finally if I use the following commands:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>python3 -m venv env
source env/bin/activate
python -m pip install label-studio</code></pre>
</div>
</div>
</p>
<p>I get the following error in the <code>source env/bin/activate</code> command:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>source : The term 'source' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path wa
s included, verify that the path is correct and try again.
At line:1 char:1
+ source env/bin/activate
+ ~~~~~~
+ CategoryInfo : ObjectNotFound: (source:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException</code></pre>
</div>
</div>
</p>
<p>Do you know what could be the problem?</p>
| <python><pip><python-venv><label-studio> | 2023-09-04 08:32:57 | 1 | 315 | Gregory |
77,036,214 | 535,009 | Running python Flask app with maven-like folder structure on Google Cloud Run | <p>How to configure Google Cloud Run to be able to run (via <code>gcloud run deploy</code>) a python Flask app with the following source code structure?</p>
<pre><code>root
│
├── src
│ └── app
│ └── main.py
│
├── Dockerfile
└── requirements.txt
</code></pre>
| <python><flask><google-cloud-run> | 2023-09-04 08:30:44 | 1 | 533 | St. |
77,036,213 | 8,278,075 | Make only one value to be a unique shape in Altair point graph? | <p>I'm using Altair to make a point graph where all the shapes are the same (circle) for each stock value except for one (let's say diamond).</p>
<p>In this dataset I want the stock symbol for "V" to be a unique shape.</p>
<pre class="lang-py prettyprint-override"><code>ratio_df = pd.DataFrame(data={
"symbol": {
"0": "V",
"1": "MA",
"2": "FI"
},
"shortName": {
"0": "Visa Inc.",
"1": "Mastercard Incorporated",
"2": "Fiserv, Inc."
},
"value": {
"0": 31.446135,
"1": 38.91105,
"2": 30.7025
}
})
chart = (
alt.Chart(ratio_df)
.mark_point()
.encode(
row=alt.Row("metric:N"),
x=alt.X("value:Q"),
y=alt.Y("symbol:N"),
tooltip=alt.Tooltip(["shortName:N", "metric:N", "value:Q"]),
color=alt.Color("shortName:N"),
shape=alt.condition("datum.symbol == V", "diamond", "circle"),
)
)
</code></pre>
<p>I've tried:</p>
<ul>
<li><code>encode(..., shape=alt.condition("datum.symbol == V", alt.value("diamond"), alt.value("circle")))</code>
<ul>
<li>Cannot use alt.condition here</li>
</ul>
</li>
<li><code>encode(..., shape=alt.Shape("symbol:N"))</code>
<ul>
<li>Different shapes for each stock symbol; I need all the same except one</li>
</ul>
</li>
<li><code>mark_point(..., shape=alt.Shape("symbol:N"))</code>
<ul>
<li>Different shapes for each stock symbol</li>
</ul>
</li>
<li><code>mark_point(..., shape=alt.condition("datum.symbol == V", alt.value("diamond"), alt.value("circle")))</code>
<ul>
<li>Shape requires a string</li>
</ul>
</li>
<li><a href="https://github.com/altair-viz/altair/issues/1135#issuecomment-421415074" rel="nofollow noreferrer">https://github.com/altair-viz/altair/issues/1135#issuecomment-421415074</a>
<ul>
<li>Only two bins; I could have 2 or more</li>
</ul>
</li>
</ul>
<h3>Solution: ordering list as <code>range</code></h3>
<pre class="lang-py prettyprint-override"><code>base_symbol: str = "V"
marker_shape: list[str] = []
for distinct_symbol in ratio_df["symbol"].drop_duplicates().sort_values():
if distinct_symbol == base_symbol:
marker_shape.append("cross")
else:
marker_shape.append("circle")
chart = (
alt.Chart(ratio_df)
.mark_point()
.encode(
row=alt.Row("metric:N"),
x=alt.X("value:Q"),
y=alt.Y("symbol:N"),
tooltip=alt.Tooltip(["shortName:N", "metric:N", "value:Q"]),
color=alt.Color("shortName:N"),
shape=alt.Shape("shortName", scale=alt.Scale(range=marker_shape)),
)
)
chart
</code></pre>
| <python><dataframe><altair> | 2023-09-04 08:30:33 | 1 | 3,365 | engineer-x |
77,036,059 | 12,415,855 | os.isdir not working on Mac after create executeable with pyinstaller? | <p>i try to check the existing files and folders using the following code:</p>
<pre><code>import os, sys
path = os.path.abspath(os.path.dirname(sys.argv[0]))
listFiles = [x for x in os.listdir(path)]
existDirs = [x for x in os.listdir(path) if os.path.isdir(x)]
print(path)
print(listFiles)
print(existDirs)
</code></pre>
<p>I also create executeables for this file using:</p>
<pre><code>pyinstaller --onefile test.py
</code></pre>
<p>On Windows everything works find (the output is correct when i directly run the test.py and also when i run the created executeable).</p>
<p>But on Mac when i run the pyhon file test.py everything works fine and the output looks like this:</p>
<pre><code>/Users/polzimac/Documents/DEV/Fiverr/ORDER/robalf/gptFiles
['chatGPT.spec', '.DS_Store', 'dist', 'CHUNK 1', 'test.py', 'test.spec', 'chatGPT.py', 'chatGPT', 'build']
['dist', 'CHUNK 1', 'build']
</code></pre>
<p>But when i run the created program on Mac i get this output and the existDir-output is empty:</p>
<pre><code>/Users/polzimac/Documents/DEV/Fiverr/ORDER/robalf/gptFiles
['chatGPT.spec', '.DS_Store', 'test', 'dist', 'CHUNK 1', 'test.py', 'test.spec', 'chatGPT.py', 'chatGPT', 'build']
[]
</code></pre>
<p>Why is existDirs empty when i run the compiled program on Mac?</p>
| <python><macos><pyinstaller> | 2023-09-04 08:04:37 | 1 | 1,515 | Rapid1898 |
77,035,987 | 5,953,720 | Why do I need to convert to_numpy() otherwise loc assignment does not work? | <p>I am using <a href="https://github.com/subashgandyer/datasets/blob/main/Real%20estate.csv" rel="nofollow noreferrer">this csv</a>.</p>
<pre><code>import pandas as pd
import numpy as np
real_estate = pd.read_csv('real_estate.csv',index_col=0)
buckets = pd.cut(real_estate['X2 house age'],4,labels=False)
for i in range(len(real_estate['X2 house age'])):
real_estate.loc[i,'X2 house age'] = buckets[i]
</code></pre>
<p>It gives me:</p>
<pre><code>KeyError: 0
</code></pre>
<p>for the line <code>real_estate.loc[i,'X2 house age'] = buckets[i]</code> it fails just at the first iteration</p>
<p>Why do I need to change the line to <code>buckets = pd.cut(real_estate['X2 house age'],4,labels=False).to_numpy()</code> to make it work?</p>
| <python><pandas><numpy><categorization><discretization> | 2023-09-04 07:54:09 | 2 | 1,517 | Allexj |
77,035,955 | 8,930,751 | Find the first occurrence of the specific attribute in list of dictionaries - python | <p>I have a similar dataset</p>
<pre><code>dataset = [
{
'Country': 'GB',
'Pollutant': 'SO2',
'Pollution': 10
},
{
'Country': 'AL',
'Pollutant': 'O3',
'Pollution': 10,
'Year': 2015
},
{
'Country': 'BE',
'Pollutant': 'SO2',
'Pollution': 5,
'Year': 2016
}
]
</code></pre>
<p>In this case, the first object doesn't have 'Year' attribute. I want to find the first occurrence of the year attribute and capture its value.<br />
So I tried this:</p>
<pre><code>[x for x in dataset if hasattr(x,'Year')][0]['Year']
</code></pre>
<p>This is giving index out of range error.</p>
<p>Later I tried this to find if the specific attribute is there :</p>
<pre><code>for x in dataset:
print(any('Year' in x for x in dataset))
</code></pre>
<p>But this is returning true of all the list objects.<br />
Can someone guide me how to get the first 'Year' attribute value, preferably in single line code.</p>
| <python><python-3.x><dictionary><iterator> | 2023-09-04 07:48:35 | 6 | 2,416 | CrazyCoder |
77,035,950 | 2,066,215 | Segmentation fault opening Calc spreadsheet | <p>I need to crunch a Calc spreadsheet composed of many individual sheets. The Wiki has a detailed <a href="https://wiki.documentfoundation.org/Macros/Python_Guide/Documents#Open" rel="nofollow noreferrer">Python guide</a> that I am following. I installed the <code>libreoffice-script-provider-python</code> package and am able to import the <code>uno</code> package without error. However, every time the <code>create_instance</code> function is invoked the interpreter crashes with a segmentation fault. A small example is below:</p>
<pre><code>import uno
CTX = uno.getComponentContext()
SM = CTX.getServiceManager()
def create_instance(name, with_context=False):
if with_context:
instance = SM.createInstanceWithContext(name, CTX)
else:
instance = SM.createInstance(name)
return instance
path = uno.systemPathToFileUrl('/home/user/temp/test.ods')
desktop = create_instance('com.sun.star.frame.Desktop', True)
doc = desktop.loadComponentFromURL(path, '_default', 0, ())
</code></pre>
<p>How can I open a Calc spreadsheet with <code>uno</code>?</p>
<p>Setup:</p>
<ul>
<li>OS: Ubuntu 22.04</li>
<li>Python: 3.10.12</li>
<li>LibreOffice: 7.3.7</li>
</ul>
<p><strong>Update</strong>: The log of an even smaller example. Launching Calc beforehand does not really change the outcome, but is added for completion.</p>
<pre><code>$ soffice --calc --accept="socket,host=localhost,port=2002;urp;StarOffice.ServiceManager"
$ python3
Python 3.10.12 (main, Jun 11 2023, 05:26:28) [GCC 11.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import uno
>>> CTX = uno.getComponentContext()
>>> SM = CTX.getServiceManager()
>>> name='com.sun.star.frame.Desktop'
>>> instance = SM.createInstanceWithContext(name, CTX)
Segmentation fault (core dumped)
</code></pre>
| <python><libreoffice><libreoffice-calc><uno><pyuno> | 2023-09-04 07:46:50 | 1 | 7,000 | Luís de Sousa |
77,035,931 | 9,261,322 | Strange garbage in subprocess.stderr | <p>Why does the following Python script</p>
<pre><code>import subprocess
p = subprocess.Popen(['time', 'ls'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(p.stderr.readline().decode('utf-8'))
</code></pre>
<p>outputs the following:</p>
<pre><code>0.00user 0.00system 0:00.00elapsed 91%CPU (0avgtext+0avgdata 2264maxresident)k
</code></pre>
<p>while <code>time ls</code> command outputs the following:</p>
<pre><code>real 0m0.001s
user 0m0.001s
sys 0m0.000s
</code></pre>
<p>what is this strange suffix <code>91%CPU (0avgtext+0avgdata 2264maxresident)k?</code></p>
<p>The script should read the first line and parse.</p>
| <python><python-3.x><ubuntu> | 2023-09-04 07:43:13 | 1 | 4,405 | Alexey Starinsky |
77,035,785 | 12,000,021 | Problem with the initial value in optimization problem | <p>I have formulated the following problem that tries to minimize the cost of imported energy by controlling a battery:</p>
<pre><code>import pyomo.environ as pyo
def self_consumption(pv, demand, prices):
pv.index = np.arange(1, len(pv) + 1)
demand.index = np.arange(1, len(demand) + 1)
prices.index = np.arange(1, len(prices) + 1)
# Define the model
model = pyo.ConcreteModel()
# Define the set of timesteps
model.timesteps = pyo.Set(initialize = pyo.RangeSet(len(pv)), ordered = True)
# Define the inputs of the model
model.b_efficiency = pyo.Param(initialize = ETTA)
model.b_cap = pyo.Param(initialize = BATTERY_CAPACITY)
model.b_min_soc = pyo.Param(initialize = BATTERY_SOC_MIN)
model.b_max_soc = pyo.Param(initialize = BATTERY_SOC_MAX)
model.b_charging_rate = pyo.Param(initialize = BATTERY_CHARGE_RATE)
model.Ppv = pyo.Param(model.timesteps, initialize = pv.to_dict()['value'], within = pyo.Any)
model.Pdemand = pyo.Param(model.timesteps, initialize = demand.to_dict()['value'], within = pyo.Any)
model.day_ahead_prices = pyo.Param(model.timesteps, initialize = prices.to_dict(), within = pyo.Any)
# Define the decision variables of the model
model.Pbat_ch = pyo.Var(model.timesteps, within = pyo.NonNegativeReals, bounds = (0, model.b_charging_rate))
model.Pbat_dis = pyo.Var(model.timesteps, within = pyo.NonNegativeReals, bounds = (0, model.b_charging_rate))
model.Ebat = pyo.Var(model.timesteps, within = pyo.NonNegativeReals, bounds = (model.b_min_soc * model.b_cap, model.b_max_soc * model.b_cap))
model.Pgrid = pyo.Var(model.timesteps)
model.is_charging = pyo.Var(model.timesteps, within = pyo.Binary)
model.AbsPgrid = pyo.Var(model.timesteps, within=pyo.NonNegativeReals)
# Define the constraints of the model
def BatEnergyRule(model, t):
if t == 1:
return model.Ebat[t] == model.b_cap/2 # battery initialization at half of the capacity (assumption)
else:
return model.Ebat[t] == model.Ebat[t-1] + (model.b_efficiency * model.Pbat_ch[t] - model.Pbat_dis[t]/model.b_efficiency)
model.cons1 = pyo.Constraint(model.timesteps, rule = BatEnergyRule)
def PowerBalanceRule(model, t):
return model.Pgrid[t] == model.Pdemand[t] - model.Ppv[t] + model.Pbat_ch[t] - model.Pbat_dis[t]
model.cons2 = pyo.Constraint(model.timesteps, rule = PowerBalanceRule)
# Charge/Discharge constraint
def charge_discharge_rule(model, t):
return model.Pbat_ch[t] <= model.is_charging[t] * model.b_charging_rate
model.charge_constraint = pyo.Constraint(model.timesteps, rule=charge_discharge_rule)
def discharge_charge_rule(model, t):
return model.Pbat_dis[t] <= (1 - model.is_charging[t]) * model.b_charging_rate
model.discharge_constraint = pyo.Constraint(model.timesteps, rule=discharge_charge_rule)
def AbsPgridRule1(model, t):
return model.AbsPgrid[t] >= model.Pgrid[t]
model.cons6 = pyo.Constraint(model.timesteps, rule=AbsPgridRule1)
def AbsPgridRule2(model, t):
return model.AbsPgrid[t] >= -model.Pgrid[t]
model.cons7 = pyo.Constraint(model.timesteps, rule=AbsPgridRule2)
# Define the objective function
def ObjRule(model):
return sum(model.day_ahead_prices[t] * model.AbsPgrid[t] for t in model.timesteps)
model.obj = pyo.Objective(rule=ObjRule, sense=pyo.minimize)
# Choose a solver
opt = pyo.SolverFactory('glpk')
# Solve the optimization problem
result = opt.solve(model, tee = True)
solution = {
"Pbat_ch": {t: model.Pbat_ch[t].value for t in model.timesteps},
"Pbat_dis": {t: model.Pbat_dis[t].value for t in model.timesteps},
"Ebat": {t: model.Ebat[t].value for t in model.timesteps},
"Pgrid": {t: model.Pgrid[t].value for t in model.timesteps},
}
return solution
</code></pre>
<p>However, by inspecting the solution I notice that the Ebat at the first timestep is not as I have defined it (namely b_cap/2 = 8.3/2 = 4.15, but 0.415). Do you know why is this happening?</p>
<p>The code to run the model is the following:</p>
<pre><code>import numpy as np
import pandas as pd
# battery constants
BATTERY_CAPACITY = 8.3 # Energy capacity of the battery in kWh
BATTERY_CHARGE_RATE = 2.6 # Charging/discharging rate of battery in kW
BATTERY_SOC_MAX = 1 # Maximum amount of state of charge in %
BATTERY_SOC_MIN = 0.05 # Minimum amount of state of charge in %
ETTA = 0.96 # Battery efficiency in %
# Create 'pv' DataFrame
pv = pd.DataFrame({'value': np.random.uniform(0, 5, 24)})
# Create 'demand' DataFrame
demand = pd.DataFrame({'value': np.random.uniform(0, 5, 24)})
# Create 'prices' Series
prices = pd.Series(np.random.uniform(0.1, 0.5, 24), name='prices')
optimization_results = self_consumption(pv, demand, prices)
</code></pre>
| <python><optimization><pyomo> | 2023-09-04 07:21:13 | 1 | 428 | Kosmylo |
77,035,775 | 8,353,711 | How to set default value of nested pydantic schema field | <p>I was trying to set the default value to the nested field of Pydantic model(generated by <a href="https://koxudaxi.github.io/datamodel-code-generator/" rel="nofollow noreferrer"><code>datamodel-codegen</code></a> from below JSON data)</p>
<p>Using Pydantic V2</p>
<p>JSON data:</p>
<pre><code>{
"name": "Alice",
"age": 30,
"addresses": [
{
"street": "123 Main St",
"city": "New York",
"state": "NY"
},
{
"street": "456 Elm St",
"city": "Los Angeles"
}
]
}
</code></pre>
<p>Pydantic model:</p>
<pre><code>from typing import List, Optional
from pydantic import BaseModel
class AddressesItem(BaseModel):
street: str
city: str
# I need this, state: Optional[str] ="NY" either getting generated by `datamodel-codegen`
# or overwriting this value by inheriting the final `Model`
state: Optional[str] = None
class Model(BaseModel):
name: str
age: int
addresses: List[AddressesItem]
</code></pre>
<p>How to set the default value of <code>state</code> as <code>NY</code> by inheriting the <code>Model</code>?</p>
<p>I was trying to do it as shown below with no luck,</p>
<pre><code>from pydantic import field_validator
class MyModel(Model):
class ConfigDict:
validate_assignment = True
@field_validator("state") # check_fields=False, even I add this, it's the same error
def set_value(cls, state):
return state or 'NY'
</code></pre>
<p><strong>Error:</strong></p>
<pre><code>pydantic.errors.PydanticUserError: Decorators defined with incorrect fields: schema.MyModel:51085136.set_value (use check_fields=False if you're inheriting from the model and intended this
</code></pre>
<p><strong>Edit:</strong></p>
<p>Though I was able to find the workaround, looking for an answer using <code>pydantic</code> config or <code>datamodel-codegen</code>.</p>
| <python><pydantic> | 2023-09-04 07:18:46 | 2 | 5,588 | shaik moeed |
77,035,555 | 1,722,380 | pytest does not honor pytest.ini | <pre><code> tree
.
├── app
│ ├── __init__.py
│ ├── app.py
│ └── inner
│ └── __init__.py
├── pytest.ini
└── tests
├── __init__.py
└── test_app.py
</code></pre>
<p>pytest.init contents</p>
<pre><code>[pytest]
markers =
exception
</code></pre>
<p>test case</p>
<pre><code>@pytest.mark.exception(socket.gaierror())
def test_two_equals_two():
assert 2 == 2
</code></pre>
<p>running pytest -v results in</p>
<pre><code> PytestUnknownMarkWarning: Unknown pytest.mark.exception - is this a typo? You can register custom marks to avoid this warning - for details, see https://docs.pytest.org/en/stable/how-to/mark.html
@pytest.mark.exception(socket.gaierror())
</code></pre>
<p>edit 1 - usage of parameterless pytest.mark.* decorators is also mentioned in the warning log even though being registered in pytest.ini</p>
| <python><pytest><fixtures> | 2023-09-04 06:39:49 | 0 | 2,192 | Łukasz |
77,035,238 | 10,431,629 | Reading Data in Pandas from Excel File separated with different segments | <p>I have an excel file which looks like this :</p>
<p><a href="https://i.sstatic.net/IZElr.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/IZElr.png" alt="enter image description here" /></a></p>
<p>I want to read the file into multiple data frames based on the flags like here :</p>
<p>DataEx1, DataEx2 and DataEx3.</p>
<p>So my output should like the following</p>
<pre><code> df1
A1 A2 A3 A4 A5
1 a u 4 10
2 b u 5 12
df2
B1 B2 B3
x 1
y 2 3
z 12 0
df3
C1 C2 C3 C4 C5 C6
10 12 15 20 10 s
20 1 45 2 4 t
30 7 23 20 4 u
4 8 12 2 4 v
</code></pre>
<p>I have tried using pd.read_excel with skiprows functionality. However, not able to get how to use the indicators to read the different data labels separately and load into three different data frames?</p>
<p>Not able to figure the best pythonic way. Any help will immensely appreciated.</p>
| <python><pandas><excel><dataframe><split> | 2023-09-04 05:23:46 | 1 | 884 | Stan |
77,035,204 | 13,916,049 | AttributeError: 'str' object has no attribute 'cat' | <p>For each <code>GENE_SYMBOLS</code> column of a dataframe, merge the rows and retain only unique comma-separated or dash-separated values. After merging the values of each row into a list, obtain only the unique values.</p>
<pre><code>geneset = pd.read_csv("genesets.v2023.1.Hs.tsv", sep="\t", index_col=0)
geneset = geneset.loc["GENE_SYMBOLS"] # retrieve only rows with index name "GENE_SYMBOLS"
for i in geneset.columns:
genes = i.cat(sep=',').tolist() # Merge all the rows of strings with "," delimiter and store as a list
genes = genes.split(",") # split by the "," delimiter
genes = genes.split("-") # or the "-" delimiter
genes = genes.unique() # Keep only if not duplicated
</code></pre>
<p>Traceback:</p>
<pre><code>---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Input In [46], in <cell line: 3>()
2 geneset = geneset.loc["GENE_SYMBOLS"] # retrieve only rows with index name "GENE_SYMBOLS"
3 for i in geneset.columns:
----> 4 genes = i.cat(sep=',').tolist() # Merge all the rows of strings with "," delimiter and store as a list
5 genes = genes.split(",") # split by the "," delimiter
6 genes = genes.split("-") # or the "-" delimiter
AttributeError: 'str' object has no attribute 'cat'
</code></pre>
<p>Input:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>STANDARD_NAME</th>
<th>DEURIG_T_CELL_PROLYMPHOCYTIC_LEUKEMIA_UP</th>
</tr>
</thead>
<tbody>
<tr>
<td>SYSTEMATIC_NAME</td>
<td>M16431</td>
</tr>
<tr>
<td>GENE_SYMBOLS</td>
<td>DDR1,CYP2A6,DTX2P1-UPK3BP1-PMS2P11,MARCKSL1</td>
</tr>
<tr>
<td>SYSTEMATIC_NAME</td>
<td>M16432</td>
</tr>
<tr>
<td>GENE_SYMBOLS</td>
<td>CCL5,IK,ARL6IP5,EIF1AX,PFKP,PJA2,DDR1</td>
</tr>
<tr>
<td>SYSTEMATIC_NAME</td>
<td>M16433</td>
</tr>
<tr>
<td>GENE_SYMBOLS</td>
<td>PJA2,TLR4,GPNMB,TAGLN,COL1A1,CARMN,CD63</td>
</tr>
</tbody>
</table>
</div>
<p>Desired output:</p>
<pre><code>genes = ['DDR1','CYP2A6','DTX2P1', 'UPK3BP1', 'PMS2P11','MARCKSL1', 'CCL5','IK','ARL6IP5',EIF1AX,PFKP,PJA2, TLR4,GPNMB,TAGLN,COL1A1,CARMN,CD63]
</code></pre>
| <python><pandas> | 2023-09-04 05:12:39 | 3 | 1,545 | Anon |
77,034,930 | 12,595,487 | zsh: command not found: psql in mac terminal | <p>I've got this error when I type 'psql' in my terminal : "<code>zsh: command not found: psql</code>".</p>
<p>i only got this when I open <code>~/.zshrc</code> :</p>
<ul>
<li><code>export PATH=$PATH:/Applications/Postgres.app/Contents/Versions</code></li>
</ul>
<p>I've installed postgresql version 11-15 on my Mac.</p>
<p>Now what do I do to run psql without any error?</p>
| <python><postgresql><zsh><psql> | 2023-09-04 03:28:27 | 1 | 657 | Asyraf |
77,034,768 | 6,017,248 | Web scraping multiple paragraphs in an Arabic website that has <p> and <font> HTML elements | <h1>Context</h1>
<p>I have been doing this small web scraping project to practice and polish my coding skills. I had an idea that I could preserve some of my grandpa's work and save it somewhere and keep up his legacy in the future when it doesn't exist anymore on the site. So I'm doing my part where I can do what I can and share it with my family.</p>
<p>I'm using Python to do this project and using urllib without the use of other frameworks like BeautifulSoup or Selenium. The reason I'm doing this is to have a strong principle in coding in general, and slowly build up to the best way and the reasons behind it. Plus, I want to learn my libraries too, so I believe this is a good way to learn in general. Eventually (not now, though), I will opt-in to a BeautifulSoup in a different project.</p>
<h1>Problem</h1>
<p>I have a parser that checks for paragraphs and saves them into a list. So whenever there is a <code><p></code> and <code></p></code>, I would put the information inside of my list and continue. Now, I do this for every title it finds, but I found a small bug for a specific type of articles. When the article has a <code><font></code> and <code></font></code> compared to the other ones, they are differently structured. I'm trying to check for the font tags, but it seems it is not doing the work as it is supposed to do. For all this, I do inspect element to whatever div is located, and just parse from it.</p>
<h1>Example</h1>
<p>This is my initial <a href="https://alrai.com/article/1000303/%D9%83%D8%AA%D8%A7%D8%A8/%D9%84%D9%85%D8%A7%D8%B0%D8%A7-%D8%AA%D9%82%D8%B1%D9%8A%D8%B1-%D8%AA%D8%B4%D9%8A%D9%84%D9%83%D9%88%D8%AA-%D8%A5%D8%B0%D9%86" rel="nofollow noreferrer">URL</a>, I parse from the div it starts (<code>div class="item-article-body size-20"</code>) that the is located, and go from there.</p>
<pre><code><div class="item-article-body size-20">
<div class="author-image">
<a href="https://alrai.com/author/19/د-زيد-حمزة">
<img src="https://alrai.com/uploads/authors/19_1635945465.jpg" width="100%" height="100%" alt="د. زيد حمزة">
</a>
</div>
<a href="د. زيد حمزة" class="author-name-a">د. زيد حمزة</a>
لم يكن ضروريا أن ينتظر الشعب البريطاني وغيره من شعوب العالم سبع سنوات حتى يطل عليها تقرير تشيلكوت ويدين توني بلير فالادانة الشعبية – ولو على نطاق محدود – كانت قائمة حتى قبل الحرب على العراق، ولم يكن ضروريا أن يقرأ الناس في كل مكان آلاف الصفحات كي يستوعبوا حجم الخديعة التي أجاد نسج خيوطها رئيس الوزراء البريطاني بالتواطؤ مع رئيس الولايات المتحدة لتبرير تلك الحرب التي اودت بحياة الآلاف من جنود بلديهما وبلغت تكاليفها ارقاما فلكية (اكثر من 3 تريليون دولار) ! كما لم يُرضِ احداً ان يسارع بلير في اليوم التالي لصدور التقرير بمواجهة الصحافة فيعترف بالخطأ لكنه يصر على أنه لولا غزو العراق لكان العالم الآن في حال أسوأ مع ان الواقع الماثل عكس ذلك تماما ومن مضاعفاته أن الارهاب الاعمى قد وصل الى الغرب نفسه ! لا بل إن بلير أهان الضمير العالمي حين لم يعترف بالذنب او يعتذر – مجرد اعتذار – عن التسبب في قتل وتشريد ملايين العراقيين وتدمير دولتهم وتمزيق بلدهم وإشعال فتنة طائفية فيها لا يعلم احد متى تنطفئ نارها.<br><br>صحيح أن لغة التقرير ليست جازمة في تبيان الأدلة على دخول حرب فتاكة بمبررات غير صحيحة على الاطلاق، فلا العراق كان يملك أسلحة دمار شامل ولا صدام كانت له علاقة بالقاعدة أو بن لادن، لذلك لم نجد وزارة العدل البريطانية تتحرك لاقامة الدعوى ضد توني بلير لمحاكمته امام القضاء البريطاني ولم تتحرك حكومة العراق (!) كي تأخذه الى محكمة العدل الدولية أو محكمة الجنايات الدولية كما وقفت مكتوفة اليدين منظمات حقوق الانسان ( أمنستي انترناشونال وهيومان رايتس ووتش على سبيل المثال ) وكذلك المفوضية الدولية لحقوق الانسان في الأمم المتحدة ! أما الديمقراطية البريطانية ، وهي أم الديمقراطيات كما يقال، فسوف يخجل برلمانها من عدم قدرته استنادا الى هذا التقرير على محاسبة توني بلير وتحميله مسؤولية الارواح ( ارواح الجنود البريطانيين على الأقل ) التي ازهقت عبثا وبهتانا رغم نصيحة المخابرات البريطانية بأن غزو العراق سوف لن يقضي على الارهاب بل يؤدي الى مزيد منه ورغم تقرير المخابرات الاميركية بناء على طلب من البنتاغون والذي أفاد ايضا بان الارهاب سوف يستشري ويتسع.. أما اللغة المائعة للتقرير - كما قالت كثير من الصحف العالمية – فربما كانت وراء تأخير صدوره كل هذه السنوات الطويلة ، في محاولة من قوى ضاغطة عديدة من اجل ان يأتي في صيغة تجعل رئيس الوزراء توني بلير قادراً على الافلات من العقاب وكذا الرئيس جورج دبليو بوش ونائبه ديك تشيني ووزير دفاعه دونالد رامسفيلد الذين استخدم بعض الكتاب في وصفهم نعوتاً جارحة وهم يتساءلون عن سبب حماسهم في شن الحرب على العراق الذي أنكر وجود اسلحة الدمار الشامل لديه في حين جبنوا كل الوقت عن التصدي لكوريا الشمالية التي تملك مثل هذه الاسلحة وتعلن عن وجودها في حوزتها ( حتى ان بعضهم ذكّر بباكستان! ) ، وقبل ذلك كله لم ينبسوا ببنت شفة وهم يعلمون علم اليقين بان اسرائيل تملك مائتي قنبلة ذرية على الاقل..! وقد سخر الكتاب كذلك من ادعاءات اولئك الزعماء الغربين بان الحرب كانت من اجل التخلص من دكتاتورية صدام وتوفير الديمقراطية للشعب العراقي فالعالم كله يعرف أن اكثر حلفائهم في المنطقة العربية لا يحكمون بالديمقراطية ! وأثبت بعض الكتاب ان هدف الحرب تدمير كيانات عديدة في المنطقة خدمة للحليفة الاستراتيجية اسرائيل وكان من نتائجها الكارثية ايضاً اقتتال طائفي وارهاب لم يعرف العالم مثيلاً لفظاعته..<br><br>وبعد.. فما لم تشر له معظم التعليقات هو أن المستفيد الأكبر من شن الحرب كان المجمع العسكري الصناعي من خلال البنتاغون وال <span dir="LTR">FED</span> وصفقات الأسلحة.. بالمليارات يومياً !<br><br>****<br><br>تنويه: أخطأتُ في مقال الاسبوع الماضي بان ذكرت أن المعابد البوذية تدعى بادوغا <span dir="LTR">Padoga</span> والصحيح أنها باغودا <span dir="LTR">Pagoda</span> ولقد لفت نظري لذلك الصديق حسان بدران (رفيق الرحلة الى بورما وفيتنام) وإذ أشكره فاني اعتذر للقراء وأعفي (الرأي) من مسؤوليتها عن هذا الخطأً..<br><br>
</div>
</code></pre>
<h1>Code</h1>
<pre><code>import urllib.parse
def paragraphs(url):
#Note: if I want to look for paragraphs HTML elements, I would change it to <p> and </p> instead of font (that part works). Only issue is when it comes to the font and how the HTML is structured.
content = html_content(url)
paragraphs = []
target_element_paragraph_article = '<div class="item-article-body size-20">'
start_index = content.find(target_element_paragraph_article)
if start_index != -1:
start_index += len(target_element_paragraph_article)
content_paragraph = content[start_index:].strip()
paragraph_start = content_paragraph.find('<font>')
while paragraph_start != -1:
paragraph_end = content_paragraph.find('<font>', paragraph_start)
if paragraph_end != -1:
paragraph = content_paragraph[paragraph_start + len('<p>'):paragraph_end].strip()
paragraphs.append(paragraph)
paragraph_start = paragraph_end + len('</font>')
else:
print("Closing </font> tag not found")
break
else:
print("Font element was not found")
return paragraphs
</code></pre>
<p>If anything, let me know if you have questions. I'm happy to answer them back :)</p>
| <python><html><web-scraping><urllib> | 2023-09-04 02:14:11 | 2 | 398 | Zeid Tisnes |
77,034,675 | 21,575,627 | Finding the minimum cost for 'm' compatible elements for group 1 and group 2 (algorithm) | <p>Here is a problem statement. I recently had an interview question regarding this:</p>
<blockquote>
<p>given arrays compatible1, compatible2, and cost of length n >= 1. cost[i] represents the cost of element i. the respective compatible[i] == 1 if compatible with that group and 0 otherwise. also given min_compatible, which is the minimum number of elements to be compatible for each. for example, if item is compatible with both, it counts toward the quota for both. return the minimum cost to fulfill the compatibility requirement.</p>
</blockquote>
<p>My idea was: we either are compatible with one of group1, group2, or both (disjoint). pick the minimum cost that's compatible with both if both still need an element and that one is less than the minimum of the non-intersect ones combined. otherwise, just pick the minimum you need.</p>
<p>My solution looked like this (Python):</p>
<pre><code>from heapq import heappush, heappop
def getMinCost(cost, compatible1, compatible2, min_compatible):
# set of indices compatible with each
c1 = {i for i,c in enumerate(compatible1) if c == 1}
c2 = {i for i,c in enumerate(compatible2) if c == 1}
# not enough to fulfill reqs
if len(c1) < min_compatible or len(c2) < min_compatible:
return -1
# make disjoint -> one, the other, or both
c1, c2, c3 = c1 - c2, c2 - c1, c2 & c1
# fill the disjoint heaps
heap1 = []
heap2 = []
heap3 = []
for i,c in enumerate(cost):
if i in c3:
heappush(heap3, c)
elif i in c2:
heappush(heap2, c)
elif i in c1:
heappush(heap1, c)
# handle edge case (one empty early)
heappush(heap1, float('inf'))
heappush(heap2, float('inf'))
heappush(heap3, float('inf'))
# amount fulfilling each
a1 = 0
a2 = 0
# minimum cost counter
minCost = 0
# both are below threshold, prioritize intersection
while a1 < min_compatible and a2 < min_compatible:
# if first cond true, advantageous to take the one
# that fulfills both
if heap1[0] + heap2[0] >= heap3[0]:
minCost += heappop(heap3)
a1 += 1
a2 += 1
elif heap1[0] <= heap2[0]:
minCost += heappop(heap1)
a1 += 1
else:
minCost += heappop(heap2)
a2 += 1
# deal with leftovers
while a1 < min_compatible:
if heap1[0] <= heap3[0]:
minCost += heappop(heap1)
else:
minCost += heappop(heap3)
a2 += 1
a1 += 1
while a2 < min_compatible:
if heap2[0] <= heap3[0]:
minCost += heappop(heap2)
else:
minCost += heappop(heap3)
a1 += 1
a2 += 1
return minCost
</code></pre>
<p>I succeeded in 8/15 of the test cases, but not all (and the inputs were hidden). Where did I go wrong? I cannot see it and am looking to (1) be aware of my mistake (2) not repeat it in the future.</p>
<p>The errors were all incorrect output.</p>
| <python><algorithm><set><heap><disjoint-sets> | 2023-09-04 01:17:12 | 1 | 1,279 | user129393192 |
77,034,664 | 3,654,852 | Call a defined function in lambda in Python | <p>I am trying to understand the mechanics of user defined functions (UDF) and the difference that using a lambda function makes when creating a new column in a dataframes, based on multiple conditions across all rows in two more more columns.</p>
<p>I tried a few different ways, but only some of it works. I'd like to understand why the other parts of the code don't work and what I need to change to make it work. In particular, I need an efficient way to call a UDF to create a new column in a large dataframe. It's easier to communicate the idea and issues using this smaller dataframe.</p>
<p>Define the DF</p>
<pre><code>df = pd.DataFrame({'A': ['foo', 'bar', 'baz', 'foo'],
'B': ['qux', 'quux', 'quuz', 'xyz']})
df
</code></pre>
<p>First, the lines that do work:</p>
<pre><code>df['col2'] = (df['A'] == 'foo') & (df['B'] == 'qux' )
df = df.assign(col3 = lambda x: (df['A'] == 'foo') & (df['B'] == 'qux' ))
</code></pre>
<p>The resulting columns col2 and col3 are correct; only the first row is True, the rest false as expected. However, the conditions can become more complicated as there could be many more columns (in the real code; the concept would be the same, so easier to use this example here) - so I thought I'd create a separate UDF and try to call it. This doesn't work.</p>
<pre><code>def test(df):
if ( (df['A'] == 'foo') & (df['B'] == 'qux' ) ).any():
x = True
else:
x = False
return x
</code></pre>
<p>The results on 'col1' and col4 are incorrect - they both return TRUE for all rows. I'm not sure why and would appreciate some guidance here.</p>
<pre><code>df['col1'] = test(df)
df = df.assign(col4 = lambda x: test(df))
</code></pre>
<p>Again, the only reason I'm using a separate UDF is that I anticipate the filtering conditions to get more convoluted.....so the code is cleaner if I use a different function and just call it in. Seems like I'll have to use a loop for the DF....but that will get so inefficient with a large data set.</p>
<p>I also tried this, but the results are unchanged:</p>
<pre><code>df = df.assign(col5 = df.apply(lambda x: test(df), axis=1))
</code></pre>
<p>Here's a picture of the output; only the highlighted yellow columns here are correct. Not sure why the other lines of code don't work.</p>
<p><a href="https://i.sstatic.net/54JG9.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/54JG9.png" alt="code output" /></a></p>
<p>Update: this worked. Now, the function correctly looks at the condition for each row and labels them (peak, bad, offpeak) correctly.</p>
<pre><code>def test3(row):
x = True
if (( row['A'] == 'foo') & (row['B'] == 'qux') ):
x = False
elif ( (row['A'] == 'foo') & (row['B'] == 'xyz') ):
x = 'NA'
return x
df['col'] = df.apply(lambda x: test3(x), axis=1)
</code></pre>
| <python><dataframe><lambda> | 2023-09-04 01:11:22 | 0 | 803 | user3654852 |
77,034,517 | 5,953,720 | Why does loc adds a NaN row in my Pandas Dataframe? | <p>I am using <a href="https://github.com/subashgandyer/datasets/blob/main/Real%20estate.csv" rel="nofollow noreferrer">this csv</a>.</p>
<pre><code>import pandas as pd
import numpy as np
real_estate = pd.read_csv('real_estate.csv',index_col=0)
buckets = pd.cut(real_estate['X2 house age'],4,labels=False).to_numpy()
for i in range(len(real_estate['X2 house age'])):
real_estate.loc[i,'X2 house age'] = buckets[i]
</code></pre>
<p>Why if I do this a new row is added at the end of the dataset? A row with all NaN except 'X2 House Age'.... I'm must doing something wrong but I don't know why.</p>
| <python><pandas><numpy><categorization><discretization> | 2023-09-03 23:56:30 | 1 | 1,517 | Allexj |
77,034,494 | 219,153 | Small value artifacts from applying scipy.signal.convolve | <p>This Python 3.11.5 script:</p>
<pre><code>import numpy as np
from skimage.io import imread
from scipy.signal import convolve
image = np.flipud(imread('conv-test.bmp').astype(np.float32))
con = convolve(image, np.ones((3, 3))/9, mode='valid')
print(image.min())
print(np.logical_and(image > 0, image < 1).any())
print(np.logical_and(con > 0, con < 0.00001).any())
</code></pre>
<p>produces:</p>
<pre><code>0.0
False
True
</code></pre>
<p>How is it possible to get positive values smaller than 0.00001? Shouldn't 1/9 be the smallest positive value produced by this convolution?</p>
<p><a href="https://i.sstatic.net/57VBB.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/57VBB.png" alt="enter image description here" /></a></p>
| <python><numpy><scipy><convolution> | 2023-09-03 23:40:53 | 1 | 8,585 | Paul Jurczak |
77,034,404 | 21,183,551 | jsonbin API problems with Swift | <p>I'm building a little app that talks to the <a href="https://jsonbin.io" rel="nofollow noreferrer">jsonbin</a> API with Alamofire. Their API docs cover using Python to "put" or "update" the JSON file data extensively in Python. I'm working on doing that in Swift 5.</p>
<p>My problem is when I attempt to use a put command to send data to a specific file. See code:</p>
<pre><code>import AlamoFire
func sendData()
{
let headers: HTTPHeaders = [
"Content-Type": "application/json",
"X-Master-Key": "x-x-x-x-x-x-x-x",
"X-Bin-Meta": "false"
]
let queue = DispatchQueue(label: "com.app.name", qos: .background, attributes: .concurrent)
do{
var testData = [
"title": "My Test Task",
"date": "My Date",
"complete": "Completion Status",
"assignee": "Bob Jones"
]
AF.request("https://api.jsonbin.io/v3/b/x-x-x-x-x-x-x", method: .put, parameters: testData, headers: headers).validate().responseJSON(queue: queue) { response in
switch response.result {
case .success(_):
print("Success!")
case .failure(let error):
print(error)
}
}
}
catch
{
print("Error occured.")
}
}
</code></pre>
<p>I'm trying to send a simple JSON structure over. The error I receive is this:</p>
<pre><code>esponseValidationFailed(reason: Alamofire.AFError.ResponseValidationFailureReason.unacceptableStatusCode(code: 400))
</code></pre>
<p>Their API docs say that an error 400 typically means:</p>
<ul>
<li><p>You need to pass Content-Type set to application/json</p>
</li>
<li><p>Invalid Bin Id provided</p>
</li>
<li><p>Bin (JSON Data) cannot be blank</p>
</li>
</ul>
<p>I have verified all of these requirements are correct.</p>
<p>Here is functioning Python code as per their docs:</p>
<pre><code>import requests
url = 'https://api.jsonbin.io/v3/b/x-x-x-x-x-x'
headers = {
'Content-Type': 'application/json',
'X-Master-Key': 'x-x-x-x-x-x-x'
}
data = {"sample": "Hello World"}
req = requests.put(url, json=data, headers=headers)
print(req.text)
</code></pre>
<p>Is there something I'm missing? Are the data types different? Is the <code>testData</code> Swift variable different than the <code>data</code> Python variable? How might I go about "putting" data to the RESTful API with Swift and Alamofire 5?</p>
<p>Thanks!</p>
| <python><json><swift><alamofire><alamofire5> | 2023-09-03 22:48:10 | 1 | 641 | Ars_Codicis |
77,034,126 | 2,743,931 | Python setup.py with src directory | <p>I have a simple project folder which looks like this:</p>
<pre><code>.
├── setup.py
├── src
├── __init__.py
└── pricing_functions.py
</code></pre>
<p>and I want to make it an installable package.</p>
<p>What I <em>want</em> is to have the package named <code>pricer</code> and have the actual code taken from the <code>src</code> directory (and I don't want to rename the <code>src</code> directory).</p>
<p>So in python I want to be able to call:</p>
<pre><code>from pricer import pricing_functions
</code></pre>
<p>My <code>setup.py</code> file looks like this:</p>
<pre><code>from setuptools import setup, find_packages
setup(
name='pricer',
version='0.1',
python_requires='>=3.7, <4',
packages=find_packages('src'),
package_dir={'':'src'},
install_requires=[
'QuantLib',
'matlab-tictoc',
'more-itertools',
'pandas>=1.4',
'numpy>=1.14.5',
]
)
</code></pre>
<p>However when I install the package in virtualnv via
<code>python setup.py install</code>
I can't make the above import. But I can do
<code>from src import pricing_functions</code> - which means my package is installed but with the name of the folder.</p>
<p>What should I change to call it a <code>pricer</code>?</p>
| <python><python-import><setuptools><setup.py><python-packaging> | 2023-09-03 20:49:16 | 0 | 312 | user2743931 |
77,034,027 | 6,653,602 | How to update where the files are stored in Django app | <p>I have a Django app that contains multiple models with FileField. I am saving by default every file directly in the Media folder. But as the app grew larger also Media folder became bigger. Now my idea is to move the files into separate folders split by models. So I am wondering what is the best practice when it comes to this?
Shall I move the files to separate folders, then manually update every file location in the Database and then update Filefield path for every model? Or is there better approach?</p>
| <python><django> | 2023-09-03 20:13:41 | 1 | 3,918 | Alex T |
77,033,994 | 11,686,518 | Column-wise sum of nested list | <p>Is there a more pythonic or more simple way to accomplish this?</p>
<p>I am taking the column-wise sum of items in a nested list. I have a working example but I'm sure nested loops are not the way to do. There has to be something, maybe in NumPy or something, that already does this?</p>
<p>So it's the sum of the first elements in each nested list, the sum of the second elements in each nested list, etc...</p>
<pre><code>list_a = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
def sum_columns(nested_list):
col_sums = []
col_len = len(list_a[0])
for col in range(col_len):
col_sum = 0
for row in list_a:
col_sum += row[col]
col_sums.append(col_sum)
return col_sums
sum_columns(list_a)
>> [12, 15, 18]
</code></pre>
<p>I also tried list comprehensions because I think that would be faster but the logic of it seems too complicated because of the nested loops and I was not able to get that to work.</p>
| <python><python-3.x><numpy><nested-lists> | 2023-09-03 20:04:30 | 1 | 1,633 | Jesse Sealand |
77,033,934 | 12,300,981 | How to convert a 3D plot into a 2D filled contour | <p>I have a 3D plot that looks quite nice, and I'd like to convert this to a 2D filled contour plot, but I'm not quite sure how to do that. Here is my setup</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()
ax = plt.axes(projection='3d')
x=np.array([0.3, 0.304, 0.3, 0.3, 0.304, 0.308, 0.308, 0.3, 0.304, 0.312, 0.308, 0.3, 0.312, 0.304, 0.316, 0.304, 0.312, 0.3, 0.308, 0.32, 0.316, 0.32, 0.3, 0.308, 0.304, 0.312, 0.316, 0.324, 0.304, 0.312, 0.316, 0.3, 0.328, 0.324, 0.308, 0.32, 0.33199999999999996, 0.3, 0.304, 0.324, 0.32, 0.328, 0.308, 0.316, 0.312, 0.304, 0.3, 0.33199999999999996, 0.33599999999999997, 0.32, 0.324, 0.328, 0.312, 0.308, 0.316, 0.304, 0.33199999999999996, 0.33999999999999997, 0.308, 0.33599999999999997, 0.3, 0.32, 0.328, 0.316, 0.312, 0.324, 0.312, 0.308, 0.33999999999999997, 0.33199999999999996, 0.3, 0.304, 0.344, 0.33599999999999997, 0.32, 0.324, 0.316, 0.328, 0.316, 0.33599999999999997, 0.308, 0.304, 0.33999999999999997, 0.3, 0.312, 0.33199999999999996, 0.344, 0.348, 0.32, 0.328, 0.324, 0.3, 0.316, 0.308, 0.33199999999999996, 0.312, 0.33599999999999997, 0.348, 0.344, 0.32, 0.304, 0.33999999999999997, 0.352, 0.328, 0.324, 0.32, 0.348, 0.33199999999999996, 0.352, 0.324, 0.33599999999999997, 0.304, 0.33999999999999997, 0.356, 0.312, 0.308, 0.316, 0.344, 0.3, 0.328, 0.344, 0.328, 0.308, 0.33199999999999996, 0.312, 0.33999999999999997, 0.316, 0.32, 0.324, 0.356, 0.304, 0.33599999999999997, 0.3, 0.36, 0.352, 0.348, 0.344, 0.304, 0.316, 0.348, 0.324, 0.33599999999999997, 0.32, 0.33199999999999996, 0.328, 0.352, 0.33999999999999997, 0.356, 0.312, 0.36, 0.308, 0.308, 0.328, 0.352, 0.33999999999999997, 0.348, 0.33199999999999996, 0.32, 0.36, 0.312, 0.344, 0.33599999999999997, 0.316, 0.324, 0.356, 0.33199999999999996, 0.348, 0.36, 0.33999999999999997, 0.324, 0.316, 0.328, 0.32, 0.312, 0.33599999999999997, 0.344, 0.356, 0.352, 0.33599999999999997, 0.33199999999999996, 0.36, 0.316, 0.32, 0.33999999999999997, 0.344, 0.356, 0.352, 0.328, 0.324, 0.348, 0.33599999999999997, 0.33199999999999996, 0.33999999999999997, 0.344, 0.324, 0.348, 0.352, 0.32, 0.356, 0.36, 0.328, 0.344, 0.33999999999999997, 0.33599999999999997, 0.33199999999999996, 0.324, 0.328, 0.352, 0.36, 0.348, 0.356, 0.344, 0.33599999999999997, 0.33999999999999997, 0.33199999999999996, 0.348, 0.352, 0.36, 0.356, 0.328, 0.33999999999999997, 0.33199999999999996, 0.352, 0.33599999999999997, 0.344, 0.348, 0.36, 0.356, 0.352, 0.348, 0.33999999999999997, 0.33599999999999997, 0.356, 0.344, 0.36, 0.33999999999999997, 0.344, 0.348, 0.36, 0.356, 0.352, 0.352, 0.344, 0.348, 0.356, 0.36, 0.36, 0.352, 0.356, 0.348, 0.352, 0.36, 0.356, 0.356, 0.36, 0.36])
y=np.array([0.0, 0.0, 0.004, 0.008, 0.004, 0.0, 0.004, 0.012, 0.008, 0.0, 0.008, 0.016, 0.004, 0.012, 0.0, 0.016, 0.008, 0.02, 0.012, 0.0, 0.004, 0.004, 0.024, 0.016, 0.02, 0.012, 0.008, 0.0, 0.024, 0.016, 0.012, 0.028, 0.0, 0.004, 0.02, 0.008, 0.0, 0.032, 0.028, 0.008, 0.012, 0.004, 0.024, 0.016, 0.02, 0.032, 0.036000000000000004, 0.004, 0.0, 0.016, 0.012, 0.008, 0.024, 0.028, 0.02, 0.036000000000000004, 0.008, 0.0, 0.032, 0.004, 0.04, 0.02, 0.012, 0.024, 0.028, 0.016, 0.032, 0.036000000000000004, 0.004, 0.012, 0.044, 0.04, 0.0, 0.008, 0.024, 0.02, 0.028, 0.016, 0.032, 0.012, 0.04, 0.044, 0.008, 0.048, 0.036000000000000004, 0.016, 0.004, 0.0, 0.028, 0.02, 0.024, 0.052000000000000005, 0.036000000000000004, 0.044, 0.02, 0.04, 0.016, 0.004, 0.008, 0.032, 0.048, 0.012, 0.0, 0.024, 0.028, 0.036000000000000004, 0.008, 0.024, 0.004, 0.032, 0.02, 0.052000000000000005, 0.016, 0.0, 0.044, 0.048, 0.04, 0.012, 0.056, 0.028, 0.016, 0.032, 0.052000000000000005, 0.028, 0.048, 0.02, 0.044, 0.04, 0.036000000000000004, 0.004, 0.056, 0.024, 0.06, 0.0, 0.008, 0.012, 0.02, 0.06, 0.048, 0.016, 0.04, 0.028, 0.044, 0.032, 0.036000000000000004, 0.012, 0.024, 0.008, 0.052000000000000005, 0.004, 0.056, 0.06, 0.04, 0.016, 0.028, 0.02, 0.036000000000000004, 0.048, 0.008, 0.056, 0.024, 0.032, 0.052000000000000005, 0.044, 0.012, 0.04, 0.024, 0.012, 0.032, 0.048, 0.056, 0.044, 0.052000000000000005, 0.06, 0.036000000000000004, 0.028, 0.016, 0.02, 0.04, 0.044, 0.016, 0.06, 0.056, 0.036000000000000004, 0.032, 0.02, 0.024, 0.048, 0.052000000000000005, 0.028, 0.044, 0.048, 0.04, 0.036000000000000004, 0.056, 0.032, 0.028, 0.06, 0.024, 0.02, 0.052000000000000005, 0.04, 0.044, 0.048, 0.052000000000000005, 0.06, 0.056, 0.032, 0.024, 0.036000000000000004, 0.028, 0.044, 0.052000000000000005, 0.048, 0.056, 0.04, 0.036000000000000004, 0.028, 0.032, 0.06, 0.052000000000000005, 0.06, 0.04, 0.056, 0.048, 0.044, 0.032, 0.036000000000000004, 0.044, 0.048, 0.056, 0.06, 0.04, 0.052000000000000005, 0.036000000000000004, 0.06, 0.056, 0.052000000000000005, 0.04, 0.044, 0.048, 0.052000000000000005, 0.06, 0.056, 0.048, 0.044, 0.048, 0.056, 0.052000000000000005, 0.06, 0.06, 0.052000000000000005, 0.056, 0.06, 0.056, 0.06])
z=np.array([95.04597652659395, 93.07169300791817, 86.41091378436298, 78.34438186919142, 84.28293560208068, 90.99430316168865, 82.05075271093197, 70.81956500179922, 76.09555746842769, 88.80946213542661, 73.74247054741866, 63.814701759030804, 79.70713086816829, 68.4804576360916, 86.50492808734144, 61.411971344204396, 71.27993747341829, 57.30367846300854, 66.04015177478145, 84.07501743344253, 77.24301883685469, 74.65362436130224, 51.26423750067391, 58.91207005961288, 54.86318852178682, 63.49153397778519, 68.6991473720035, 81.50849542102088, 48.8094605989559, 56.31211751844223, 60.83162919739374, 45.67567310972991, 78.7945025104922, 71.92736246929788, 52.33202775655146, 65.99398045254483, 75.9227956237361, 40.51568403157141, 43.22761997937239, 63.15759412126584, 58.05355658264885, 69.05560979875929, 46.272987182375566, 53.60665663794348, 49.70877412288789, 38.09431844582127, 35.76611318237437, 66.02941761913569, 72.88105942465431, 50.794014788290504, 55.15315977444494, 60.1826102793514, 43.65339424937394, 40.70815913994665, 46.99112474144888, 33.39135870389347, 57.06201132927449, 69.65537451933291, 35.6145715150264, 62.83835882162572, 31.40773179439253, 44.17796418876675, 52.12445158267965, 40.952566664906996, 38.11850878026559, 47.86983942422426, 33.07706500252916, 30.968759803924296, 59.472616777191334, 48.96396982344986, 27.42232365576576, 29.095469972744016, 66.23369927283454, 53.78907408633386, 38.16920129740417, 41.26718319757395, 35.460618219452655, 44.83267388998538, 30.486209186684196, 45.66877097031951, 26.7492079741212, 25.1879876184327, 50.357833903749956, 23.793264961588868, 28.503632233000594, 41.68143865195456, 55.92411681399547, 62.602040414153436, 32.737080106531906, 38.262204180250805, 35.307079275214086, 20.504965629265598, 26.001941824443026, 22.934787566648367, 35.16414842828048, 24.375915837974958, 38.417647482512585, 52.183223475400425, 46.764236521960356, 27.847695627594547, 21.651951344041745, 42.23745078550662, 58.7486635658336, 32.370568277953886, 29.953599826849384, 23.472939828370624, 43.0064416381895, 29.365624602515823, 48.245841005914286, 25.17053808625563, 31.979981680064885, 18.467992104439183, 35.045344071560066, 54.66218711883382, 20.669937446692995, 19.505408609505, 21.983371919011866, 38.67214321103867, 17.539733461223655, 27.117574924924078, 31.572812873998643, 22.466032542732094, 16.443245776120413, 24.2409420001134, 17.365732951566233, 28.718698301383473, 18.405920693287136, 19.584790929537345, 20.927274270297637, 44.10975175851463, 15.621134390166244, 26.303364418342934, 14.884854891742494, 50.33532348260853, 39.08801072397429, 34.978370361105966, 25.396357763334883, 13.093794646214183, 15.245360559256401, 28.01403749316034, 17.192124683229846, 21.339430775662887, 16.155565837989112, 19.74917859564828, 18.380058183613784, 31.168656484960362, 23.199805388379076, 35.017572733654454, 14.44199394670105, 39.77998854987883, 13.729070264143143, 11.346911104669699, 14.826597675743553, 24.39190718008288, 18.434180461079755, 22.034810233530056, 15.851362438599907, 13.161307980429406, 30.815540283692425, 11.880002954924821, 20.077222490194877, 17.041644543286573, 12.480819689160308, 13.937187381696818, 27.26500078493244, 12.51094881156381, 16.966980870415316, 23.303152376399595, 14.370711153030173, 11.135186711010434, 10.090487273914302, 11.77391829747407, 10.578674928530958, 9.66079764755596, 13.367708069288115, 15.555350065743474, 20.740782967906497, 18.667665977595888, 10.277243048965051, 9.693623758996056, 17.113566938669496, 8.055866920180963, 8.384375391031437, 10.962604505357024, 11.773924988908062, 15.34327076939705, 13.913536319438865, 9.192626639560688, 8.760402036693474, 12.743127231680926, 7.732751057134466, 7.36675841687418, 8.165298800642773, 8.680802847878777, 6.787933025877766, 9.300489076468914, 10.05339503288019, 6.557384688690587, 10.978653802485539, 12.131123230834657, 7.055085859022233, 6.22731794094746, 5.937938719418917, 5.699224545702991, 5.500815523085859, 5.195664664070231, 5.334932485979189, 7.0171502171500615, 8.249070447101744, 6.580911352886527, 7.561330476433264, 4.367976775112049, 4.143264099643755, 4.241684382135572, 4.066603365531463, 4.530455892542467, 4.739999538254734, 5.370823105713089, 5.012619143814073, 4.0071751320157984, 3.0409176976014267, 3.037921536588448, 3.1622049587954795, 3.034404773151192, 3.0607972205754965, 3.098909471280704, 3.407285944994312, 3.260238193353411, 2.228405125954436, 2.2403142547782524, 2.301784702795703, 2.3435558143108883, 2.237381252011389, 2.2663466711203877, 2.27735590501212, 1.9930746922320377, 1.9480623234072603, 1.9115118902381407, 1.9071495409410206, 1.8831262520810794, 1.8877684267325927, 2.093097490680202, 2.0718660504293087, 2.0726202431163654, 2.141268771079559, 2.2287157638764166, 3.1800800140087624, 2.8008846853966536, 2.960115226464081, 2.6865687087736654, 3.970923041282829, 4.704638756418261, 4.292188345854714, 6.093648447344786, 6.750181957450197, 9.269311560401611])
ax.plot_trisurf(x,y,z,cmap ='viridis')
plt.show()
plt.contourf(np.reshape(x,(int(len(x)**0.5),int(len(x)**0.5))),np.reshape(y,(int(len(x)**0.5),int(len(x)**0.5))),np.reshape(x,(int(len(x)**0.5),int(len(x)**0.5))))
plt.show()
</code></pre>
<p>The 3D plot looks quite nice, but the 2D filled contour is all jagged, and I'm not entirely sure why. The 2D contour plot also appears to be flipped from the 3D counterpart. I suspect this is due to me setting up the <code>contourf</code> improperly, but I cannot see the problem.</p>
<p><img src="https://i.sstatic.net/usHp3.png" alt="3D Plot" /></p>
<p><img src="https://i.sstatic.net/cM4qV.png" alt="2D Plot" /></p>
| <python><arrays><numpy><matplotlib><contourf> | 2023-09-03 19:45:21 | 0 | 623 | samman |
77,033,858 | 12,461,032 | Cannot install stellargraph | <p>I am trying to install <a href="https://stellargraph.readthedocs.io/en/stable/README.html#installation" rel="nofollow noreferrer">stellargraph</a> package. I created a new conda environment with python 3.6 and tried to install it with <code>pip install stellargraph</code> but when I try to write <code>import stellargraph</code> in jupyter, it says <code>ModuleNotFoundError: No module named 'stellargraph'</code>.</p>
<p>I also tried it with PyCharm to create a new conda enironment with python 3.6 and then use its package manager to install stellargraph. It installs successfully but when I import it, I get this error:</p>
<pre><code>Traceback (most recent call last):
File "/home/hossein/Desktop/Univ/Computer/10th/Network/Project/pycharm/main.py", line 1, in <module>
import stellargraph
File "/home/hossein/anaconda3/envs/pycharm/lib/python3.6/site-packages/stellargraph/__init__.py", line 39, in <module>
from stellargraph import (
File "/home/hossein/anaconda3/envs/pycharm/lib/python3.6/site-packages/stellargraph/data/__init__.py", line 26, in <module>
from .loader import from_epgm
File "/home/hossein/anaconda3/envs/pycharm/lib/python3.6/site-packages/stellargraph/data/loader.py", line 23, in <module>
from stellargraph.data.epgm import EPGM
File "/home/hossein/anaconda3/envs/pycharm/lib/python3.6/site-packages/stellargraph/data/epgm.py", line 24, in <module>
import chardet
ModuleNotFoundError: No module named 'chardet'
</code></pre>
| <python><conda><stellargraph> | 2023-09-03 19:24:21 | 1 | 472 | m0ss |
77,033,850 | 913,098 | setting a multi index does not allow access using .loc? | <pre><code>import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
empty_row_index = ("zero_scan")
empty_row_df = pd.DataFrame({c: [None] for c in df.columns})
empty_row_df.index = [empty_row_index]
df2 = pd.concat([empty_row_df, df])result = df2.loc[df2.index[0], :]
</code></pre>
<p>works</p>
<pre><code>import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
empty_row_index = ("zero_scan",)
empty_row_df = pd.DataFrame({c: [None] for c in df.columns})
empty_row_df.index = [empty_row_index]
df2 = pd.concat([empty_row_df, df])result = df2.loc[df2.index[0], :]
</code></pre>
<p>key error.</p>
<p>Notice <code>"zero_scan"</code> vs <code>"zero_scan",</code>.</p>
<p>This is a test program, and I need the <code>"zero_scan",</code> version using multi index.</p>
<p>How to correct the access to the row by index?</p>
| <python><pandas><dataframe><multi-index> | 2023-09-03 19:22:50 | 1 | 28,697 | Gulzar |
77,033,740 | 425,895 | What's the difference between astype("category), categorical() and factorize()? | <p>Python offers many ways to convert a variable to categorical.</p>
<pre><code>import numpy as np
import pandas as pd
mydata = pd.Series(['A', 'B', 'B', 'C'])
mydata
0 A
1 B
2 B
3 C
dtype: object
pd.factorize(mydata) # Outputs a tuple with an array and an index
(array([0, 1, 1, 2], dtype=int64), Index(['A', 'B', 'C'], dtype='object'))
pd.Categorical(mydata) # Outputs a pandas. How do you extract categories?
['A', 'B', 'B', 'C']
Categories (3, object): ['A', 'B', 'C']
mydata.astype('category') # Outputs a series. How do you extract categories?
0 A
1 B
2 B
3 C
dtype: category
Categories (3, object): ['A', 'B', 'C']
</code></pre>
<p>There are more alternatives such as sklearn LabelEncoder and keras to_categorical, which are used with pipelines because they preserve the conversions and allow to reapply them to new data.</p>
<p>Could you please explain the differences, advantages or limitations of these methods, and they different applications: factorize(), categorical() and astype("category")?</p>
<p>For example if I want to use them for a decision tree model or I just want to calculate a frequency table.<br />
Which one is easier to use or more versatile? For example if afterwards I want to modify a category or add a new one or change a value or merge two categories.</p>
| <python><pandas><categorical-data> | 2023-09-03 18:44:45 | 2 | 7,790 | skan |
77,033,675 | 1,020,139 | Why does `pip3 install lxml` on public.ecr.aws/lambda/python:3.11 install a source distribution rather than a (manylinux) wheel? | <p>I'm curious to understand why <code>pip3</code> @ <code>public.ecr.aws/lambda/python:3.11</code> (Python v3.11.4) downloads and install the source distribution of <code>lxml</code> instead of downloading the seemingly compatible manylinux wheel <code>lxml-4.9.3-cp311-cp311-manylinux_2_28_aarch64.whl</code>?</p>
<p><a href="https://pypi.org/project/lxml/#files" rel="nofollow noreferrer">https://pypi.org/project/lxml/#files</a></p>
<p>The above wheel is downloaded e.g. by <code>pip3</code> @ <code>amazonlinux</code> (Python v3.11.2):</p>
<p><a href="https://i.sstatic.net/iaRyn.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/iaRyn.png" alt="enter image description here" /></a></p>
<p><strong>Example</strong>:</p>
<pre><code>$ docker run -ti --rm --user 0 --platform linux/arm64 --entrypoint bash public.ecr.aws/lambda/python:3.11
$ pip3 install lxml
</code></pre>
<p><a href="https://i.sstatic.net/KKXDW.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/KKXDW.png" alt="enter image description here" /></a></p>
| <python><linux><pip><python-poetry><python-wheel> | 2023-09-03 18:26:27 | 1 | 14,560 | Shuzheng |
77,033,643 | 6,440,589 | Converting from local time to UTC in pandas | <p>I am working with pandas dataframes containing local (Chilean) dates and times, <em>e.g.</em>:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>local_time</th>
</tr>
</thead>
<tbody>
<tr>
<td>2/9/2023 23:33</td>
</tr>
<tr>
<td>2/9/2023 23:39</td>
</tr>
<tr>
<td>3/9/2023 1:00</td>
</tr>
<tr>
<td>3/9/2023 1:08</td>
</tr>
</tbody>
</table>
</div>
<p>I used to convert these dates and times to UTC by applying a bulk time shift (<code>pd.Timedelta(4, "h")</code>) to my <strong>local_time</strong> column, but now I would like to account for changes in daylight saving times.</p>
<p>I started using <code>tz_location</code> to specify the time zone before converting to UTC using <code>tz_convert</code>:</p>
<pre><code>import pandas as pd
from datetime import datetime
df = pd.read_csv("Example_dataset.csv")
pd.to_datetime(pd.to_datetime(df['local_time']).apply(lambda x: datetime.strftime(x, '%d-%m-%Y %H:%M:%S'))).dt.tz_localize('America/Santiago').dt.tz_convert('UTC')
</code></pre>
<p>This seems to work on the example dataset provided here: data from September 2, 2023 are shifted by 4 hours, while those from September 3 are shifted by 3 hours.</p>
<pre><code>0 2023-09-03 03:33:00+00:00
1 2023-09-03 03:39:00+00:00
2 2023-09-03 04:00:00+00:00
3 2023-09-03 04:08:00+00:00
</code></pre>
<p>Is this the correct way to proceed or am I missing anything here?</p>
| <python><pandas><datetime><dst> | 2023-09-03 18:18:11 | 1 | 4,770 | Sheldon |
77,033,528 | 22,466,650 | Why can't we use a fill_value when reshaping a dataframe (array)? | <p>I have this dataframe :</p>
<pre><code>df = pd.DataFrame([list("ABCDEFGHIJ")])
0 1 2 3 4 5 6 7 8 9
0 A B C D E F G H I J
</code></pre>
<p>I got an error when trying to reshape the dataframe/array :</p>
<pre><code>np.reshape(df, (-1, 3))
</code></pre>
<p><strong>ValueError: cannot reshape array of size 10 into shape (3)</strong></p>
<p>I'm expecting this array (or a dataframe with the same shape) :</p>
<pre><code>array([['A', 'B', 'C'],
['D', 'E', 'F'],
['G', 'H', 'I'],
['J', nan, nan]], dtype=object)
</code></pre>
<p>Why NumPy can't guess the expected shape by completing the missing values with <code>nan</code>?</p>
| <python><pandas><numpy> | 2023-09-03 17:46:29 | 2 | 1,085 | VERBOSE |
77,033,496 | 4,681,060 | Model returns multiple values during inference, but expected is exactly one output value | <p>I have a tf model of given summary:</p>
<pre><code>Model: "model"
Layer (type) Output Shape Param #
input_1 (InputLayer) [(None, 1024, 9)] 0
conv1d (Conv1D) (None, 1024, 1024) 28672
re_lu (ReLU) (None, 1024, 1024) 0
conv1d_1 (Conv1D) (None, 1024, 64) 196672
re_lu_1 (ReLU) (None, 1024, 64) 0
dense (Dense) (None, 1024, 1024) 66560
dense_1 (Dense) (None, 1024, 1) 1025
Total params: 292,929 Trainable params: 292,929 Non-trainable params: 0
</code></pre>
<p>I've preapred the <code>inputs</code> tensor and it looks like this:</p>
<pre><code><tf.Tensor: shape=(1, 1024, 9), dtype=float64, numpy=
array([[[2.88565600e+04, 2.88415400e+04, 2.88415300e+04, ...,
5.92000000e+02, 2.68717000e+00, 7.75434895e+04],
[2.88415300e+04, 2.88391800e+04, 2.88364700e+04, ...,
3.80000000e+02, 8.36111000e+00, 2.41110700e+05],
[2.88391900e+04, 2.88597400e+04, 2.88391800e+04, ...,
4.94000000e+02, 1.46990300e+01, 4.23977006e+05],
...,
[2.96478600e+04, 2.96478600e+04, 2.96478600e+04, ...,
2.24000000e+02, 3.16775000e+00, 9.39170402e+04],
[2.96478700e+04, 2.96456900e+04, 2.96422200e+04, ...,
4.22000000e+02, 3.72039000e+00, 1.10288124e+05],
[2.96457000e+04, 2.96389700e+04, 2.96389700e+04, ...,
2.69000000e+02, 1.79933000e+00, 5.33333054e+04]]])>
</code></pre>
<p>I expect only single number output, but when I try to use the model and feed it with the above input i get 1024 predictions instead of 1:</p>
<pre><code>model.call( inputs, training=False, mask=None)
<tf.Tensor: shape=(1, 1024, 1), dtype=float32, numpy=
array([[[28849.605],
[28859.383],
[28880.047],
...,
[29644.61 ],
[29644.61 ],
[29667.752]]], dtype=float32)>
</code></pre>
<p>Here, you can see that it returns 1024 predictions, but the model was trained to return exacly one number, expected is only one prediction from the provided input. How should I properly feed the input so that I get the proper working of the network and one prediction? Is there some problem with the dimensionality of the input?</p>
| <python><tensorflow><conv-neural-network> | 2023-09-03 17:35:40 | 0 | 6,442 | Krzysztof Cichocki |
77,033,384 | 6,929,467 | Pytest MonkeyPatch | <p>I am trying to patch <code>PyMongoClient</code> that has multiple nested commands that need to be patched.</p>
<p>One example would be instantiating the <code>PyMongoClient</code> (i.e. <code>client = PyMongoClient().db</code> then doing a command like <code>client.command('ping)</code></p>
<p>Here is an example of what I have tried,</p>
<pre><code>class DbMock:
def command(self, *args, **kwargs):
return True
class MockPyMongoClient:
def __init__(self, *args, **kwargs) -> None:
pass
@property
def db(self, *args, **kwargs):
return DbMock()
mp.setattr('pymongo.MongoClient', lambda *args, **kwargs: MockPyMongoClient)
</code></pre>
<p>Main code c something like,</p>
<pre><code>py_mongo_db = pyMongoClient(settings.MONGODB_HOST).db
try:
py_mongo_db.command('ping')
except Exception:
raise "MongoDB does not seem to be running, or is not healthy."
)
print "MongoDB Healthy"
</code></pre>
<p>This creates the following error output:</p>
<pre><code>AttributeError: 'property' object has no attribute 'command'
</code></pre>
| <python><mongodb><pytest> | 2023-09-03 17:10:49 | 1 | 2,720 | innicoder |
77,033,348 | 2,678,074 | How to find directory in realtion to Pycharm project root? | <p>I simply created a new project in Pycharm, and added directory <em>cfg</em> to it. I simply want to check in my <em>main.py</em> if in fact, my <em>cfg</em> directory is where it supposed to be, just want to check if hierarhy of my projest from within python (i wrote in pycharm, but it may be my code will be exported somewhere else and I want to make sure my paths wont be affected). I expected Pycharm to add some environment variable that i can use as project root, but found nothing. Can you tell me, what best practices are in such cases?
Next step will be to check if config yaml/json file is inside such directory.</p>
| <python><path><pycharm> | 2023-09-03 17:03:02 | 2 | 845 | user2678074 |
77,033,163 | 15,673,147 | What's the difference about using Langchain's Retrieval with .from_llm or defining LLMChain? | <p>In the documentation, I've seen two patterns of construction and I'm a bit confused about the difference between both. I don't know if there's any actual difference or if just the same thing in different approach.</p>
<p>Example 1 (using .from_llm):</p>
<pre><code>model = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0.3)
embeddings = OpenAIEmbeddings()
vectordb = Chroma(embedding_function=embeddings, persist_directory=directory)
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
qa = ConversationalRetrievalChain.from_llm(
model,
vectordb.as_retriever(),
condense_question_prompt=CUSTOM_QUESTION_PROMPT,
memory=memory
)
query = "What did the president say about Ketanji Brown Jackson"
result = qa({"question": query})
</code></pre>
<p>Example 2 (no method, with LLMChain):</p>
<pre><code>llm = OpenAI(temperature=0)
question_generator = LLMChain(llm=llm, prompt=CONDENSE_QUESTION_PROMPT)
doc_chain = load_qa_with_sources_chain(llm, chain_type="map_reduce")
chain = ConversationalRetrievalChain(
retriever=vectorstore.as_retriever(),
question_generator=question_generator,
combine_docs_chain=doc_chain,
)
chat_history = []
query = "What did the president say about Ketanji Brown Jackson"
result = chain({"question": query, "chat_history": chat_history})
</code></pre>
<p>I can see that in the second example I'm defining the model and prompt separately as a question_generator that I pass as an argument in the chain aftwerwards. Thus, I'm passing a doc_chain.</p>
<p>But I've some abstract doubts, such as what's underneath, what are the consequences, when should I use one or another, if it's the same output etc. Mostly, is the first simple example somehow using a question_generator or a doc_chain which are omitted in the code?</p>
| <python><openai-api><information-retrieval><langchain><large-language-model> | 2023-09-03 16:11:50 | 2 | 343 | Guilherme Giuliano Nicolau |
77,032,964 | 7,169,895 | Coroutine does not run on button click in Pyside6 | <p>I am trying to run a coroutine which gets data on a button click. It uses <code>aiohttp</code> to get the data. The button is decorated with <code>@asyncSlot()</code> from <code>qasync</code> However, when I click the button, nothing happens, not even a print statement. I do not think the asyncio examples <a href="https://doc.qt.io/qtforpython-6/examples/example_async_minimal.html" rel="nofollow noreferrer">examples</a> match my use case. I have tried moving when asyncio runs around to see if that helps. I am a little stumped as I get no errors to work with. Why is my function not running?</p>
<p>My code:</p>
<pre><code>class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.container = QWidget() # Controls container widget.
self.controlsLayout = QVBoxLayout()
# -- Search bar and settings button
self.search_layout = QHBoxLayout()
self.search_bar = QLineEdit()
self.search_button = QPushButton("Search")
self.search_button.clicked.connect(self.update_data) # search by entered text
self.search_layout.addWidget(self.search_button)
self.controlsLayout.addLayout(self.search_layout)
# Our tab container with adjustable number of tabs
self.tab_container = TabContainer()
# Add out tabs widget
self.controlsLayout.addWidget(self.tab_container)
self.container.setLayout(self.controlsLayout)
self.setCentralWidget(self.container
@asyncSlot()
async def update_data(self):
stock_tickers = self.search_bar.text()
print("Entered tickers: ", stock_tickers)
short_interest = asyncio.create_task(self.setup_data(stock))
short_interest = await short_interest
print('SHORT INTEREST:', short_interest)
# Make a table in a new tab here
# ..............................
async def setup_data(self, stock):
short_interest = await get_data(stock) # this function is our main coroutine
# process the data here ...... as previous method return json
async def main():
app = QApplication(sys.argv)
loop = qasync.QEventLoop(app)
asyncio.set_event_loop(loop)
main_window = MainWindow()
main_window.show()
sys.exit(app.exec())
if __name__ == '__main__':
asyncio.run(main())
</code></pre>
<p>where my <code>get_data(stock)</code>, <strong>which we can think of as an basic aiohttp json call</strong>, is defined as</p>
<pre><code>async def get_data(stock_ticker):
async with aiohttp.ClientSession() as session:
async with session.get('https://www.finra.org/finra-data/browse-catalog/equity-short-interest/data') as response:
cfruid = session.cookie_jar.filter_cookies('https://www.finra.org/')["__cfruid"].value
print("CFRUID", cfruid)
five_months_date = date.today() + relativedelta(months=-5)
headers = {
'authority': 'services-dynarep.ddwa.finra.org',
'accept': 'application/json, text/plain, */*',
'accept-language': 'en-US,en;q=0.6',
'content-type': 'application/json',
'cookie': f'XSRF-TOKEN={cfruid};',
'origin': 'https://www.finra.org',
'referer': 'https://www.finra.org/',
'x-xsrf-token': cfruid,
}
json_data = {
'fields': [
'settlementDate',
'issueName',
'symbolCode',
'marketClassCode',
'currentShortPositionQuantity',
'previousShortPositionQuantity',
'changePreviousNumber',
'changePercent',
'averageDailyVolumeQuantity',
'daysToCoverQuantity',
'revisionFlag',
],
'dateRangeFilters': [],
'domainFilters': [],
'compareFilters': [
{
'fieldName': 'symbolCode',
'fieldValue': 'GME',
'compareType': 'EQUAL',
},
{
'fieldName': 'settlementDate',
'fieldValue': str(five_months_date),
'compareType': 'GREATER',
},
],
'multiFieldMatchFilters': [],
'orFilters': [],
'aggregationFilter': None,
'sortFields': [
'-settlementDate',
'+issueName',
],
'limit': 50,
'offset': 0,
'delimiter': None,
'quoteValues': False,
}
async with session.post('https://services-dynarep.ddwa.finra.org/public/reporting/v2/data/group/OTCMarket/name/ConsolidatedShortInterest',
headers=headers, json=json_data) as response2:
short_interest_data = await response2.json()
return short_interest_data
</code></pre>
<p>I was able to have the coroutine work and return data in its own file by creating a task and awaiting it. I also tried using the <code>loop</code> instead. What am I missing? Note, other regular methods work when the button is clicked so I know it is just asyncio that refuses to run.</p>
<p>Edit: It seems to hang at the beginning of the <code>aiohttp</code> part not running the print statement I have within <code>get_data</code></p>
| <python><python-asyncio><pyside6> | 2023-09-03 15:24:00 | 1 | 786 | David Frick |
77,032,789 | 1,856,357 | Is it safe to set `out=a` in `np.compress`? | <p>Let's say I want to compress some subset of a large numpy array along the first dimension, here's an arbitrary example:</p>
<pre class="lang-py prettyprint-override"><code>a = np.random.normal(size=(100_000, 5))
subset = (np.sum(a, axis=1) > 0)
a_compressed = a.compress(subset, axis=0)
</code></pre>
<p>Sadly this allocates a new array</p>
<pre class="lang-py prettyprint-override"><code>assert not np.shares_memory(a, a_compressed)
</code></pre>
<p>I don't really want to allocate more memory since my array is already quite large. I also don't actually care about <code>a</code> after generating <code>a_compressed</code>, so I'd like to reuse the array. I found I can do this:</p>
<pre class="lang-py prettyprint-override"><code>a_compressed = a.compress(subset, axis=0, out=a[:np.sum(subset)])
assert np.shares_memory(a, a_compressed)
</code></pre>
<p>This seems to work but I can't verify anywhere that this is a legal way of using <code>out=</code>. The <a href="https://numpy.org/doc/stable/reference/generated/numpy.compress.html#numpy.compress" rel="nofollow noreferrer">documentation</a> doesn't mention it, and when I try to follow the source I have a very hard time tracking which function call goes where.</p>
| <python><numpy> | 2023-09-03 14:37:12 | 0 | 304 | Timon Knigge |
77,032,773 | 310,370 | !source venv/bin/activate not working in a Kaggle notebook any ideas? | <p>I generated venv with below command</p>
<pre><code>!python3 -m venv venv
</code></pre>
<p>Activated it with below command</p>
<pre><code>!source venv/bin/activate
</code></pre>
<p>But it is not working. How do I know?</p>
<p>When I do <code>!pip freeze</code> it shows the entire notebook not the activated <code>venv</code></p>
<p>Any ideas?</p>
<p>Here how do I test screenshot</p>
<p><a href="https://i.sstatic.net/m0MZq.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/m0MZq.png" alt="enter image description here" /></a></p>
| <python><conda><kaggle> | 2023-09-03 14:33:47 | 1 | 23,982 | Furkan Gözükara |
77,032,768 | 1,334,761 | PIL saving as a PNG loses ICC profile | <p>I have a JPEG image (which unfortunately I cannot share here) which I'm trying to re-save as PNG, while maintaining its color profile:</p>
<pre><code>from PIL import Image
import numpy as np
pil_img = Image.open(path_to_jpeg)
# Some processing on the image...
np_img = np.array(pil_img)
Image.fromarray(np_img).save('/path/to/img.png', icc_profile=pil_img.info.get("icc_profile"))
</code></pre>
<p>Unfortunately, the colors change, so I assume the ICC profile is not saved correctly.<br />
When switching to save a 'jpeg' then the colors are maintained correctly. But I do not wish to save as a jpeg.</p>
| <python><image-processing><python-imaging-library><png><color-profile> | 2023-09-03 14:31:39 | 1 | 11,484 | Jjang |
77,032,661 | 18,020,941 | Django keeps running migrations without changes made | <p>I am creating a custom model field. It basically a one-level dictionary field which allows you to store model-subfields in a JSON manner in the database so fields which wont be queried upon will not take up an extra column.</p>
<p>The issue is, whenever I predefine the default value for the field, the migrations keep thinking there's changes in the default values, and thus makes a new migration.</p>
<p>The default values don't change across migration files, but maybe I am missing something about Django's internals.</p>
<p>How I know it is because of the default values is if I don't set default in the kwargs, the issue does not seem to appear.</p>
<p>The custom field:</p>
<pre><code>class JSONStructField(models.JSONField):
def __init__(self, fields=None, fieldrows=None, *args, **kwargs):
self.fields = self.process_fields(fields) if fields else None
self.fieldrows = self.process_fieldrows(fieldrows) if fieldrows else None
kwargs["default"] = self.generate_default
super().__init__(*args, **kwargs)
@staticmethod
def process_fields(fields):
return [FieldType(**field[2]) if isinstance(field, tuple) else field for field in fields]
@staticmethod
def process_fieldrows(fieldrows):
return [
[FieldType(**field[2]) if isinstance(field, tuple) else field for field in row]
for row in fieldrows
]
def generate_default(self):
default = {}
if self.fields:
for field in self.fields:
default[field.name] = field.default
elif self.fieldrows:
for row in self.fieldrows:
for field in row:
default[field.name] = field.default
else:
default = None
return default
def formfield(self, **kwargs):
return super().formfield(**{
"widget": JsonInputWidget(fields=self.fields, fieldrows=self.fieldrows),
**kwargs
})
def deconstruct(self):
name, path, args, kwargs = super().deconstruct()
if self.fields:
kwargs['fields'] = [field.deconstruct() for field in self.fields]
if self.fieldrows:
kwargs['fieldrows'] = [
[field.deconstruct() for field in row] for row in self.fieldrows
]
return name, path, args, kwargs
class FieldType:
def __init__(self, name: str, label: str, type: str, help_text: str = "", required: bool = False, default: any = None, attrs: dict = None):
self.name = name
self.label = label
self.type = type
self.help_text = help_text
self.required = required
self.default = default
self.attrs = attrs
def deconstruct(self):
return (
"{0}.{1}".format(self.__class__.__module__, self.__class__.__name__),
[],
{
"name": self.name,
"label": self.label,
"type": self.type,
"help_text": self.help_text,
"required": self.required,
"default": self.default,
"attrs": self.attrs,
},
)
</code></pre>
<p>How the fields are generated:</p>
<pre><code>
def button_fieldtypes(default_bg, default_text) -> list[FieldType]:
return [
[
FieldType("background_color", "Background Color", "color", default=default_bg),
FieldType("background_hover_color", "Background Hover Color", "color", default=default_bg),
FieldType("background_color_active", "Background Active Color", "color", default=default_bg),
FieldType("background_color_disabled", "Background Disabled Color", "color", default=default_bg),
],
[
FieldType("text_color", "Text Color", "color", default=default_text),
FieldType("text_hover_color", "Text Hover Color", "color", default=default_text),
FieldType("text_color_active", "Text Active Color", "color", default=default_text),
FieldType("text_color_disabled", "Text Disabled Color", "color", default=default_text),
],
[
FieldType("border_color", "Border Color", "color", default=default_text),
FieldType("border_hover_color", "Border Hover Color", "color", default=default_text),
FieldType("border_color_active", "Border Active Color", "color", default=default_text),
FieldType("border_color_disabled", "Border Disabled Color", "color", default=default_text),
]
]
</code></pre>
<pre><code> info_button = JSONStructField(
blank=True,
null=True,
help_text=_("Add info button styles to this site"),
fieldrows=button_fieldtypes("#248782", "#fafafa"),
)
</code></pre>
<p>Migration file:</p>
<pre><code># Generated by Django 4.2 on 2023-09-03 14:01
import core.apps.goodadvice.site_settings.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('site_settings', '0003_alter_stylesettings_danger_button_and_more'),
]
operations = [
migrations.AlterField(
model_name='stylesettings',
name='danger_button',
field=core.apps.goodadvice.site_settings.fields.JSONStructField(blank=True, default=core.apps.goodadvice.site_settings.fields.JSONStructField.generate_default, fieldrows=[[('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#872424', 'help_text': '', 'label': 'Background Color', 'name': 'background_color', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#872424', 'help_text': '', 'label': 'Background Hover Color', 'name': 'background_hover_color', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#872424', 'help_text': '', 'label': 'Background Active Color', 'name': 'background_color_active', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#872424', 'help_text': '', 'label': 'Background Disabled Color', 'name': 'background_color_disabled', 'required': False, 'type': 'color'})], [('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Text Color', 'name': 'text_color', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Text Hover Color', 'name': 'text_hover_color', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Text Active Color', 'name': 'text_color_active', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Text Disabled Color', 'name': 'text_color_disabled', 'required': False, 'type': 'color'})], [('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Border Color', 'name': 'border_color', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Border Hover Color', 'name': 'border_hover_color', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Border Active Color', 'name': 'border_color_active', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Border Disabled Color', 'name': 'border_color_disabled', 'required': False, 'type': 'color'})]], help_text='Add danger button styles to this site', null=True),
),
migrations.AlterField(
model_name='stylesettings',
name='info_button',
field=core.apps.goodadvice.site_settings.fields.JSONStructField(blank=True, default=core.apps.goodadvice.site_settings.fields.JSONStructField.generate_default, fieldrows=[[('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#248782', 'help_text': '', 'label': 'Background Color', 'name': 'background_color', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#248782', 'help_text': '', 'label': 'Background Hover Color', 'name': 'background_hover_color', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#248782', 'help_text': '', 'label': 'Background Active Color', 'name': 'background_color_active', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#248782', 'help_text': '', 'label': 'Background Disabled Color', 'name': 'background_color_disabled', 'required': False, 'type': 'color'})], [('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Text Color', 'name': 'text_color', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Text Hover Color', 'name': 'text_hover_color', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Text Active Color', 'name': 'text_color_active', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Text Disabled Color', 'name': 'text_color_disabled', 'required': False, 'type': 'color'})], [('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Border Color', 'name': 'border_color', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Border Hover Color', 'name': 'border_hover_color', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Border Active Color', 'name': 'border_color_active', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Border Disabled Color', 'name': 'border_color_disabled', 'required': False, 'type': 'color'})]], help_text='Add info button styles to this site', null=True),
),
migrations.AlterField(
model_name='stylesettings',
name='primary_button',
field=core.apps.goodadvice.site_settings.fields.JSONStructField(blank=True, default=core.apps.goodadvice.site_settings.fields.JSONStructField.generate_default, fieldrows=[[('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#244487', 'help_text': '', 'label': 'Background Color', 'name': 'background_color', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#244487', 'help_text': '', 'label': 'Background Hover Color', 'name': 'background_hover_color', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#244487', 'help_text': '', 'label': 'Background Active Color', 'name': 'background_color_active', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#244487', 'help_text': '', 'label': 'Background Disabled Color', 'name': 'background_color_disabled', 'required': False, 'type': 'color'})], [('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Text Color', 'name': 'text_color', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Text Hover Color', 'name': 'text_hover_color', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Text Active Color', 'name': 'text_color_active', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Text Disabled Color', 'name': 'text_color_disabled', 'required': False, 'type': 'color'})], [('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Border Color', 'name': 'border_color', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Border Hover Color', 'name': 'border_hover_color', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Border Active Color', 'name': 'border_color_active', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Border Disabled Color', 'name': 'border_color_disabled', 'required': False, 'type': 'color'})]], help_text='Add primary button styles to this site', null=True),
),
migrations.AlterField(
model_name='stylesettings',
name='secondary_button',
field=core.apps.goodadvice.site_settings.fields.JSONStructField(blank=True, default=core.apps.goodadvice.site_settings.fields.JSONStructField.generate_default, fieldrows=[[('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#642487', 'help_text': '', 'label': 'Background Color', 'name': 'background_color', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#642487', 'help_text': '', 'label': 'Background Hover Color', 'name': 'background_hover_color', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#642487', 'help_text': '', 'label': 'Background Active Color', 'name': 'background_color_active', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#642487', 'help_text': '', 'label': 'Background Disabled Color', 'name': 'background_color_disabled', 'required': False, 'type': 'color'})], [('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Text Color', 'name': 'text_color', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Text Hover Color', 'name': 'text_hover_color', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Text Active Color', 'name': 'text_color_active', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Text Disabled Color', 'name': 'text_color_disabled', 'required': False, 'type': 'color'})], [('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Border Color', 'name': 'border_color', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Border Hover Color', 'name': 'border_hover_color', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Border Active Color', 'name': 'border_color_active', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Border Disabled Color', 'name': 'border_color_disabled', 'required': False, 'type': 'color'})]], help_text='Add secondary button styles to this site', null=True),
),
migrations.AlterField(
model_name='stylesettings',
name='success_button',
field=core.apps.goodadvice.site_settings.fields.JSONStructField(blank=True, default=core.apps.goodadvice.site_settings.fields.JSONStructField.generate_default, fieldrows=[[('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#24874d', 'help_text': '', 'label': 'Background Color', 'name': 'background_color', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#24874d', 'help_text': '', 'label': 'Background Hover Color', 'name': 'background_hover_color', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#24874d', 'help_text': '', 'label': 'Background Active Color', 'name': 'background_color_active', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#24874d', 'help_text': '', 'label': 'Background Disabled Color', 'name': 'background_color_disabled', 'required': False, 'type': 'color'})], [('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Text Color', 'name': 'text_color', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Text Hover Color', 'name': 'text_hover_color', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Text Active Color', 'name': 'text_color_active', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Text Disabled Color', 'name': 'text_color_disabled', 'required': False, 'type': 'color'})], [('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Border Color', 'name': 'border_color', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Border Hover Color', 'name': 'border_hover_color', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Border Active Color', 'name': 'border_color_active', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Border Disabled Color', 'name': 'border_color_disabled', 'required': False, 'type': 'color'})]], help_text='Add success button styles to this site', null=True),
),
migrations.AlterField(
model_name='stylesettings',
name='tertiary_button',
field=core.apps.goodadvice.site_settings.fields.JSONStructField(blank=True, default=core.apps.goodadvice.site_settings.fields.JSONStructField.generate_default, fieldrows=[[('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#247887', 'help_text': '', 'label': 'Background Color', 'name': 'background_color', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#247887', 'help_text': '', 'label': 'Background Hover Color', 'name': 'background_hover_color', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#247887', 'help_text': '', 'label': 'Background Active Color', 'name': 'background_color_active', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#247887', 'help_text': '', 'label': 'Background Disabled Color', 'name': 'background_color_disabled', 'required': False, 'type': 'color'})], [('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Text Color', 'name': 'text_color', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Text Hover Color', 'name': 'text_hover_color', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Text Active Color', 'name': 'text_color_active', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Text Disabled Color', 'name': 'text_color_disabled', 'required': False, 'type': 'color'})], [('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Border Color', 'name': 'border_color', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Border Hover Color', 'name': 'border_hover_color', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Border Active Color', 'name': 'border_color_active', 'required': False, 'type': 'color'}), ('core.apps.goodadvice.site_settings.widgets.FieldType', [], {'attrs': None, 'default': '#fafafa', 'help_text': '', 'label': 'Border Disabled Color', 'name': 'border_color_disabled', 'required': False, 'type': 'color'})]], help_text='Add tertiary button styles to this site', null=True),
),
]
</code></pre>
<p>I only included one migration file, because they do not seem to change (after running through diff-checker, only the name of migration changes).</p>
<p>A thing to note:
It does work, the default values are properly set. It just keeps making a migration over and over again.</p>
| <python><django><django-models> | 2023-09-03 14:09:56 | 1 | 1,925 | nigel239 |
77,032,559 | 10,788,239 | Why is the kivy window automatically 25% bigger than specified? | <p>I'm creating a game in kivy and noticed that the window size is always 25% bigger than I specify it to be:</p>
<pre><code>from kivy.app import App
from kivy.uix.widget import Widget
from kivy.core.window import Window
# screen dimensions, px
screen_width = 400
screen_height = 600
Window.size = (screen_width, screen_height)
class PlayGame(Widget):
def on_touch_move(self, touch):
self.touch = touch
print(self.touch.x, self.touch.y)
class TestGame(App):
def build(self):
return PlayGame()
if __name__ == '__main__':
game = TestGame()
game.run()
</code></pre>
<p>Running this code, then clicking my mouse and running it down the side of the screen gives a width of 500 and doing the same along the top gives a height of 750.</p>
<p>I have looked in the kivy docs, but all it has for the window size is</p>
<pre><code>Get the rotated size of the window. If rotation is set, then the size will change to reflect the rotation.
New in version 1.0.9.
size is an AliasProperty.
</code></pre>
<p>I'm not sure that any of this helps, expecially given that the window is not rotated.</p>
| <python><kivy><window> | 2023-09-03 13:44:20 | 1 | 438 | Arkleseisure |
77,032,448 | 913,098 | Pytorch Lightning: How to save a checkpoint for every validation epoch? | <p>It is not clear from <a href="https://pytorch-lightning.readthedocs.io/en/1.2.10/api/pytorch_lightning.callbacks.model_checkpoint.html" rel="noreferrer">the docs</a> how to save a checkpoint for every epoch, and have it actually saved and not instantly deleted, with no followed metric.</p>
<p>How to do it?</p>
| <python><pytorch><pytorch-lightning> | 2023-09-03 13:17:44 | 1 | 28,697 | Gulzar |
77,032,436 | 1,991,502 | Using pydantic to catch an invalid attribute setting | <p>The script below runs without error. I would like to catch the invalid attribute setting on the last line, where the value is not set to a positive integer.</p>
<pre><code>from pydantic.dataclasses import dataclass
from pydantic import PositiveInt
@dataclass
class MyDataClass:
value: PositiveInt
my_class = MyDataClass(value=10)
my_class.value = -1
</code></pre>
| <python><validation><pydantic> | 2023-09-03 13:15:01 | 1 | 749 | DJames |
77,032,427 | 10,666,587 | r_ slicing mistakenly includes last argument | <p>I have strange float inaccuracies; the results of <a href="https://numpy.org/doc/stable/reference/generated/numpy.r_.html" rel="nofollow noreferrer"><code>r_</code></a> are not consistent:</p>
<pre><code>import numpy as np
np.r_[-665.6:-650.24:2.56] == array([-665.6 , -663.04, -660.48, -657.92, -655.36, -652.8 , -650.24])
</code></pre>
<p>This is not what I expect (the last element is included). Adding <code>650</code> "solves" it:</p>
<pre><code>import numpy as np
np.r_[-15.6:-0.24:2.56] == array([-15.6 , -13.04, -10.48, -7.92, -5.36, -2.8 ])
</code></pre>
<p>I believe it is not possible that <code>np.r_[a:b:t].shape != np.r_[a+x:b+x:t].shape</code>. Is it a bug and not just inaccuracies? What can I do about it? I use Python 3.11 and NumPy 1.21.6. <a href="https://numpy.org/doc/stable/reference/generated/numpy.arange.html" rel="nofollow noreferrer">Documentation recommends</a> <a href="https://numpy.org/doc/stable/reference/generated/numpy.linspace.html" rel="nofollow noreferrer"><code>linspace</code></a> in this case. The API is not the same and the best I can do is:</p>
<pre><code>import numpy as np
def float_linspace(start, stop, step, precision=10):
num_of_elements = round((stop - start) / step, precision)
new_stop = round(int(num_of_elements) * step + start, precision)
end_point = new_stop < round(stop, 10)
coords, new_step = np.linspace(start, new_stop, num=int(num_of_elements) + end_point, endpoint=end_point, retstep=True)
assert round(new_step, 10) == step
return coords
</code></pre>
<p>This is more stable than results from <code>arange</code> but I consider it far from elegant.</p>
| <python><numpy> | 2023-09-03 13:12:34 | 1 | 328 | Shaq |
77,032,221 | 20,266,647 | MLRun ingestion, ConnectionResetError 10054 | <p>I got this error during ingest data to Parquet in MLRun CE:</p>
<pre><code>2023-09-03 14:01:47,327 [error] Unhandled exception while sending request: {'e': <class 'ConnectionResetError'>, 'e_msg': ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None), 'connection': <http.client.HTTPSConnection object at 0x000002183B39F100>}
</code></pre>
<p>See part of call stack:</p>
<pre><code>File "C:\Python\qgate-sln-mlrun\venv\lib\site-packages\v3io\dataplane\transport\httpclient.py", line 160, in _send_request_on_connection
connection.request(request.method, path, request.body, request.headers)
File "C:\Users\jist\AppData\Local\Programs\Python\Python39\lib\http\client.py", line 1285, in request
self._send_request(method, url, body, headers, encode_chunked)
File "C:\Users\jist\AppData\Local\Programs\Python\Python39\lib\http\client.py", line 1331, in _send_request
self.endheaders(body, encode_chunked=encode_chunked)
File "C:\Users\jist\AppData\Local\Programs\Python\Python39\lib\http\client.py", line 1280, in endheaders
self._send_output(message_body, encode_chunked=encode_chunked)
File "C:\Users\jist\AppData\Local\Programs\Python\Python39\lib\http\client.py", line 1079, in _send_output
self.send(chunk)
File "C:\Users\jist\AppData\Local\Programs\Python\Python39\lib\http\client.py", line 1001, in send
self.sock.sendall(data)
File "C:\Users\jist\AppData\Local\Programs\Python\Python39\lib\ssl.py", line 1204, in sendall
v = self.send(byte_view[count:])
File "C:\Users\jist\AppData\Local\Programs\Python\Python39\lib\ssl.py", line 1173, in send
return self._sslobj.write(data)
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
</code></pre>
<p>Did you solve the same issue?</p>
| <python><data-ingestion><mlops><mlrun><feature-store> | 2023-09-03 12:13:23 | 1 | 1,390 | JIST |
77,031,967 | 3,990,451 | How to make python3 import examine .so and ...-g.so as well? | <p>We expose C++ code to python via boost.python. We produce release and debug builds.</p>
<p>release builds produce lib.so files</p>
<p>debug builds produce lib-g.so files.</p>
<p>Our python code then</p>
<pre><code>import lib<mymodule>
</code></pre>
<p>Is there a way to place a hook such that those import statements can explore both libmymodule.so and if not found libmymodule-g.so?</p>
| <python><boost-python> | 2023-09-03 10:55:57 | 1 | 982 | MMM |
77,031,949 | 7,625,386 | problem with changing the frames in an video with opencv | <p>I have a code that runs in the last few months without any problem. The code shows an image from a video with extra data from the relevant db. using the keyboard you can jump around some frames and get better insights. However, in the last week changing the frame of the video stopped working.</p>
<p>I built a small script that show the problem.</p>
<pre><code>import cv2
vid_cap_reader_path = "vid_230830_122746_C.avi"
cap_rgb = cv2.VideoCapture(vid_cap_reader_path)
k = 0
while 1:
if k == ord("q"):
break
if k == ord("b"):
before = cap_rgb.get(cv2.CAP_PROP_POS_FRAMES)
cap_rgb.set(cv2.CAP_PROP_POS_FRAMES, before + 30.0)
after = cap_rgb.get(cv2.CAP_PROP_POS_FRAMES)
print(f"before = {before} after = {after}")
ret, img = cap_rgb.read()
if ret:
cv2.imshow("bla", img)
k = cv2.waitKey(0)
else:
break
</code></pre>
<p>This is what is printed to the terminal:</p>
<pre><code>[mpeg4 @ 0x1d87400] warning: first frame is no keyframe
before = 36.0 after = 0.0
before = 67.0 after = 0.0
[mpeg4 @ 0x1d87400] warning: first frame is no keyframe
before = 40.0 after = 0.0
[mpeg4 @ 0x1d87400] warning: first frame is no keyframe
</code></pre>
<p>The video itself doesn't "jump" for the next frame as expected and also most of the properties that opencv have return 0. I tested also <code>CAP_PROP_FRAME_COUNT</code>, and <code>CAP_PROP_POS_MSEC</code> without any lack, although the msec flag did give non-zero results which make no sense.</p>
<p>It is also important to mention that I am building this application in a docker file and I am not using a specific version for my requirements. The tests here are with <code>opencv-python==4.7.0.68</code>. Also, the videos are working fine while playing them on VLC.</p>
<p>I was looking around the net for a similar problem from the recent time and didn't find much except this <a href="https://github.com/opencv/opencv/issues/23472" rel="nofollow noreferrer">github issue</a> that may be similar. I started to downgrade opencv one by one without any luck.</p>
<p>Maybe someone here can help with this issue, or give me a lead to doing something different.</p>
| <python><docker><opencv><ffmpeg> | 2023-09-03 10:48:27 | 1 | 501 | Avizipi |
77,031,155 | 13,834,948 | discrepancy with Python datetime with timezone | <p>Can anyone please help explain about the following. why don't I get even numbers for the hours?</p>
<p>I'm running Python 3.10. The following is from ptpython session:</p>
<pre><code>>>> import pytz
... from datetime import datetime
...
... # Define time zones for Eastern Time and Pacific Time
... eastern_timezone = pytz.timezone("US/Eastern")
... pacific_timezone = pytz.timezone("US/Pacific")
...
... # Create datetime objects with accurate timezone offsets
... dt1 = datetime(2023, 1, 1, 11, 0, 0, 0, tzinfo=eastern_timezone) # Eastern Time
... dt2 = datetime(2023, 1, 1, 8, 0, 0, 0, tzinfo=pacific_timezone) # Pacific Time
...
... print(dt1)
... print(dt2)
2023-01-01 11:00:00-04:56
2023-01-01 08:00:00-07:53
>>> dt1 - dt2
datetime.timedelta(seconds=180)
</code></pre>
| <python><python-3.x> | 2023-09-03 06:29:39 | 1 | 1,634 | LXJ |
77,031,060 | 1,385,107 | Query bot on multiple JSON files on Langchain | <p>I have around 30 GB of JSON data with multiple files, wanted build query bot on this.
I have built same with text file but i am not sure how it will work for JSON data.</p>
<p>I have explored JSONLoader but dont know how to use this to convert JSON data into vector and store it into ChromaDB so that i can query them.
<a href="https://python.langchain.com/docs/modules/data_connection/document_loaders/json" rel="noreferrer">https://python.langchain.com/docs/modules/data_connection/document_loaders/json</a></p>
<p>Sample JSON File : <a href="http://jsonblob.com/1147948130921996288" rel="noreferrer">http://jsonblob.com/1147948130921996288</a></p>
<p><strong>Code for Text data:</strong></p>
<pre><code># Loading and Splitting the Documents
from langchain.document_loaders import DirectoryLoader
directory = '/content/drive/MyDrive/Data Science/LLM/docs/text files'
def load_docs(directory):
loader = DirectoryLoader(directory)
documents = loader.load()
return documents
documents = load_docs(directory)
len(documents)
from langchain.text_splitter import RecursiveCharacterTextSplitter
def split_docs(documents,chunk_size=1000,chunk_overlap=20):
text_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
docs = text_splitter.split_documents(documents)
return docs
docs = split_docs(documents)
print(len(docs))
# Embedding Text Using Langchain
from langchain.embeddings import SentenceTransformerEmbeddings
embeddings = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")
#Creating Vector Store with Chroma DB
from langchain.vectorstores import Chroma
persist_directory = "/content/drive/MyDrive/Data Science/LLM/docs/chroma_db"
vectordb = Chroma.from_documents(
documents=docs, embedding=embeddings, persist_directory=persist_directory
)
vectordb.persist()
#Using OpenAI Large Language Models (LLM) with Chroma DB
import os
os.environ["OPENAI_API_KEY"] = "sk-your-key"
from langchain.chat_models import ChatOpenAI
model_name = "gpt-3.5-turbo"
llm = ChatOpenAI(model_name=model_name)
#Extracting Answers from Documents
from langchain.chains.question_answering import load_qa_chain
chain = load_qa_chain(llm, chain_type="stuff",verbose=True)
query = "who is Mr. Jabez Wilson?"
matching_docs = vectordb.similarity_search(query)
answer = chain.run(input_documents=matching_docs, question=query)
answer
</code></pre>
<p>What I tried for JSON Data :</p>
<pre><code>from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.embeddings import SentenceTransformerEmbeddings
from langchain.vectorstores import Chroma
from langchain.chat_models import ChatOpenAI
from langchain.chains.question_answering import load_qa_chain
from langchain.document_loaders import DirectoryLoader
from langchain.document_loaders import JSONLoader
import json
# Define a simple JSON schema (modify as needed)
json_schema = {
}
# Function to validate a JSON document against a schema
def validate_json(json_data, schema):
return all(key in json_data for key in schema.keys())
# 1. Load JSON Files
def load_json_docs(directory):
loader = DirectoryLoader(directory, glob='**/*.json', loader_cls=JSONLoader)
documents = loader.load()
# Manually filter and validate documents based on the JSON schema
valid_documents = []
for doc in documents:
try:
# Parse the JSON content
json_data = json.loads(doc.page_content)
if validate_json(json_data, json_schema):
valid_documents.append(doc)
except json.JSONDecodeError:
pass # Invalid JSON format, skip this document
return valid_documents
directory = '/content/drive/MyDrive/Data Science/LLM/docs/json files'
json_documents = load_json_docs(directory)
len(json_documents)
# 2. Split JSON Documents
def split_json_docs(documents, chunk_size=1000, chunk_overlap=20):
text_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
docs = text_splitter.split_documents(documents)
return docs
split_json_documents = split_json_docs(json_documents)
print(len(split_json_documents))
# 3. Embedding Text Using Langchain
embeddings = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")
# 4. Creating Vector Store with Chroma DB
persist_directory = "/content/drive/MyDrive/Data Science/LLM/docs/chroma_json_db"
vectordb = Chroma.from_documents(
documents=split_json_documents, embedding=embeddings, persist_directory=persist_directory
)
vectordb.persist()
# 5. Using OpenAI Large Language Models (LLM) with Chroma DB
import os
os.environ["OPENAI_API_KEY"] = "sk-your-key"
model_name = "gpt-3.5-turbo"
llm = ChatOpenAI(model_name=model_name)
# 6. Extracting Answers from Documents
chain = load_qa_chain(llm, chain_type="stuff", verbose=True)
query = "who is Mr. Jabez Wilson?"
matching_docs = vectordb.similarity_search(query)
answer = chain.run(input_documents=matching_docs, question=query)
answer
</code></pre>
| <python><langchain><large-language-model><chromadb><jsonloader> | 2023-09-03 05:46:58 | 1 | 5,313 | Juned Ansari |
77,030,917 | 5,763,590 | Unable to pass wandb API Key in PyCharm terminal | <pre><code>wandb: (1) Create a W&B account
wandb: (2) Use an existing W&B account
wandb: (3) Don't visualize my results
wandb: Enter your choice: 2
wandb: You chose 'Use an existing W&B account'
wandb: Logging into wandb.ai. (Learn how to deploy a W&B server locally: https://wandb.me/wandb-server)
wandb: You can find your API key in your browser here: https://wandb.ai/authorize
wandb: Paste an API key from your profile and hit enter, or press ctrl+c to quit:
</code></pre>
<p>Here my terminal in PyCharm freezes an I have no means whatsoever to enter or paste my API Key. On pressing enter nothing happens either.
<strong>Any help or ideas?</strong></p>
| <python><terminal><pycharm><wandb> | 2023-09-03 04:37:47 | 1 | 10,287 | mrk |
77,030,534 | 3,654,852 | Python : assign a column using lambda with if else | <p>I have a date column in a dataframe, and I'd like to create another column that I call peak_day. If the day name of the day in the date column is a weekend (Sat or Sun), it will return false, else True.
I got the code to work....but not sure what I'm doing wrong in the "bad" code. I could just move on....but I'm trying to really understand what the code does wrong and be a better coder:)</p>
<p>Here's the code that works:</p>
<pre><code>pk_day = lambda pkday : (df['Date'].dt.strftime('%a') == 'Sat' ) | (df['Date'].dt.strftime('%a') == 'Sun')
</code></pre>
<p>Here's the line that doesn't work - but I thought it's just a more explicit version of the first one:</p>
<pre><code>pk_day = lambda pkday : False if df[ (df['Date'].dt.strftime('%a') == 'Sat' ) | (df['Date'].dt.strftime('%a') == 'Sun') ] else True
</code></pre>
<p>Here's the error this line generates:</p>
<pre><code>The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
</code></pre>
<p>I also tried a slight variation with the df and square brackets to enclose the statement:</p>
<pre><code>pk_day = lambda pkday : False if (df['Date'].dt.strftime('%a') == 'Sat' ) | (df['Date'].dt.strftime('%a') == 'Sun') else True
</code></pre>
<p>and I get the same error as the previous line. It looks like there could be two sets of boolean values being generated by False and True results explicitly in the code and that causes it to fail? What is causing this?</p>
<p>Would appreciate the guidance! Thanks!</p>
| <python><pandas><dataframe><lambda> | 2023-09-03 00:45:17 | 3 | 803 | user3654852 |
77,030,437 | 1,536,050 | Pyinstaller Builds seemingly successfully, running the executable does nothing | <p>I have an application I'm trying to build an executable for written in python. For the records, my dependencies are reflected in the following import statements:</p>
<pre><code>import asyncio
import os
import time
from dotenv import load_dotenv
from winsdk.windows.media.control import (
GlobalSystemMediaTransportControlsSessionManager as MediaManager,
)
import musicbrainzngs
from difflib import SequenceMatcher
import PySimpleGUI as sg
from psgtray import SystemTray
import selenium
from selenium import webdriver
import requests
</code></pre>
<p>I am running the command:</p>
<pre><code>python -m PyInstaller --onefile --paths=./venv/Lib/site-packages app.pyw
</code></pre>
<p>This seems to run successfully as I don't see any warnings or messages. However, when I run the application by clicking on the exe or by running ./app.exe, a process appears in the task manager, but no UI window or console appear as they should.</p>
<p>I've also looked at warn-app.txt and I see all of the following, but I have no idea if these are actually causing the problem, and if so, why there are so many missing modules:</p>
<pre><code>This file lists modules PyInstaller was not able to find. This does not
necessarily mean this module is required for running your program. Python and
Python 3rd-party packages include a lot of conditional or optional modules. For
example the module 'ntpath' only exists on Windows, whereas the module
'posixpath' only exists on Posix systems.
Types if import:
* top-level: imported at the top-level - look at these first
* conditional: imported within an if-statement
* delayed: imported within a function
* optional: imported within a try-except-statement
IMPORTANT: Do NOT post this list to the issue-tracker. Use it as a basis for
tracking down the missing module yourself. Thanks!
missing module named pyimod02_importers - imported by C:\Users\adamm\Development\mediascrobbler\venv\Lib\site-packages\PyInstaller\hooks\rthooks\pyi_rth_pkgutil.py (delayed), C:\Users\adamm\Development\mediascrobbler\venv\Lib\site-packages\PyInstaller\hooks\rthooks\pyi_rth_pkgres.py (delayed)
missing module named jnius - imported by pkg_resources._vendor.platformdirs.android (delayed, optional)
missing module named platformdirs - imported by pkg_resources._vendor.platformdirs.__main__ (top-level)
missing module named pwd - imported by posixpath (delayed, conditional), shutil (delayed, optional), tarfile (optional), pathlib (delayed, optional), subprocess (delayed, conditional, optional), netrc (delayed, conditional), getpass (delayed), webbrowser (delayed), http.server (delayed, optional), distutils.util (delayed, conditional, optional), distutils.archive_util (optional), setuptools._distutils.util (delayed, conditional, optional), setuptools._distutils.archive_util (optional)
missing module named grp - imported by shutil (delayed, optional), tarfile (optional), pathlib (delayed, optional), subprocess (delayed, conditional, optional), distutils.archive_util (optional), setuptools._distutils.archive_util (optional)
missing module named _posixsubprocess - imported by subprocess (optional), multiprocessing.util (delayed)
missing module named fcntl - imported by subprocess (optional)
missing module named 'org.python' - imported by copy (optional), xml.sax (delayed, conditional)
missing module named org - imported by pickle (optional)
missing module named typing_extensions - imported by setuptools.config._validate_pyproject.formats (conditional), setuptools.command.build (conditional), urllib3.connection (conditional), urllib3.util.timeout (conditional), urllib3._base_connection (conditional), urllib3.util.request (conditional), urllib3._collections (conditional), urllib3.util.ssl_ (conditional), urllib3.util.ssltransport (conditional), urllib3.connectionpool (conditional), urllib3.response (conditional), urllib3.poolmanager (conditional), pkg_resources._vendor.packaging.metadata (conditional, optional), setuptools._vendor.packaging.metadata (conditional, optional)
missing module named posix - imported by os (conditional, optional), importlib._bootstrap_external (conditional), shutil (conditional)
missing module named resource - imported by posix (top-level)
missing module named _manylinux - imported by setuptools._vendor.packaging._manylinux (delayed, optional), pkg_resources._vendor.packaging._manylinux (delayed, optional)
missing module named 'pkg_resources.extern.importlib_resources' - imported by pkg_resources._vendor.jaraco.text (optional)
missing module named 'typing.io' - imported by importlib.resources (top-level)
missing module named _frozen_importlib_external - imported by importlib._bootstrap (delayed), importlib (optional), importlib.abc (optional), zipimport (top-level)
excluded module named _frozen_importlib - imported by importlib (optional), importlib.abc (optional), zipimport (top-level)
missing module named pep517 - imported by importlib.metadata (delayed)
missing module named 'pkg_resources.extern.more_itertools' - imported by pkg_resources._vendor.jaraco.functools (top-level)
missing module named pkg_resources.extern.packaging - imported by pkg_resources.extern (top-level), pkg_resources (top-level)
missing module named pkg_resources.extern.platformdirs - imported by pkg_resources.extern (top-level), pkg_resources (top-level)
missing module named 'pkg_resources.extern.jaraco' - imported by pkg_resources (top-level), pkg_resources._vendor.jaraco.text (top-level)
missing module named 'java.lang' - imported by platform (delayed, optional), xml.sax._exceptions (conditional)
missing module named vms_lib - imported by platform (delayed, optional)
missing module named java - imported by platform (delayed)
missing module named _winreg - imported by platform (delayed, optional), selenium.webdriver.firefox.firefox_binary (delayed, optional)
missing module named win32con - imported by setuptools._distutils.msvccompiler (optional)
missing module named win32api - imported by setuptools._distutils.msvccompiler (optional)
missing module named 'distutils._log' - imported by setuptools._distutils.command.bdist_dumb (top-level), setuptools._distutils.command.bdist_rpm (top-level), setuptools._distutils.command.build_clib (top-level), setuptools._distutils.command.build_ext (top-level), setuptools._distutils.command.build_py (top-level), setuptools._distutils.command.build_scripts (top-level), setuptools._distutils.command.clean (top-level), setuptools._distutils.command.config (top-level), setuptools._distutils.command.install (top-level), setuptools._distutils.command.install_scripts (top-level), setuptools._distutils.command.register (top-level), setuptools._distutils.command.sdist (top-level)
missing module named termios - imported by getpass (optional), tty (top-level)
missing module named usercustomize - imported by site (delayed, optional)
missing module named sitecustomize - imported by site (delayed, optional)
missing module named readline - imported by site (delayed, optional), rlcompleter (optional)
missing module named 'docutils.nodes' - imported by setuptools._distutils.command.check (top-level)
missing module named 'docutils.frontend' - imported by setuptools._distutils.command.check (top-level)
missing module named 'docutils.parsers' - imported by setuptools._distutils.command.check (top-level)
missing module named docutils - imported by setuptools._distutils.command.check (top-level)
missing module named _posixshmem - imported by multiprocessing.resource_tracker (conditional), multiprocessing.shared_memory (conditional)
missing module named multiprocessing.set_start_method - imported by multiprocessing (top-level), multiprocessing.spawn (top-level)
missing module named multiprocessing.get_start_method - imported by multiprocessing (top-level), multiprocessing.spawn (top-level)
missing module named multiprocessing.get_context - imported by multiprocessing (top-level), multiprocessing.pool (top-level), multiprocessing.managers (top-level), multiprocessing.sharedctypes (top-level)
missing module named multiprocessing.TimeoutError - imported by multiprocessing (top-level), multiprocessing.pool (top-level)
missing module named multiprocessing.BufferTooShort - imported by multiprocessing (top-level), multiprocessing.connection (top-level)
missing module named multiprocessing.AuthenticationError - imported by multiprocessing (top-level), multiprocessing.connection (top-level)
missing module named 'setuptools.extern.jaraco' - imported by setuptools._reqs (top-level), setuptools._entry_points (top-level), setuptools.command.egg_info (top-level), setuptools._vendor.jaraco.text (top-level)
missing module named setuptools.extern.importlib_resources - imported by setuptools.extern (conditional), setuptools._importlib (conditional), setuptools._vendor.jaraco.text (optional)
missing module named setuptools.extern.tomli - imported by setuptools.extern (delayed), setuptools.config.pyprojecttoml (delayed)
missing module named setuptools.extern.ordered_set - imported by setuptools.extern (top-level), setuptools.dist (top-level)
missing module named setuptools.extern.packaging - imported by setuptools.extern (top-level), setuptools.dist (top-level), setuptools._normalization (top-level), setuptools.command.egg_info (top-level), setuptools.depends (top-level)
missing module named setuptools.extern.importlib_metadata - imported by setuptools.extern (conditional), setuptools._importlib (conditional)
missing module named 'setuptools.extern.more_itertools' - imported by setuptools.dist (top-level), setuptools.config.expand (delayed), setuptools.config.pyprojecttoml (delayed), setuptools._itertools (top-level), setuptools._entry_points (top-level), setuptools.msvc (top-level), setuptools._vendor.jaraco.functools (top-level)
missing module named 'setuptools.extern.packaging.utils' - imported by setuptools.wheel (top-level)
missing module named 'setuptools.extern.packaging.tags' - imported by setuptools.wheel (top-level)
missing module named 'setuptools.extern.packaging.version' - imported by setuptools.config.setupcfg (top-level), setuptools.wheel (top-level)
missing module named importlib_metadata - imported by setuptools._importlib (delayed, optional)
missing module named trove_classifiers - imported by setuptools.config._validate_pyproject.formats (optional)
missing module named packaging - imported by setuptools.config._validate_pyproject.formats (optional)
missing module named 'setuptools.extern.packaging.specifiers' - imported by setuptools.config.setupcfg (top-level), setuptools.config._apply_pyprojecttoml (delayed)
missing module named 'setuptools.extern.packaging.requirements' - imported by setuptools.config.setupcfg (top-level), setuptools._reqs (top-level)
missing module named 'setuptools.extern.packaging.markers' - imported by setuptools.config.setupcfg (top-level)
missing module named _scproxy - imported by urllib.request (conditional)
missing module named simplejson - imported by requests.compat (conditional, optional)
missing module named dummy_threading - imported by requests.cookies (optional)
missing module named zstandard - imported by urllib3.response (optional), urllib3.util.request (optional)
missing module named brotli - imported by urllib3.response (optional), urllib3.util.request (optional)
missing module named brotlicffi - imported by urllib3.response (optional), urllib3.util.request (optional)
missing module named win_inet_pton - imported by socks (conditional, optional)
missing module named cryptography - imported by urllib3.contrib.pyopenssl (top-level), requests (conditional, optional)
missing module named 'OpenSSL.crypto' - imported by urllib3.contrib.pyopenssl (delayed, conditional)
missing module named 'cryptography.x509' - imported by urllib3.contrib.pyopenssl (delayed, optional)
missing module named OpenSSL - imported by urllib3.contrib.pyopenssl (top-level)
missing module named chardet - imported by requests.compat (optional), requests (optional), requests.packages (optional)
missing module named urllib3_secure_extra - imported by urllib3 (optional)
missing module named olefile - imported by PIL.FpxImagePlugin (top-level), PIL.MicImagePlugin (top-level)
missing module named 'packaging.version' - imported by PIL.Image (delayed, conditional, optional)
missing module named numpy - imported by PIL.Image (delayed, conditional, optional)
missing module named _dummy_thread - imported by cffi.lock (conditional, optional)
missing module named dummy_thread - imported by cffi.lock (conditional, optional)
missing module named thread - imported by cffi.lock (conditional, optional), cffi.cparser (conditional, optional)
missing module named cStringIO - imported by cPickle (top-level), cffi.ffiplatform (optional)
missing module named copy_reg - imported by cPickle (top-level), cStringIO (top-level)
missing module named cPickle - imported by pycparser.ply.yacc (delayed, optional)
missing module named cffi._pycparser - imported by cffi (optional), cffi.cparser (optional)
missing module named defusedxml - imported by PIL.Image (optional)
runtime module named six.moves - imported by pystray._base (top-level), pystray._win32 (top-level), pystray._xorg (top-level)
missing module named 'Xlib.XK' - imported by pystray._xorg (top-level)
missing module named 'Xlib.threaded' - imported by pystray._xorg (top-level)
missing module named Xlib - imported by pystray._xorg (top-level)
missing module named StringIO - imported by musicbrainzngs.compat (conditional), six (conditional)
missing module named 'gi.repository' - imported by pystray._appindicator (top-level), pystray._util.gtk (top-level), pystray._util.notify_dbus (top-level), pystray._gtk (top-level)
missing module named gi - imported by pystray._appindicator (top-level), pystray._util.gtk (top-level), pystray._util.notify_dbus (top-level), pystray._gtk (top-level)
missing module named PyObjCTools - imported by pystray._darwin (top-level)
missing module named objc - imported by pystray._darwin (top-level)
missing module named Foundation - imported by pystray._darwin (top-level)
missing module named AppKit - imported by pystray._darwin (top-level)
missing module named urlparse - imported by musicbrainzngs.compat (conditional)
missing module named httplib - imported by musicbrainzngs.compat (conditional)
missing module named urllib2 - imported by musicbrainzngs.compat (conditional)
missing module named 'winsdk.windows.ui.composition' - imported by winsdk.windows.ui.core (optional), winsdk.windows.ui.windowmanagement (optional)
missing module named 'IPython.core' - imported by dotenv.ipython (top-level)
missing module named IPython - imported by dotenv.ipython (top-level)
missing module named asyncio.DefaultEventLoopPolicy - imported by asyncio (delayed, conditional), asyncio.events (delayed, conditional)
</code></pre>
| <python><pyinstaller> | 2023-09-02 23:52:48 | 1 | 1,550 | KinsDotNet |
77,030,386 | 16,886,597 | How can I see if at least N times in a list of times fall within a 24-hour time span? | <p>I have a handful of different dates and times, represented as a handful of <a href="https://docs.python.org/3/library/datetime.html#datetime.datetime" rel="nofollow noreferrer">datetime objects</a> in a list.</p>
<pre class="lang-py prettyprint-override"><code>from datetime import datetime
arr = [datetime(2023, 9, 1, hour=4, minute=3),
datetime(2023, 9, 1, hour=2, minute=15),
datetime(2023, 9, 1, hour=6, minute=45),
# trimmed for brevity
]
</code></pre>
<p>If I wanted to see if <em>two</em> datetime objects fell within 24-hours of each other, that <a href="https://stackoverflow.com/questions/1345827/how-do-i-find-the-time-difference-between-two-datetime-objects-in-python">isn't terribly hard to do</a>. Except, I'm trying to see if, given a list of datetime objects, at least <em>n</em> of them can be contained within a 24-hour time span.</p>
<p>For a real-world use case of this, those timestamps might represent sign-ins on a user account, and if a user attempts to log in too <em>n</em> times in 15 minutes, I might choose to take some action based on that*.</p>
<p>How can this be done in Python?</p>
<hr />
<p>*Don't worry, I'm not <em>actually</em> trying to DIY authentication - that is purely an example.</p>
| <python><python-3.x><python-datetime> | 2023-09-02 23:29:25 | 1 | 674 | cocomac |
77,030,241 | 14,509,604 | pandas.convert_dtype(dtype_backend="pyarrow") raises error | <p>I'm starting to use pandas with Pyarrow and realized there's no easy way to declare a df directly as with Pyarrow engine, so I ended up in <a href="https://stackoverflow.com/questions/75939770/how-can-i-construct-a-dataframe-that-uses-the-pyarrow-backend-directly-i-e-wi">this post</a>. The thing is that I'm having the same isssue as one user comment in the accepted answer.</p>
<pre><code>
df = pd.DataFrame({'A' : ['spam', 'eggs', 'spam', 'eggs'] * 2,
'B' : ['alpha', 'beta', 'gamma' , 'foo'] * 2,
'C' : [np.random.choice(pd.date_range(datetime.datetime(2013,1,1),datetime.datetime(2013,1,3))) for i in range(8)],
'D' : np.random.randn(8),
'E' : np.random.random_integers(8)}).convert_dtypes(dtype_backend='pyarrow')
</code></pre>
<p>This raises <code>NameError: name 'ArrowDtype' is not defined</code></p>
<p>pandas version == 2.1.0</p>
<p>Using vscode with jupyter integrated terminal.</p>
| <python><pandas><pyarrow> | 2023-09-02 22:21:13 | 1 | 329 | juanmac |
77,030,165 | 5,019,169 | How to send message as slash command in discord.py? | <p>I have a bot (Let's name it <code>A</code>) already connected to the channel, and it has a slash command '/greet' that takes a <code>prompt</code> and acts upon it. Now I am trying to write a bot <code>B</code> here, that sends a command <code>/greet prompt hello!</code> for example, which will trigger the bot <code>A</code>, and <code>A</code> will provide the appropriate output to the prompt.</p>
<p>The problem is, when I run my script below, it doesn't understand that it's supposed to be a slash command, and send to discord as a raw string. How to fix this?</p>
<pre><code>import discord
from discord.ext import commands
discord_token = ''
channel_id = ""
client = commands.Bot(command_prefix="*", intents=discord.Intents.all())
@client.event
async def on_ready():
print("Bot connected")
await client.get_channel(int(channel_id)).send('/greet prompt hello')
@client.event
async def on_message(message):
print(message.content)
print('We are successfully triggering the bot')
if __name__ == "__main__":
client.run(discord_token)
</code></pre>
| <python><python-3.x><discord><discord.py><bots> | 2023-09-02 21:49:27 | 2 | 11,224 | Ahasanul Haque |
77,030,009 | 10,883,088 | JSONDecodeError error when trying to pull playlists from spotify using spotipy | <p>I'm using the default instructions provided by docs in spotipy, I setup my app in the spotify dev dashboard, and checked my credentials, but am still getting this error code:</p>
<p><code>JSONDecodeError: Expecting value: line 1 column 1 (char 0)</code></p>
<pre><code>import spotipy
from spotipy.oauth2 import SpotifyOAuth
YOUR_APP_CLIENT_ID = "myappclientid"
YOUR_APP_CLIENT_SECRET = "myclientsecret"
YOUR_APP_REDIRECT_URI = "mycallback"
SCOPE = "playlist-read-private"
sp = spotipy.Spotify(
auth_manager=SpotifyOAuth(
client_id=YOUR_APP_CLIENT_ID,
client_secret=YOUR_APP_CLIENT_SECRET,
redirect_uri=YOUR_APP_REDIRECT_URI,
scope=SCOPE,
)
)
sp.current_user_playlists(limit = 50)
</code></pre>
<p>full traceback:</p>
<pre><code>---------------------------------------------------------------------------
JSONDecodeError Traceback (most recent call last)
c:\my_spotify_playlists\example.py in
14 )
15
---> 16 sp.current_user_playlists(limit = 50)
c:\Users\MyUserName\AppData\Local\Programs\Python\Python38\lib\site-packages\spotipy\client.py in current_user_playlists(self, limit, offset)
635 - offset - the index of the first item to return
636 """
--> 637 return self._get("me/playlists", limit=limit, offset=offset)
638
639 def playlist(self, playlist_id, fields=None, market=None, additional_types=("track",)):
c:\Users\MyUserName\AppData\Local\Programs\Python\Python38\lib\site-packages\spotipy\client.py in _get(self, url, args, payload, **kwargs)
321 kwargs.update(args)
322
--> 323 return self._internal_call("GET", url, payload, kwargs)
324
325 def _post(self, url, args=None, payload=None, **kwargs):
c:\Users\MyUserName\AppData\Local\Programs\Python\Python38\lib\site-packages\spotipy\client.py in _internal_call(self, method, url, payload, params)
245 if not url.startswith("http"):
246 url = self.prefix + url
--> 247 headers = self._auth_headers()
248
249 if "content_type" in args["params"]:
...
354 except StopIteration as err:
--> 355 raise JSONDecodeError("Expecting value", s, err.value) from None
356 return obj, end
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
</code></pre>
| <python><python-3.x><spotify><spotipy> | 2023-09-02 20:50:48 | 0 | 471 | dko512 |
77,029,973 | 3,651,478 | Hello World Neural Network to understand basics | <p>I am trying to build a noob neural net using tensorflow that learns to solve the equation <code>y = 2x - 1</code>
Training data -</p>
<pre><code>xs = [0,1,2,3,4,5]
ys = [-1,1,3,5,7,9]
xs = np.array(xs, dtype=float)
ys = np.array(ys, dtype=float)
</code></pre>
<p>I am using 3 different models which changes only in the input_shape as below -</p>
<p>Model 1 works perfectly -</p>
<pre><code>model1 = keras.models.Sequential()
model1.add(keras.layers.Dense(units=1, input_shape=[1]))
model1.compile(optimizer='sgd', loss='mean_squared_error')
</code></pre>
<p>Model 2 works perfectly as well -</p>
<pre><code>model2 = keras.models.Sequential()
model2.add(keras.layers.Dense(units=1, input_shape=(1,)))
model2.compile(optimizer='sgd', loss='mean_squared_error')
</code></pre>
<p>Model 3 fails in model.fit()</p>
<pre><code>model3 = keras.models.Sequential()
model3.add(keras.layers.Dense(units=1, input_shape=(None,1,)))
model3.compile(optimizer='sgd', loss='mean_squared_error')
</code></pre>
<p>Here is the error -</p>
<pre><code>ValueError: in user code:
File "/usr/local/lib/python3.10/dist-packages/keras/engine/training.py", line 1284, in train_function *
return step_function(self, iterator)
File "/usr/local/lib/python3.10/dist-packages/keras/engine/training.py", line 1268, in step_function **
outputs = model.distribute_strategy.run(run_step, args=(data,))
File "/usr/local/lib/python3.10/dist-packages/keras/engine/training.py", line 1249, in run_step **
outputs = model.train_step(data)
File "/usr/local/lib/python3.10/dist-packages/keras/engine/training.py", line 1050, in train_step
y_pred = self(x, training=True)
File "/usr/local/lib/python3.10/dist-packages/keras/utils/traceback_utils.py", line 70, in error_handler
raise e.with_traceback(filtered_tb) from None
File "/usr/local/lib/python3.10/dist-packages/keras/engine/input_spec.py", line 253, in assert_input_compatibility
raise ValueError(
ValueError: Exception encountered when calling layer 'sequential_13' (type Sequential).
Input 0 of layer "dense_13" is incompatible with the layer: expected min_ndim=2, found ndim=1. Full shape received: (None,)
Call arguments received by layer 'sequential_13' (type Sequential):
• inputs=tf.Tensor(shape=(None,), dtype=float32)
• training=True
• mask=None
</code></pre>
<p>Here is the rest of the code I am using to train and predict the model.</p>
<pre><code>model.fit(xs, ys, epochs=20)
model.predict([10.0])
</code></pre>
<p>Why <code>model1</code> works, despite not using a <code>tuple</code>, and why <code>model3</code> fails despite specifying <code>optional batch_size</code> argument as <code>null</code>?</p>
| <python><keras><neural-network><tensorflow2.0><tf.keras> | 2023-09-02 20:41:00 | 1 | 375 | Ujjwal Vaish |
77,029,938 | 1,392,104 | Change django.forms.models.ModelChoiceIterator | <p>The choices variable of one of my fields (django.forms.models.ModelChoiceIterator) in ModelForm contains 3 items.
In some cases, I want to use only one of them (the first one in the "list") for the actual HTML.</p>
<p>Here's a part of the Django Python code:</p>
<p>class MyForm(ModelForm):</p>
<pre><code>def __init__(self, *args, user=None, **kwargs):
choices = self.fields['xxx'].choices
qs = choices.queryset
qs = qs[:1]
...
...
self.fields['xxx'] = forms.ChoiceField(
label="xxx",
widget=forms.Select(
attrs={
'class': 'form-select' }
),
self.fields['xxx'].choices = choices
self.fields['xxx'].choices.queryset = qs
class Meta:
...
model = MyModel
fields = ('xxx')
...
</code></pre>
<p>This throws an error : 'list' object has no attribute 'queryset'" and, obviously, the size and content of choices do not change.<br />
<strong>choices</strong> is an instance of django.forms.models.ModelChoiceIterator
How can I reduce the number of items in the <strong>choices</strong> which will be displayed in the HTML ?</p>
| <python><django><modelform> | 2023-09-02 20:29:50 | 1 | 529 | tamirko |
77,029,834 | 16,284,229 | How to use try catch for multiple sections of code raising the same Exception? | <p>I have the code below, the until function raises a <code>TimeoutException</code> if the lambda function does not return an element. The problem is, that there are multiple sections of code that raise the same error, both when closing the cookies footer and finding the product title. I imagine it would be incredibly difficult to debug if multiple sections of code raise the same Exception. I initially thought of using the check on the string converted error message <code>str(e)</code>, but the <code>TimeoutException</code> also does not provide a useful message. Should I wrap a <code>try-except</code> statement for each section of code?</p>
<p>thanks</p>
<pre><code>try:
#Closes cookies footer
reject_cookies_btn = self.wait.until(lambda driver: driver.find_element(By.CSS_SELECTOR, "[data-type='no']"))
self.wait.until(EC.element_to_be_clickable(reject_cookies_btn))
reject_cookies_btn.click()
#Finds the product title and sets the product_description dictionary
product_title = self.wait.until(lambda driver : driver.find_element(By.CSS_SELECTOR, "[class='title-name a-fonts--26 a-colors--black-t js-detail-title']"))
product_description["title"] = product_title.text
except TimeoutException as e:
print(str(e))
</code></pre>
| <python><python-3.x><selenium-webdriver> | 2023-09-02 19:55:17 | 2 | 305 | Tech Visionary |
77,029,779 | 1,492,229 | why merging dataframes is not working the way is intended in python | <p>I have a dataframe df</p>
<p>it looks like this</p>
<pre><code> Weight Height Depth RepID Code
0 18 3 14 257428 0
1 6 0 6 214932 0
2 21 6 16 17675 0
3 45 6 20 60819 0
4 30 6 16 262530 0
... ... ... ... ...
4223 36 6 28 331596 1
4224 24 9 0 331597 1
4225 36 12 8 331632 1
4226 24 24 0 331633 1
4227 30 9 0 331634 1
[4228 rows x 5 columns]
</code></pre>
<p>I broke it down in test and training datasets</p>
<pre><code>y = df["Code"]
X = df.drop("Code", axis=1, errors='ignore')
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=TestSize, random_state=56)
</code></pre>
<p>then predict the values</p>
<pre><code> clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
</code></pre>
<p>now I want to keep the predicted results along with its related RepID in a file</p>
<p>so i did this</p>
<pre><code> dfCSV = X_test["RepID"]
dfCSV["Code"] = pd.DataFrame(y_pred)
dfCSV.to_csv(PredictionFile)
</code></pre>
<p>expecting the ended dataframe would like this</p>
<pre><code> RepID Code
0 84833 0
1 38388 1
2 2848 0
3 2992 1
4 28279 0
.... ...
423 74993 1
424 39924 1
425 55339 0
426 33882 1
427 64490 1
</code></pre>
<p>but the result is something to see for the first time is this</p>
<pre><code>dfCSV
Out[15]:
3792 262578
482 129648
62 7144
2998 127711
840 157391
207 277899
569 89965
2895 116296
570 279183
ICD10 0
0 1
1 1
2 0
3 1
4 0
.. ...
Name: RepID, Length: 847, dtype: object
</code></pre>
<p>what is going on and how to fix it?</p>
| <python><arrays><pandas><dataframe> | 2023-09-02 19:36:07 | 2 | 8,150 | asmgx |
77,029,732 | 4,645,982 | Getting Error cors "Request header field responsetype is not allowed by Access-Control-Allow-Headers in preflight response" in django | <p>Error in the browser console</p>
<blockquote>
<p>Access to XMLHttpRequest at<br />
'https:///some_site/resource1/downloadCSV' from origin 'https://some_site' has been blocked by CORS policy: Request header field responsetype is not allowed by Access-Control-Allow-Headers in preflight response.</p>
</blockquote>
<p>check the API Method</p>
<pre><code>@api_view(["POST"])
def downloadCSV(request):
request_body = request.data
response = HttpResponse(
some_service.call_some_other_service(),
content_type="application/octet-streamf",
)
today = datetime.today().strftime("%Y-%m-%d")
filename = f"{today}_Data.csv"
response["Content-Disposition"] = f'attachment; filename="{filename}.csv"'
return response
</code></pre>
<p>main/settings.py</p>
<pre><code>INSTALLED_APPS = [
.............
"corsheaders",
........
]
MIDDLEWARE = [
"corsheaders.middleware.CorsMiddleware",
]
CORS_ORIGIN_ALLOW_ALL = True
</code></pre>
<p>I can't do it because the other response type header is failing, Please suggest how to allow the responseType =bob so that I will able to download API.</p>
<pre><code>CORS_ALLOW_HEADERS = [
# ...
'responsetype',
# ...
]
</code></pre>
| <python><django><django-models><django-rest-framework><cors> | 2023-09-02 19:20:20 | 1 | 2,676 | Neelabh Singh |
77,029,695 | 2,497,309 | Installing NodeJS on AWS Lambda Python Container Image | <p>I'm trying to build a custom docker image starting from</p>
<pre><code>FROM public.ecr.aws/lambda/python:3.11
</code></pre>
<p>This docker image only has Python installed but I also want to install NodeJS and use NPM to install aws-cdk on it and deploy a stack to CloudFormation via the python lambda. I've tried a bunch of different ways to install NodeJS but I haven't been able to get it working. This is what I have so far with some of the statements commented out (which I tested but didn't work).</p>
<pre><code>FROM public.ecr.aws/lambda/python:3.11
# FROM public.ecr.aws/lambda/nodejs:18
# https://docs.aws.amazon.com/lambda/latest/dg/python-image.html#python-image-instructions
COPY . ${LAMBDA_TASK_ROOT}
# Install packages
# RUN yum -y update && \
# yum -y install wget && \
# yum install -y tar.x86_64 && \
# yum clean all
# RUN yum install nodejs npm
# RUN touch ~/.bashrc && chmod +x ~/.bashrc
# RUN curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/install.sh | bash
# RUN . ~/.nvm/nvm.sh && nvm install node
RUN yum update
RUN yum install https://rpm.nodesource.com/pub_20.x/nodistro/repo/nodesource-release-nodistro-1.noarch.rpm -y
RUN yum install nsolid -y
# RUN curl --silent --location https://rpm.nodesource.com/setup_20.x | bash -
RUN yum install nodejs
RUN yum install -y python3
RUN yum install -y python3-pip
# RUN pip install --upgrade pip
RUN pip3 install -r requirements.txt
# Update NPM
RUN npm update -g
# Install AWSCLI
RUN pip3 install --upgrade awscli
# Install cdk
RUN npm install -g aws-cdk
RUN cdk --version
# Set the CMD to your handler (could also be done as a parameter override outside of the Dockerfile)
CMD [ "cdk_handler.handler" ]
</code></pre>
<p>The error when I try to build this specific image is:</p>
<pre><code>1.950 Error: Package: nodesource-release-nodistro-1.noarch (/nodesource-release-nodistro-1.noarch)
1.950 Requires: glibc >= 2.28
1.950 Installed: glibc-2.26-63.amzn2.x86_64 (@amzn2-core)
1.950 glibc = 2.26-63.amzn2
1.950 Available: glibc-2.25-10.amzn2.0.1.x86_64 (amzn2-core)
1.950 glibc = 2.25-10.amzn2.0.1
1.950 Available: glibc-2.26-27.amzn2.0.4.x86_64 (amzn2-core)
1.950 glibc = 2.26-27.amzn2.0.4
1.950 Available: glibc-2.26-27.amzn2.0.5.i686 (amzn2-core)
1.950 glibc = 2.26-27.amzn2.0.5
...
</code></pre>
<p>Simply trying the</p>
<pre><code>RUN yum install nodejs
</code></pre>
<p>results in the following error:</p>
<pre><code> > [ 4/11] RUN yum install nodejs:
0.401 Loaded plugins: ovl
0.620 No package nodejs available.
0.633 Error: Nothing to do
</code></pre>
| <python><node.js><amazon-web-services><docker><aws-lambda> | 2023-09-02 19:08:39 | 1 | 947 | asm |
77,029,693 | 13,584,963 | Python do np.logical_and in parallel like np.max(array, axis=1) | <p>I have a 2D bool array of shape row*col, is there any efficient way to horizontally perform the <code>AND</code> operation to the array?
For example,</p>
<pre><code>k = np.array([[True, True, False],
[True, False, False],
[True, True, True]])
</code></pre>
<p>The result is expected to be</p>
<pre><code>np.array([False, False, True])
</code></pre>
<p>Both row and col are quite large, and doing <code>for</code> takes more than 12 seconds per 5 million operations. I have thousands of this 5-million operations per task, which takes extremely long.</p>
| <python><arrays><numpy> | 2023-09-02 19:07:08 | 2 | 311 | Crear |
77,029,596 | 1,951,176 | CPU time > wall time in Python multihreading | <p>A wrote a short piece of code in Python that uses multiple threads (but a single process) and ran it with a timer:</p>
<pre class="lang-py prettyprint-override"><code>import random
a = "".join([chr(ord('a') + random.randint(1, 20)) for _ in range(50_000_000)])
def sum_part(i):
part = a[i * 20_000_000: (i+1) * 20_000_000]
size = 1_000_000
splits = [part[j: j + size] for j in range(0, len(part), size)]
hashes = [hashlib.sha1(bytes(k, "utf-8")).hexdigest() for k in splits]
return "".join(hashes)
def calc_split():
threads = [threading.Thread(target=sum_part, args=[i]) for i in range(2)]
for t in threads:
t.start()
for t in threads:
t.join()
</code></pre>
<p>I got these results:</p>
<pre><code>CPU times: user 118 ms, sys: 36.7 ms, total: 155 ms
Wall time: 110 ms
</code></pre>
<p>If this was C++, user time > wall time would not surprise me: the CPU time corresponds to per-cpu-thread time. However, as I understand it, with GIL there should only ever be a single CPU thread involved. What am I missing?</p>
| <python><multithreading> | 2023-09-02 18:41:25 | 2 | 4,687 | sygi |
77,029,549 | 1,008,596 | using vertex ai in custom python script outside AI workbench and collab fails with permission denied | <p>I'm trying to use GCP Vertex AI outside of a GCP managed AI Workbench notebook environment or Google Collab notebook environment. Specifically I am trying to run in an self hosted jupyter notebook environment. Here is my setup and problem:</p>
<h1>Setup</h1>
<h2>Setup GCP and shell running python</h2>
<p>We used info from two primary sources:</p>
<ul>
<li>CloudSkillsBoost.google GenAI learning path to create a service account and setup permissions for the service account</li>
<li><a href="https://github.com/GoogleCloudPlatform/generative-ai/blob/main/language/prompts/intro_prompt_design.ipynb" rel="nofollow noreferrer">GoogleCloudPlatform/generative-ai github repo</a> to model the python code</li>
</ul>
<h3>install gcloud</h3>
<p>This is using a Debian linux environment</p>
<pre><code>$ sudo apt-get install apt-transport-https ca-certificates gnupg curl sudo
$ echo "deb [signed-by=/usr/share/keyrings/cloud.google.gpg] https://packages.cloud.google.com/apt cloud-sdk main" | sudo tee -a /etc/apt/sources.list.d/google-cloud-sdk.list
$ curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key --keyring /usr/share/keyrings/cloud.google.gpg add -
$ sudo apt-get update && sudo apt-get install google-cloud-cli
$ gcloud init
</code></pre>
<h4>setup authentication and authorization</h4>
<p>These api enables are a bit overkill, but you are not charged for enabling the api's. Charges only incur based upon usage.</p>
<p>Enable services</p>
<pre><code>$ gcloud services enable \
compute.googleapis.com \
iam.googleapis.com \
iamcredentials.googleapis.com \
monitoring.googleapis.com \
logging.googleapis.com \
notebooks.googleapis.com \
aiplatform.googleapis.com \
bigquery.googleapis.com \
artifactregistry.googleapis.com \
cloudbuild.googleapis.com \
container.googleapis.com
</code></pre>
<p>Create custom service account</p>
<p>Authentication</p>
<pre><code>$ SERVICE_ACCOUNT_ID=vertex-custom-training-sa
$ gcloud iam service-accounts create $SERVICE_ACCOUNT_ID \
--description="A custom service account for Vertex custom training with Tensorboard" \
--display-name="Vertex AI Custom Training"
</code></pre>
<p>Authorization</p>
<p>Grant for Vertex AI to run model training, deployment and prediction</p>
<pre><code>$ gcloud projects add-iam-policy-binding $PROJECT_ID \
--member=serviceAccount:$SERVICE_ACCOUNT_ID@$PROJECT_ID.iam.gserviceaccount.com \
--role="roles/aiplatform.user"
</code></pre>
<p>Lastly, from this <a href="https://cloud.google.com/docs/authentication/provide-credentials-adc#how-to" rel="nofollow noreferrer">guide</a></p>
<pre><code># orig from guide
# $ gcloud auth application-default login --impersonate-service-account SERVICE_ACCT_EMAIL
# our version
$ gcloud auth application-default login --impersonate-service-account $SERVICE_ACCOUNT_ID@$PROJECT_ID.iam.gserviceaccount.com
</code></pre>
<p>Testing the result of expansion of the email for the service account, it did match the service account email in IAM microservice with the gcp project as shown here: (This shows BigQuery and Cloud Storage enabled, but the key is that vertex ai is enabled.) (Furthermore, in the marketplace for the project we also have vertex ai enabled. This might only enable the api in the project, but not the use of the API from outside the hosted workbench. Likewise when I searched for Vertex AI API as an api role, I did not find it. I found platform API and I wonder if its the only api available as a generic api outside of hosted workbench notebooks.)</p>
<p><a href="https://i.sstatic.net/c1SFu.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/c1SFu.png" alt="enter image description here" /></a></p>
<h2>Setup of jupyter notebook</h2>
<p>These are from a jupyter notebook. All code is in python with the exception of the python pip commands done for the shell - these can be distinguised by the use of <code>!</code>.</p>
<pre><code># install the google cloud AI api
!pip install "shapely<2.0.0"
!pip install google-cloud-aiplatform --upgrade
# Import the os package
import os
import vertexai
PROJECT_ID = os.environ['GCP_PROJ_ID'] # @param {type:"string"}
vertexai.init(project=PROJECT_ID, location="us-central1")
# test the gcp vertex AI
from vertexai.language_models import TextGenerationModel
# these were checks to see if we had our environment set correctly.
# It showed the environment variable had the path specified correctly
# for the json credential file and that we could access the
# credentials.
#print(os.environ['GOOGLE_APPLICATION_CREDENTIALS'])
#os.system('cat application_default_credentials.json')
#os.system('pwd')
#os.system('ls')
# load the model
# this failed with "status": "PERMISSION_DENIED"
# I'm not sure if it was permission denied on loading the JSON file
# or if the service account credentials did not have access to the
# API.
generation_model = TextGenerationModel.from_pretrained("text-bison@001")
</code></pre>
<h1>Problem</h1>
<p>The last line shown above gets a permission denied result.</p>
<h1>Lastly</h1>
<p>This info might be better seen in total in github. The github with the text and notebook is shown <a href="https://github.com/rtp-gcp/gcp_icy_bridge/blob/master/genai/notebooks/gcp.ipynb" rel="nofollow noreferrer">here</a>.</p>
| <python><google-cloud-platform><jupyter-notebook><google-cloud-vertex-ai> | 2023-09-02 18:29:30 | 1 | 4,629 | netskink |
77,029,486 | 1,020,139 | Why does pip on Amazon Linux 2 download lxml-4.9.3.tar.gz, while it downloads lxml-4.9.3-cp311-cp311-manylinux_2_28_aarch64.whl on Amazon Linux 2023? | <blockquote>
<p>Why does pip on Amazon Linux 2 download lxml-4.9.3.tar.gz, while it downloads lxml-4.9.3-cp311-cp311-manylinux_2_28_aarch64.whl on Amazon Linux 2023?</p>
</blockquote>
<p>I need to download and install the <code>manylinux</code> variant, as the former doesn't work on AWS Lambda, yielding the following error:</p>
<pre><code>"Unable to import module 'app.dim.application.watchdog': libxslt.so.1: cannot open shared object file: No such file or directory"
</code></pre>
<p>Why does <code>pip</code> (<code>python@3.11.2</code>) download the<code>manylinux</code> variant, while <code>pip</code> (<code>python@3.11.4</code>) download the source package?</p>
<p>What's the difference between these packages, and why does the <code>manylinux</code> variant work in AWS Lambda, while the source package doesn't (both create a wheel)?</p>
| <python><amazon-web-services><pip><python-poetry> | 2023-09-02 18:11:27 | 1 | 14,560 | Shuzheng |
77,029,483 | 74,497 | Why do I run out of memory when training with a large dataset, but have no problems with a small dataset? | <p>I'm trying to build a keypoint detection system using Keras. I've got a UNet like model, with a series of convolutions, batch normalization, and max pooling, followed by a symmetric series of up sampling, convolution, and batch normalization layers (and skip connections). When given 100 instances, I'm able to call <code>model.fit()</code> without a problem. However, if I leave the model the same but use 500 instances, Keras crashes with an OOM exception. Why does this happen, and is there anything I can do to fix it?</p>
<p>Here's (what I think is) the relevant part of the code where I call <code>model.fit</code>:</p>
<pre class="lang-py prettyprint-override"><code>model = build_model(
filters=50,
filter_step=1,
stages=5,
stage_steps=1,
initial_convolutions=0,
stacks=1,
)
print(model.summary())
dataset = tf.data.Dataset.from_tensor_slices((X, y))
dataset = dataset.batch(1)
model.fit(
dataset,
epochs=2**7,
callbacks=[
EarlyStopping(monitor="loss", patience=5, min_delta=1e-7, start_from_epoch=10),
LearningRateScheduler(step_decay)
],
)
</code></pre>
<p><code>X</code> and <code>y</code> are Numpy arrays with the following shapes:</p>
<ul>
<li><code>X</code>: (100, 1024, 1024, 3)</li>
<li><code>y</code>: (100, 1024, 1024)</li>
</ul>
<p>100 here is the data set size. If I increase this to 500 (or more), I get the out-of-memory exception. It appears to me that Keras is perhaps trying to load the entire data set into memory, despite using <code>from_tensor_slices</code> and <code>batch(1)</code>, so I'm clearly misunderstanding something.</p>
| <python><tensorflow><machine-learning><keras> | 2023-09-02 18:10:13 | 3 | 6,088 | ocharles |
77,029,478 | 39,381 | Parsing several multi-line blocks with pyparsing | <p>I'm a complete pyparsing newbie, and am trying to parse a large file with multi-line blocks describing archive files and their contents.</p>
<p>I'm currently at the stage where I'm able to parse a single item (no starting newline, this hardcoded test data approximates reading in a real file):</p>
<pre class="lang-py prettyprint-override"><code> import pyparsing as pp
one_archive = \
"""archive (
name "something wicked this way comes.zip"
file ( name wicked.exe size 140084 date 2022/12/24 23:32:00 crc B2CF5E58 )
file ( name readme.txt size 1704 date 2022/12/24 23:32:00 crc 37F73AEE )
)
"""
pp.ParserElement.set_default_whitespace_chars(' \t')
EOL = pp.LineEnd().suppress()
start_of_archive_block = pp.LineStart() + pp.Keyword('archive (') + EOL
end_of_archive_block = pp.LineStart() + ')' + EOL
archive_filename = pp.LineStart() \
+ pp.Keyword('name').suppress() \
+ pp.Literal('"').suppress() \
+ pp.SkipTo(pp.Literal('"')).set_results_name("archive_name") \
+ pp.Literal('"').suppress() \
+ EOL
field_elem = pp.Keyword('name').suppress() + pp.SkipTo(pp.Literal(' size')).set_results_name("filename") \
^ pp.Keyword('size').suppress() + pp.SkipTo(pp.Literal(' date')).set_results_name("size") \
^ pp.Keyword('date').suppress() + pp.SkipTo(pp.Literal(' crc')).set_results_name("date") \
^ pp.Keyword('crc').suppress() + pp.SkipTo(pp.Literal(' )')).set_results_name("crc")
fields = field_elem * 4
filerow = pp.LineStart() \
+ pp.Literal('file (').suppress() \
+ fields \
+ pp.Literal(')').suppress() \
+ EOL
archive = start_of_archive_block.suppress() \
+ archive_filename \
+ pp.OneOrMore(pp.Group(filerow)) \
+ end_of_archive_block.suppress()
archive.parse_string(one_archive, parse_all=True)
</code></pre>
<p>The result is a ParseResults object with all the data I need from that single archive. (For some reason, the trailing newline in the input string causes no problems, despite me doing nothing to actively handle it.)</p>
<p>However, try as I might, I cannot get from this point to a point where I could parse the following, more realistic data. The new features I need to handle are:</p>
<ul>
<li>a single <code>file_metadata</code> block that starts the file (I don't need it in my parsing results, it can be skipped entirely)</li>
<li>multiple <code>archive</code> items</li>
<li>newlines between the <code>archive</code> items</li>
</ul>
<pre class="lang-py prettyprint-override"><code>realistic_data = \
"""
file_metadata (
description: blah blah etc.
author: john doe
version: 0.99
)
archive (
name "something wicked this way comes.zip"
file ( name wicked.exe size 140084 date 2022/12/24 23:32:00 crc B2CF5E58 )
file ( name readme.txt size 1704 date 2022/12/24 23:32:00 crc 37F73AEE )
)
archive (
name "naughty or nice.zip"
file ( name naughty.exe size 187232 date 2021/8/4 10:19:55 crc 638BC6AA )
file ( name nice.exe size 298234 date 2021/8/4 10:19:56 crc 99FD31AE )
file ( name whatever.jpg size 25603 date 2021/8/5 11:03:09 crc ABFAC314 )
)
"""
</code></pre>
<p>I've been semi-randomly trying a variety of things, but I have large fundamental gaps in my understanding of how pyparsing works, so they're not worth itemizing here. Someone who knows what they're doing can probably immediately see what to do here.</p>
<p>My ultimate goal is to parse all of these archive items and store them in a database.</p>
<p>What's the solution?</p>
| <python><parsing><pyparsing> | 2023-09-02 18:08:45 | 1 | 3,926 | JK Laiho |
77,029,411 | 8,948,544 | Returning a json response when using flask_sqlalchemy and autoload_with | <p>I am creating a python program to connect to an existing SQLITE database and provide a JSON endpoint to access the contents of a table. But I can't seem to figure out how to convert the Rows returned from a query into a JSON serializable format.</p>
<p>Here is my code:</p>
<pre><code>from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import json
from sqlalchemy.inspection import inspect
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///some-path\\db.sqlite'
db = SQLAlchemy(app)
app.app_context().push()
db.reflect()
Images = db.Table(
"images",
db.Model.metadata,
autoload_with=db.engine
)
@app.route("/all")
def alldata():
alldata =db.session.query(Images).all()
results = [tuple(row) for row in alldata]
return json.loads(json.dumps(results))
</code></pre>
<p>The above code works but loses all the column names (plus it feels extremely messy).</p>
<p>All of the solutions I have found recommend adding some sort of serialization function to my <code>Images</code> class ... but the problem with that is I have not created a class to represent my tables structure (instead, I'm using <code>autoload_with</code>).</p>
<p>What am I doing wrong and what is the right way to do this? Am I using <code>autoload_with</code> incorrectly?</p>
<h1>UPDATE 1:</h1>
<p>I have tried the following:</p>
<pre><code>@app.route("/all")
def alldata():
return db.session.execute(db.select(Images)).mappings()
</code></pre>
<p>Unfortunately, this results in <code>AssertionError: applications must write bytes</code></p>
<h1>UPDATE 2</h1>
<p>This: <code>return db.session.execute(db.select(Images)).mappings().all()</code> gives the following error:
<code>Object of type RowMapping is not JSON serializable</code></p>
<h1>UPDATE 3</h1>
<p>This is the code I used to create the original images table with <code>sqlalchemy</code>:</p>
<pre><code>images = Table(
'images', meta,
Column('id', Integer, primary_key = True),
Column('url', String),
Column('meta', String)
)
</code></pre>
| <python><flask-sqlalchemy> | 2023-09-02 17:51:49 | 0 | 331 | Karthik Sankaran |
77,029,403 | 2,555,515 | Querying large dataset from Snowflake with Python/psycopg2 | <p>We have large simple dataset with two columns: tension. and time and a foreign key device_id stored in Snowflake. We query like</p>
<pre><code>def get_waveform(self, device_id):
sql = """
select tension, time from waveform
where device_id = %s;
"""
with self.conn.cursor() as cursor:
# This will take 12 minutes for one waveform.
results = cursor.execute(sql, (device_id,))
waveform = results.fetchall()
return waveform;
</code></pre>
<p>Each device has exactly 50 mln rows. Querying this amount of data in Snowflake takes about 15 seconds on 1000Mbs network. However doing it from Python/psycopg2 is unusably long - about 12 minutes when we use fetchall. Splitting the query into smaller chunks of 1 mln each and calling fetchmany(1000000) makes things little worse about 15 minutes for all 50 queries.</p>
<p>My guess is the most of the time is spent parsing the query results on the client and creating the result array. Is there a workaround besides dumping Python and rewriting everything in one of the compiled languages ?</p>
| <python><snowflake-cloud-data-platform><psycopg2> | 2023-09-02 17:49:55 | 1 | 1,089 | user2555515 |
77,028,948 | 10,441,038 | Equivalent of C++ union in Python? | <p>I need to precisely save a lot of floating numbers to a file in C++ program, and then read them in Python.</p>
<p>You known that the precision of floating numbers may be lost when we convert them into/out from string.</p>
<p>I'm wondering that "Is there an equivalent of union in Python?" If so, I can do it as following:</p>
<p>C++ program:</p>
<pre class="lang-cpp prettyprint-override"><code>union Convert_t {
// this occupys 8 bytes
double asDouble;
// this occupies 8 bytes too, so we just only treat a double as a int64
int64_t asIntegr;
};
// when preparing data
Convert_t data;
data.asDouble = real_data;
out_csv_stream << data.asIntegr << ',';
</code></pre>
<p>When read data in Python program:</p>
<pre class="lang-py prettyprint-override"><code>import typing
import pandas as pd
# now the type of contents should be int64
pd.read_csv(csv_path)
# I don't known how to writing correctly follow lines
class PyConvert : typing.Union
asDouble : numpy.float64
asIntegr : numpy.int64
</code></pre>
<p>I think my question is different to <a href="https://stackoverflow.com/questions/45383771/equivalent-c-union-in-python">that question and answer</a>. That answer doesn't show how to convert data into a floating type, and it was using cdll.LoadLibrary() that was not required for me.</p>
| <python><c++><python-3.x><type-conversion><unions> | 2023-09-02 15:47:47 | 0 | 2,165 | Leon |
77,028,925 | 12,396,154 | Docker Compose Fails: error: externally-managed-environment | <p>I am using a windows machine and have installed wsl to be able to use Docker desktop. Of course the build failed and then I observed python3 and pip3 in the dockerfile. So I installed ubuntu and debian via wsl and then tried to run the app (docker-compose up). It still fails and throws the following error:</p>
<pre><code> ERROR [test 3/5] RUN pip3 install daff==1.3.46 0.9s
------
> [test 3/5] RUN pip3 install daff==1.3.46:
0.812 error: externally-managed-environment
0.812
0.812 × This environment is externally managed
0.812 ╰─> To install Python packages system-wide, try apt install
0.812 python3-xyz, where xyz is the package you are trying to
0.812 install.
0.812
0.812 If you wish to install a non-Debian-packaged Python package,
0.812 create a virtual environment using python3 -m venv path/to/venv.
0.812 Then use path/to/venv/bin/python and path/to/venv/bin/pip. Make
0.812 sure you have python3-full installed.
0.812
0.812 If you wish to install a non-Debian packaged Python application,
0.812 it may be easiest to use pipx install xyz, which will manage a
0.812 virtual environment for you. Make sure you have pipx installed.
0.812
0.812 See /usr/share/doc/python3.11/README.venv for more information.
0.812
0.812 note: If you believe this is a mistake, please contact your Python installation or OS distribution provider. You can override this, at the risk of breaking your Python installation or OS, by passing --break-system-packages.
0.812 hint: See PEP 668 for the detailed specification.
------
failed to solve: process "/bin/sh -c pip3 install daff==1.3.46" did not complete successfully: exit code: 1
</code></pre>
<p>Here's the DockerFile:</p>
<pre><code>FROM postgres:12
RUN apt-get update && apt-get install -y \
python3 \
python3-pip
RUN pip3 install daff==1.3.46
# Copy project files
COPY . /app
WORKDIR /app
ENV PATH=$PATH:/app/bin
</code></pre>
<p>Any idea how to resolve the issue?
Because I'm using docker, this <a href="https://stackoverflow.com/questions/75608323/how-do-i-solve-error-externally-managed-environment-everytime-i-use-pip3">How do I solve "error: externally-managed-environment" everytime I use pip3?</a> doesn't help me.</p>
| <python><docker><docker-compose><windows-subsystem-for-linux> | 2023-09-02 15:41:15 | 1 | 353 | Nili |
77,028,828 | 6,615,512 | Why are numpy operations with float32 significantly faster than float64? | <p>Doing some optimizing I noticed that switching from float64 to float32 improves run time a <em>lot</em> with some numpy ops. 5x in the example below. I know that data types are just handled differently and have hardware dependencies and such (see questions <a href="https://stackoverflow.com/q/15340781">here</a> and <a href="https://stackoverflow.com/q/56697332">here</a>). But why specifically am I seeing the following, and is there anything I can do to make 64 bit as fast?</p>
<pre><code>import numpy as np
import timeit
arr64 = np.random.random(size=10000).astype(np.float64)
arr32 = np.random.random(size=10000).astype(np.float32)
time64 = timeit.timeit(lambda :np.exp(arr64), number=10000)
time32 = timeit.timeit(lambda :np.exp(arr32), number=10000)
print(f'64bit time: {time64}')
print(f'32bit time: {time32}')
64bit time: 0.797928056679666
32bit time: 0.15939769614487886
</code></pre>
<p>Note I'm on Ubuntu with python 3.9.17 and numpy 1.25.2</p>
| <python><numpy> | 2023-09-02 15:11:56 | 1 | 391 | Shawn |
77,028,770 | 1,469,954 | ThreadPoolExecutor task for downloading files in bulk downloads only last file in list | <p>I have a file called <code>images.txt</code>, which is just a list of image URLs, one per line:</p>
<pre><code>https://upload.wikimedia.org/wikipedia/commons/thumb/3/3e/Glenn_Jacobs_%2853122237030%29_-_Cropped.jpg/440px-Glenn_Jacobs_%2853122237030%29_-_Cropped.jpg
https://upload.wikimedia.org/wikipedia/commons/thumb/d/de/Kane2003.jpg/340px-Kane2003.jpg
https://upload.wikimedia.org/wikipedia/commons/7/7a/Steel_Cage.jpg
https://upload.wikimedia.org/wikipedia/commons/thumb/c/cd/Kane_2008.JPG/340px-Kane_2008.JPG
https://upload.wikimedia.org/wikipedia/commons/thumb/e/e4/Brothers_of_Destruction.jpg/440px-Brothers_of_Destruction.jpg
</code></pre>
<p>I want to start a thread-pool executor with <code>20</code> worker threads that downloads each image in a separate thread, into a local subdirectory called "<code>images</code>". This is the code I am trying. Problem is - it prints that it is downloading all images, but ultimately only one image - the last one in the list, gets downloaded, rest are never downloaded.</p>
<pre><code>from os import makedirs
from os.path import basename
from os.path import join
import shutil
from concurrent.futures import ThreadPoolExecutor
from concurrent.futures import as_completed
import requests
# load a file from a URL, returns content of downloaded file
def download_url(urlpath, dir):
# Set the headers for the request
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"Accept-Language": "en-US,en;q=0.9"
}
r = requests.get(urlpath, headers=headers, stream=True)
filename = basename(urlpath)
outpath = join(dir, filename)
if r.status_code == 200:
with open(outpath, 'wb') as f:
r.raw.decode_content = True
shutil.copyfileobj(r.raw, f)
# download one file to a local directory
def download_url_to_file(link, path):
download_url(link, path)
return link
# download all files on the provided webpage to the provided path
def getInBulk(filePath, path):
# download the html webpage
# create a local directory to save files
makedirs(path, exist_ok=True)
# parse html and retrieve all href urls listed
links = open(filePath).readlines()
# report progress
print(f'Found {len(links)} links')
# create the pool of worker threads
with ThreadPoolExecutor(max_workers=20) as exe:
# dispatch all download tasks to worker threads
futures = [exe.submit(download_url_to_file, link, path) for link in links]
# report results as they become available
for future in as_completed(futures):
# retrieve result
link = future.result()
# check for a link that was skipped
print(f'Downloaded {link} to directory')
PATH = 'images'
filePath = "images.txt"
getInBulk(filePath, PATH)
</code></pre>
<p>Any idea what I am doing wrong, and how to fix it?</p>
| <python><multithreading><python-requests><urllib><threadpoolexecutor> | 2023-09-02 14:57:57 | 1 | 5,353 | NedStarkOfWinterfell |
77,028,576 | 2,182,542 | patch() from unittest.mock doesn't work in a subprocess | <p>It seems that <code>patch()</code> from <code>unittest.mock</code> does not work as expected in subprocesses spawned with <code>multiprocessing</code> module for me.</p>
<p>Here is my code:</p>
<p>a.py</p>
<pre><code>import multiprocessing
from unittest.mock import patch
from b import run_new_process, call_mocked_function
def main():
with patch("b.function_to_mock"):
context = multiprocessing.get_context(multiprocessing.get_start_method())
process = context.Process(target=run_new_process, args=())
print("call from the main process")
call_mocked_function()
process.start()
process.join()
if __name__ == '__main__':
main()
</code></pre>
<p>b.py</p>
<pre><code>def run_new_process():
print("call from the subprocess")
function_to_mock()
def call_mocked_function():
function_to_mock()
def function_to_mock():
print("inside real function body")
</code></pre>
<p>The output of this code is:</p>
<pre><code>call from the main process
call from the subprocess
inside real function body
</code></pre>
<p>So the function is mocked as expected when invoked from the same process, but the real body is accessed when I call it from subprocess. Why? When I run a.py, I expect NOT to see function_to_mock() body ever invoked.</p>
<p>Expected output:</p>
<pre><code>call from the the main process
call from the subprocess
</code></pre>
<p>I am using Python 3.11.5.</p>
<p>My context: this example is actually a trimmed down fragment of Airflow test code which I want to modify (<a href="https://github.com/apache/airflow/blob/b6318ffabce8cc3fdb02c30842726476b7e1fcca/tests/jobs/test_scheduler_job.py#L157" rel="nofollow noreferrer">https://github.com/apache/airflow/blob/b6318ffabce8cc3fdb02c30842726476b7e1fcca/tests/jobs/test_scheduler_job.py#L157</a>) - apparently it works on their CI but not on my local environment so I'm trying to figure out the difference between setups.</p>
| <python><python-multiprocessing><python-unittest> | 2023-09-02 13:58:00 | 1 | 1,114 | Danio |
77,028,331 | 4,575,197 | How to get Fama-Macbeth Regression Cross-sectionally in python | <p>I am very new to this topic and I'm confused with understanding the regression and Quantitative aspects of it, although i have found amazing posts like <a href="https://quant.stackexchange.com/questions/46746/rationale-of-fama-macbeth-procedure?rq=1">rationale-of-fama-macbeth-procedure</a>,
<a href="https://quant.stackexchange.com/questions/42610/fama-macbeth-cross-sectional-regression/42616#42616">fama-macbeth-cross-sectional-regression</a>, <a href="https://quant.stackexchange.com/questions/32305/what-are-the-assumptions-in-the-first-stage-of-fama-macbeth-1973/34144#34144">what-are-the-assumptions-in-the-first-stage-of-fama-macbeth</a>.</p>
<p>this is a sample data (stored in a dataframe), which looks like this (my actual data is monthly). In order to make it more clear for you column: RIe Pct Return is the return for each individual stock. :</p>
<pre><code>| year | date_x | month | Mcap | TotalAssets | NItoCommon | NIbefEIPrefDiv | PrefDiv | NIbefPrefDiv | Sales | GainLossAssetSale | PPT | LTDebt | CommonEquity | PrefStock | OtherIncome | TotalLiabilities | PreTaxIncome | IncomeTaxes | OtherTA | OtherLiabilities | CashSTInv | OtherCA | OtherCL | TotalDiv | Country | Industry | IsSingleCountry | SME | Mcap_w | NItoCommon_w | NIbefEIPrefDiv_w | PrefDiv_w | NIbefPrefDiv_w | Sales_w | GainLossAssetSale_w | PPT_w | LTDebt_w | CommonEquity_w | PrefStock_w | OtherIncome_w | TotalLiabilities_w | PreTaxIncome_w | IncomeTaxes_w | OtherTA_w | OtherLiabilities_w | CashSTInv_w | OtherCA_w | OtherCL_w | TotalDiv_w | fair_value | date_y | RIe | RIus | RIus Pct Return | RIe Pct Return | Total Return Index |
|------|------------|-------|------|-------------|------------|----------------|---------|--------------|-------|-------------------|-----|--------|--------------|------------|-------------|------------------|--------------|-------------|---------|------------------|------------|---------|---------|----------|---------|------------|-----------------|-----|--------|-------------|-------------|----------------|------------|---------------------|-------|---------|----------------|-------------------|-------------|-------------------|--------------|-------------|------------|-------------------|------------|----------|---------|-----------|------------|------------|-------|------|-----------------|-----------------|--------------------|
| 2011 | 2011-02-01 | 2 | 63240 | 410876 | 7227 | 7227 | 0 | 7227 | 149809 | 0 | 204034 | 183595 | 150758 | 0 | 296 | 260875 | 10394 | 3015 | 93101 | 507 | 41407 | 4677 | 29141 | 0 | BD | Manufacturing | NaN | Large enterprise | 63240.000 | 7227 | 7227 | 0 | 7227 | 149809 | 0 | 204034 | 183595 | 150758 | 0 | 296 | 260875 | 10394 | 3015 | 93101 | 507 | 41407 | 4677 | 29141 | 0 | 5.959437 | 2011-02-26 | 48.12 | 54.92 | 0.134042 | 0.077564 | 0.78 |
| 2013 | 2013-08-01 | 8 | 57030 | 370658 | 6525 | 6525 | 0 | 6525 | 134985 | 0 | 183668 | 165522 | 135862 | 0 | 267 | 235191 | 9378 | 2713 | 83949 | 457 | 37780 | 4263 | 26573 | 0 | BD | Technology | NaN | Large enterprise | 57030.000 | 6525 | 6525 | 0 | 6525 | 134985 | 0 | 183668 | 165522 | 135862 | 0 | 267 | 235191 | 9378 | 2713 | 83949 | 457 | 37780 | 4263 | 26573 | 0 | 5.565474 | 2013-08-28 | 39.27 | 45.62 | 0.103655 | 0.051828 | 0.78 |
| 2014 | 2014-11-01 | 11 | 74220 | 482008 | 8496 | 8496 | 0 | 8496 | 175824 | 0 | 238183 | 214365 | 176017 | 0 | 344 | 299626 | 11984 | 3472 | 107054 | 584 | 48195 | 5455 | 33935 | 0 | BD | Finance | NaN | Large enterprise | 74220.000 | 8496 | 8496 | 0 | 8496 | 175824 | 0 | 238183 | 214365 | 176017 | 0 | 344 | 299626 | 11984 | 3472 | 107054 | 584 | 48195 | 5455 | 33935 | 0 | 6.485548 | 2014-11-30 | 53.77 | 61.49 | 0.148460 | 0.073689 | 0.78 |
| 2015 | 2015-05-01 | 5 | 80150 | 521068 | 9184 | 9184 | 0 | 9184 | 190966 | 0 | 259146 | 233231 | 191151 | 0 | 377 | 323830 | 12953 | 3755 | 116013 | 635 | 52268 | 5923 | 36948 | 0 | BD | Retail | NaN | Large enterprise | 80150.000 | 9184 | 9184 | 0 | 9184 | 190966 | 0 | 259146 | 233231 | 191151 | 0 | 377 | 323830 | 12953 | 3755 | 116013 | 635 | 52268 | 5923 | 36948 | 0 | 7.057782 | 2015-05-30 | 56.59 | 62.13 | 0.111052 | 0.070297 | 0.78 |
| 2017 | 2017-09-01 | 9 | 69320 | 450400 | 7936 | 7936 | 0 | 7936 | 164384 | 0 | 223164 | 200848 | 164858
</code></pre>
<p>in <strong>first step</strong> i Know that i have to regress the Stock returns against the index return, to find the β. In <strong>Second step</strong> <a href="https://quant.stackexchange.com/questions/46746/rationale-of-fama-macbeth-procedure?rq=1#:%7E:text=We%20apply%20a,%2C">I should apply a cross-sectional regression at each point of time t.</a></p>
<p>Now that we are on the same page (if i have missed anything pls let me know), i want to write a code in Python to do the first and second step. I could find implementation in R but not in Python. I would rather that your answer be in a method so if in future someone wanted to do the regression on monthly or yearly basis it would be easier to change the code. If i can some how get the results in a Dataframe it would be great.</p>
<p>i tried to use this library <a href="https://fin-library.readthedocs.io/en/latest/contents.html" rel="nofollow noreferrer">finance-byu</a>, but i get all sorts of error and couldn't really find a basic and understandable example of it on the internet.</p>
<pre><code>from finance_byu.fama_macbeth import fama_macbeth, fm_summary
merged_df['date_x']=pd.to_datetime(merged_df['date_x'],format='mixed')
result=fama_macbeth(merged_df,pd.to_datetime(merged_df['date_x'],format='mixed'),'Total return index','RIe Pct Return')
print(fm_summary(result))
</code></pre>
<p>the Error that i got in this case:</p>
<blockquote>
<pre><code> 50 def _assertions(data,t,yvar,xvar,intercept,n_jobs=-999,backend=-999,memmap=-999,parallel=-999):
52 assert isinstance(data,pd.core.frame.DataFrame), 'Invalid input for `data`.'
</code></pre>
<p>---> 53 assert isinstance(t,str), 'Invalid input for <code>t</code>.'
54 assert isinstance(xvar,list), 'Invalid input for <code>xvar</code>.'
55 assert isinstance(intercept,bool), 'Invalid input for <code>intercept</code>.'</p>
<p>AssertionError: Invalid input for <code>t</code>.</p>
</blockquote>
<p>Any help would be appreciated.</p>
| <python><pandas><regression><quantitative-finance> | 2023-09-02 12:43:18 | 0 | 10,490 | Mostafa Bouzari |
77,028,323 | 202,385 | mypy complains about duplicate module even though its a different module with the same name but a different folder/namespace | <p>Mypy keeps complaining about duplicate module even though there is no duplicate module but modules with the same name in different folders.</p>
<p>Example tree:</p>
<pre><code>.
├── catalog
│ ├── __init__.py
│ └── k8s_pvc
│ ├── implementation.py
│ └── integration.py
├── executor
│ ├── __init__.py
│ ├── argo
│ │ ├── implementation.py
│ │ └── integration.py
│ └── k8s_job
│ ├── implementation.py
│ └── integration.py
├── experiment_tracker
│ ├── __init__.py
│ └── mlflow
│ └── implementation.py
├── run_log_store
│ ├── __init__.py
│ ├── chunked_k8s_pvc
│ │ ├── implementation.py
│ │ └── integration.py
│ └── k8s_pvc
│ ├── implementation.py
│ └── integration.py
└── secrets
</code></pre>
<p>MyPy error:</p>
<pre><code>magnus/extensions/executor/argo/implementation.py: error: Duplicate module named "implementation" (also at "magnus/extensions/catalog/k8s_pvc/implementation.py")
magnus/extensions/executor/argo/implementation.py: note: Are you missing an __init__.py? Alternatively, consider using --exclude to avoid checking one of them.
</code></pre>
<p>My mypy config:</p>
<pre><code>[mypy]
implicit_optional = True
ignore_missing_imports = True
plugins = pydantic.mypy
show_error_codes = True
follow_imports = silent
warn_redundant_casts = True
warn_unused_ignores = True
check_untyped_defs = True
implicit_reexport = True
</code></pre>
<p>Can we not use the same name in different packages and satisfy mypy?</p>
| <python><mypy> | 2023-09-02 12:40:23 | 2 | 396 | vijayvammi |
77,028,268 | 7,119,501 | How to fix UserPrincipalNotFoundException when calling an API in pyspark application? | <p>I am trying to submit API calls from a Spark application as below:</p>
<pre><code>def api_json(spark, api_param):
try:
token = generate_a_token()
token_headers = {'Authorization': f"Bearer {token}"}
response = requests.get(f'https://api_url/?api_end_point={api_param}', headers=token_headers)
json_data = spark.sparkContext.parallelize([response.text])
df = spark.read.json(json_data)
df.show()
return df
except Exception as error:
traceback.print_exc()
def generate_a_token():
token_data = {
some_key1: some_value1,
some_key2: some_value2
}
headers = {"Content-type": "application/x-www-form-urlencoded"}
data = bytes(urlencode(token_data).encode())
req = request.Request(url, data, headers)
try:
response = request.urlopen(req)
json_response = json.load(response)
token = json_response["access_token"]
print(token)
except Exception as e:
print('Some Exception')
return token
</code></pre>
<p>When I run this application, I see an exception:</p>
<blockquote>
<p>py4j.protocol.Py4JJavaError: An error occurred while calling o305.getTrustedPath.<br />
: java.nio.file.attribute.UserPrincipalNotFoundException</p>
</blockquote>
<p>I haven't faced an exception like this until and now and have no idea what it is. Full exception stack is given below.</p>
<pre><code>Traceback (most recent call last):
File "/local_disk0/tmp/spark-some-path/pyspark_template-1.0.0-py3-none-any.whl/src/tests/Api_Response.py", line 23, in api_json
json_data = spark.sparkContext.parallelize([response.text])
File "/databricks/spark/python/pyspark/context.py", line 562, in parallelize
jrdd = session._create_rdd_from_local_trusted(c, numSlices, serializer)
File "/databricks/spark/python/pyspark/sql/session.py", line 516, in _create_rdd_from_local_trusted
temp_data_path = self._write_to_trusted_path(data, serializer)
File "/databricks/spark/python/pyspark/sql/session.py", line 485, in _write_to_trusted_path
temp_dir = self._jsparkSession.getTrustedPath()
File "/databricks/spark/python/lib/py4j-0.10.9-src.zip/py4j/java_gateway.py", line 1305, in __call__
answer, self.gateway_client, self.target_id, self.name)
File "/databricks/spark/python/pyspark/sql/utils.py", line 127, in deco
return f(*a, **kw)
File "/databricks/spark/python/lib/py4j-0.10.9-src.zip/py4j/protocol.py", line 328, in get_return_value
format(target_id, ".", name), value)
py4j.protocol.Py4JJavaError: An error occurred while calling o305.getTrustedPath.
: java.nio.file.attribute.UserPrincipalNotFoundException
at sun.nio.fs.UnixUserPrincipals.lookupName(UnixUserPrincipals.java:155)
at sun.nio.fs.UnixUserPrincipals.lookupUser(UnixUserPrincipals.java:170)
at sun.nio.fs.UnixFileSystem$LookupService$1.lookupPrincipalByName(UnixFileSystem.java:330)
at org.apache.spark.sql.TrustedPathHelper.createTrustedTempDir(TrustedPathHelper.scala:86)
at org.apache.spark.sql.TrustedPathHelper.createTrustedTempDir$(TrustedPathHelper.scala:81)
at org.apache.spark.sql.SparkSession.createTrustedTempDir(SparkSession.scala:87)
at org.apache.spark.sql.TrustedPathHelper.getTrustedPath(TrustedPathHelper.scala:129)
at org.apache.spark.sql.TrustedPathHelper.getTrustedPath$(TrustedPathHelper.scala:128)
at org.apache.spark.sql.SparkSession.getTrustedPath(SparkSession.scala:87)
at py4j.commands.CallCommand.execute(CallCommand.java:79)
at py4j.GatewayConnection.run(GatewayConnection.java:251)
at java.lang.Thread.run(Thread.java:748)
</code></pre>
<p>As you can see, the exception exactly occurs at the line:</p>
<pre><code>json_data = spark.sparkContext.parallelize([response.text])
</code></pre>
<p>I printed the API call result using a print statement and was able to see the JSON(which is the payload returned from API call).
I am converting this code into a whl file, create a cluster and then submit it on databricks.
For pyspark run time libraries I am using a docker image.
Is there anything wrong in the way I configured the API calls in Spark?
Could anyone let me know what is the mistake I am doing here and how can I correct it?
Any help is really appreciated.</p>
| <python><rest><apache-spark><pyspark><apache-spark-sql> | 2023-09-02 12:25:32 | 0 | 2,153 | Metadata |
77,028,209 | 8,771,082 | How can I repeatedly list code around the current line with pdb? | <p>The <code>l</code> command for <code>pdb</code> is documented like so:</p>
<blockquote>
<p><code>l</code>: List source code for the current file. Without arguments, list 11 lines around the current line or continue the previous listing.</p>
</blockquote>
<p>I often use this command (in <code>ipdb</code> as well) to see where I am, then run a few other commands to diagnose the error which will fill my terminal with other output, then want to see the code around the error again. Since a repeated <code>l</code> continues previous listing, this doesn't help me.</p>
<p><strong>How do I opt to not continue the previous listing upon repeated call, and instead list code around the error/current line again?</strong></p>
<p>There are options to manually supply start and stop line numbers for the listing, but that is too cumbersome and messes up the flow of debugging.</p>
<p><code>ll</code> is often useful, but sometimes the current scope is too long, which means the error will be off screen anyways.</p>
<p>My current workaround is to change scope and change back using up and down commands, which is a bit clunkier than I'd want.</p>
| <python><debugging><pdb><ipdb> | 2023-09-02 12:05:32 | 0 | 449 | Anton |
77,028,034 | 6,467,567 | setup.py error when going from python=3.6 to python=3.9 | <p>I am trying to install this <a href="https://github.com/BarisYazici/deep-rl-grasping/tree/master" rel="nofollow noreferrer">https://github.com/BarisYazici/deep-rl-grasping/tree/master</a>. The instructions create a conda environment with <code>python=3.6</code> but installing the library with <code>python=3.6</code> returns an error related to opencv. I read here <a href="https://pypi.org/project/opencv-python/#supported-python-versions" rel="nofollow noreferrer">https://pypi.org/project/opencv-python/#supported-python-versions</a> that opencv does not support <code>python=3.6</code>. Here is part of the error message. The full text is too large.</p>
<pre><code>Building wheels for collected packages: opencv-python
Building wheel for opencv-python (PEP 517) ...
</code></pre>
<p>and then</p>
<pre><code> File "setup.py", line 309, in main
cmake_source_dir=cmake_source_dir,
File "/tmp/pip-build-env-o7beymxl/overlay/lib/python3.6/site-packages/skbuild/setuptools_wrap.py", line 683, in setup
cmake_install_dir,
File "setup.py", line 448, in _classify_installed_files_override
raise Exception("Not found: '%s'" % relpath_re)
Exception: Not found: 'python/cv2/py.typed'
----------------------------------------
ERROR: Failed building wheel for opencv-python
Failed to build opencv-python
ERROR: Could not build wheels for opencv-python which use PEP 517 and cannot be installed directly
</code></pre>
<p>I then tried creating a conda environment with <code>python=3.7</code> <code>python=3.8</code> <code>python=3.9</code> but the installations all fail and return me the error below. I have zero knowledge on setuptools and setup.py and was wondering if someone can assist.</p>
<pre><code>Obtaining file:///home/haziq/deep-rl-grasping
Preparing metadata (setup.py) ... error
error: subprocess-exited-with-error
× python setup.py egg_info did not run successfully.
│ exit code: 1
╰─> [14 lines of output]
error: Multiple top-level packages discovered in a flat-layout: ['config', 'models', 'tests_gripper', 'encoder_files', 'trained_models', 'manipulation_main'].
To avoid accidental inclusion of unwanted files or directories,
setuptools will not proceed with this build.
If you are trying to create a single distribution with multiple packages
on purpose, you should not rely on automatic discovery.
Instead, consider the following options:
1. set up custom discovery (`find` directive with `include` or `exclude`)
2. use a `src-layout`
3. explicitly set `py_modules` or `packages` with a list of names
To find more information, look for "package discovery" on setuptools docs.
[end of output]
note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed
× Encountered error while generating package metadata.
╰─> See above for output.
note: This is an issue with the package mentioned above, not pip.
hint: See above for details.
</code></pre>
| <python><python-3.x> | 2023-09-02 11:10:16 | 1 | 2,438 | Kong |
77,027,486 | 16,383,578 | How find logical contradictions and redundancies in a list of symbolic expressions in Python? | <p>Sometimes I have a small number of variables, and I need to compute some result according to the relationships between the variables. So I need to account for all possible relationships between the variables and calculate the result accordingly.</p>
<p>For instance, [a, b] and [c, d] are integer ranges, a <= b and c <= d, <a href="https://stackoverflow.com/revisions/76850067/4">I want to find all possible relationships of [a, b] and [c, d]</a>, or a, b, c are some numbers, and I want to find the minimum and maximum of them in one function call without using <code>min</code> and <code>max</code>.</p>
<p>For this purpose, I create all possible n choose 2 pairs, and fill the vacant comparison symbols with Cartesian products of the symbols <code>'<', '<=', '==', '>=', '>', '!='</code> of power n choose 2, to get all possible such expressions irrespective of logical consistency and redundancy, and manually process them.</p>
<p>For instance, to find all possible size relationships among a, b, c, I would do this:</p>
<pre><code>from itertools import product
relations = [', '.join(''.join(e) for e in zip('abc', triple, 'bca')) for triple in product('<=>', repeat=3)]
</code></pre>
<p><code>relations</code> is the following list containing 27 expressions:</p>
<pre><code>[
'a<b, b<c, c<a',
'a<b, b<c, c=a',
'a<b, b<c, c>a',
'a<b, b=c, c<a',
'a<b, b=c, c=a',
'a<b, b=c, c>a',
'a<b, b>c, c<a',
'a<b, b>c, c=a',
'a<b, b>c, c>a',
'a=b, b<c, c<a',
'a=b, b<c, c=a',
'a=b, b<c, c>a',
'a=b, b=c, c<a',
'a=b, b=c, c=a',
'a=b, b=c, c>a',
'a=b, b>c, c<a',
'a=b, b>c, c=a',
'a=b, b>c, c>a',
'a>b, b<c, c<a',
'a>b, b<c, c=a',
'a>b, b<c, c>a',
'a>b, b=c, c<a',
'a>b, b=c, c=a',
'a>b, b=c, c>a',
'a>b, b>c, c<a',
'a>b, b>c, c=a',
'a>b, b>c, c>a'
]
</code></pre>
<p>There are lots of logical inconsistencies and redundancies, after manually processing the expressions I get the following 13 logical consistent expressions with the least terms:</p>
<pre><code>[
'a<b, b<c',
'a<b, b=c',
'a<b, c<a',
'a<b, c=a',
'b>c, c>a',
'a=b, b<c',
'a=b, b=c',
'a=b, b>c',
'b<c, c<a',
'a>b, c=a',
'a>b, c>a',
'a>b, b=c',
'a>b, b>c'
]
</code></pre>
<p>How can I programmatically do this? In other words, given a number of undefined variables, and a list of comparisons among them, how to determine if there will always be logical contradictions between the comparisons for all possible values of the variables involved?</p>
| <python><python-3.x><symbolic-math> | 2023-09-02 08:15:15 | 0 | 3,930 | Ξένη Γήινος |
77,027,214 | 22,070,773 | How to expose an opaque pointer in nanobind? | <p>I have a function in C++ that I am trying to expose in Python:</p>
<pre><code>void f(T* t) {
...
}
</code></pre>
<p>and I am wrapping it like so:</p>
<pre><code>m.def("f", f);
</code></pre>
<p>Nanobind doesn't like the pointer and complains with:</p>
<blockquote>
<p>error: invalid use of incomplete type ‘struct T’
return nb_type_get(&typeid(Type), src.ptr(), flags, cleanup,</p>
</blockquote>
<p>It seems I am trying to expose an opaque pointer, which in Boost.Python would be done like this:</p>
<pre><code>BOOST_PYTHON_OPAQUE_SPECIALIZED_TYPE_ID(T);
</code></pre>
<p>and as far as I can see, the equivalent functionality in nanobind is:</p>
<pre><code>NB_MAKE_OPAQUE(T);
</code></pre>
<p>The discussion <a href="https://github.com/wjakob/nanobind/discussions/11" rel="nofollow noreferrer">here</a> says to create a thin wrapper for <code>T</code> and it will work, but this doesn't seem to fix the issue.</p>
<p>Any help is much appreciated.</p>
<p>Thanks</p>
| <python><c++><nanobind> | 2023-09-02 06:33:46 | 1 | 451 | got here |
77,027,198 | 1,166,391 | How to install Wagtail 5.1 or above | <p>I am using MacOS. I tried to install <strong>Wagtail 5.1</strong> in a venv and I installed <code>pip install wagtail</code>. and <code>wagtail start mysite mysite</code>. Without using cd mysite
<code>pip install -r requirements.txt</code>, I directly typed cd mysite and <code>python manage.py migrate</code>. That because I needed to install Wagtail 5.1 and not Wagtail 2.1. But when I tried to python manage.py migrate, It shows many errors including ModuleNotFoundError: No module named ‘wagtail.core’. How could I install Wagtail 5.1 or above as a fresh install?</p>
<p>This is what I got</p>
<pre class="lang-py prettyprint-override"><code>Traceback (most recent call last):
File "/Users/catman/Documents/dev/wt/mydir/catproject/manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Users/catman/Documents/dev/wt/mydir/venv/lib/python3.11/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line
utility.execute()
File "/Users/catman/Documents/dev/wt/mydir/venv/lib/python3.11/site-packages/django/core/management/__init__.py", line 416, in execute
django.setup()
File "/Users/catman/Documents/dev/wt/mydir/venv/lib/python3.11/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/catman/Documents/dev/wt/mydir/venv/lib/python3.11/site-packages/django/apps/registry.py", line 91, in populate
app_config = AppConfig.create(entry)
^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/catman/Documents/dev/wt/mydir/venv/lib/python3.11/site-packages/django/apps/config.py", line 193, in create
import_module(entry)
File "/opt/homebrew/Cellar/python@3.11/3.11.5/Frameworks/Python.framework/Versions/3.11/lib/python3.11/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<frozen importlib._bootstrap>", line 1204, in _gcd_import
File "<frozen importlib._bootstrap>", line 1176, in _find_and_load
File "<frozen importlib._bootstrap>", line 1140, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'wagtail.core'
</code></pre>
| <python><django><wagtail> | 2023-09-02 06:27:14 | 0 | 1,170 | catmantiger |
77,027,157 | 7,243,558 | Trying to use a DATE column with pyignite | <p>When I query my date column I get an error:</p>
<blockquote>
<p>Traceback (most recent call last):
File "...\Python\Python38\site-packages\pyignite\datatypes\internal.py", line 390, in __data_class_parse
return tc_map(type_code)
File "...\Python\Python38\site-packages\pyignite\datatypes\internal.py", line 117, in tc_map return _tc_map[key]
KeyError: b'\xfe'</p>
<p>During handling of the above exception, another exception occurred:</p>
<p>Traceback (most recent call last):
File "min_repo.py", line 24, in
with client.sql('SELECT * FROM DATETEST') as cursor:
File "...\Python\Python38\site-packages\pyignite\client.py", line 774, in sql
return SqlFieldsCursor(self, c_info, query_str, page_size, query_args, schema, statement_type,
File "...\Python\Python38\site-packages\pyignite\cursors.py", line 305, in <strong>init</strong>
self._finalize_init(sql_fields(self.connection, self.cache_info, *args, **kwargs))
File "...\Python\Python38\site-packages\pyignite\api\sql.py", line 309, in sql_fields<br />
return __sql_fields(conn, cache_info, query_str, page_size, query_args, schema, statement_type, distributed_joins,<br />
File "...\Python\Python38\site-packages\pyignite\api\sql.py", line 360, in __sql_fields<br />
return query_perform(
File "...\Python\Python38\site-packages\pyignite\queries\query.py", line 49, in query_perform
return _internal()
File "...\Python\Python38\site-packages\pyignite\queries\query.py", line 42, in _internal<br />
result = query_struct.perform(conn, **kwargs)
File "...\Python\Python38\site-packages\pyignite\queries\query.py", line 177, in perform<br />
raise e
File "...\Python\Python38\site-packages\pyignite\queries\query.py", line 167, in perform<br />
response_ctype = response_struct.parse(stream)
File "...\Python\Python38\site-packages\pyignite\queries\response.py", line 110, in parse<br />
self._parse_success(stream, fields)
File "...\Python\Python38\site-packages\pyignite\queries\response.py", line 178, in _parse_success
field_class = AnyDataObject.parse(stream)
File "...\Python\Python38\site-packages\pyignite\datatypes\internal.py", line 378, in parse
data_class = cls.__data_class_parse(stream)
File "...\Python\Python38\site-packages\pyignite\datatypes\internal.py", line 392, in __data_class_parse
raise ParseError('Unknown type code: <code>{}</code>'.format(type_code))
pyignite.exceptions.ParseError: Unknown type code: <code>b'\xfe'</code></p>
</blockquote>
<p>My understanding of this is that it tried to decode the type code to match it to its type. It should map to a DateObject with the type code of x\0b. My int and timestamp columns work without issue.</p>
<p>Here is my code:</p>
<pre class="lang-py prettyprint-override"><code>from pyignite import Client
import datetime
client = Client()
with client.connect("localhost", 10800):
client.sql("DROP TABLE DATETEST IF EXISTS")
client.sql('''CREATE TABLE DATETEST (
ID INT PRIMARY KEY,
Date DATE,
Timestamp TIMESTAMP
)''')
insert = '''INSERT INTO DATETEST (
ID, Date, Timestamp
) VALUES (?, ?, ?)'''
client.sql(insert, query_args=[
1,
datetime.datetime.fromisoformat("2022-01-02"),
datetime.datetime.fromisoformat("2022-01-02")
])
with client.sql('SELECT * FROM DATETEST') as cursor:
for row in cursor:
print(row)
</code></pre>
| <python><sql><ignite> | 2023-09-02 06:08:40 | 1 | 387 | James |
77,027,058 | 539,023 | Kafka error - 'Disconnected while requesting ApiVersion | <p>I have a Kafka docker set up that I was able to run properly with the following docker-compose.yml.</p>
<pre><code>> version: '2'
>
> services:
> zookeeper:
> image: bitnami/zookeeper:3.8
> ports:
> - 2181:2181
> environment:
> - ALLOW_ANONYMOUS_LOGIN=yes
> #- ZOO_ENABLE_AUTH=yes
> kafka:
> image: bitnami/kafka:2.5.0
> ports:
> - 9092:9092
> - 9091:9091
> links:
> - zookeeper
> environment:
> - ALLOW_PLAINTEXT_LISTENER=true
> - KAFKA_CFG_ZOOKEEPER_CONNECT=zookeeper:2181
> - KAFKA_LISTENERS=INTERNAL://kafka:9091,EXTERNAL://localhost:9092
> - KAFKA_ADVERTISED_LISTENERS=EXTERNAL://localhost:9092,INTERNAL://kafka:9091
> - KAFKA_INTER_BROKER_LISTENER_NAME=INTERNAL
> - KAFKA_LISTENER_SECURITY_PROTOCOL_MAP=EXTERNAL:PLAINTEXT,INTERNAL:PLAINTEXT
</code></pre>
<p>I am trying to connect using conflient-kafka and my producer code looks as below</p>
<pre><code>from confluent_kafka import Producer
import socket
conf = {'bootstrap.servers': "127.0.0.1:9092",
"enable.ssl.certificate.verification": False,
'client.id': socket.gethostname()}
producer = Producer(conf)
producer.produce('my_topic', key="key", value="value")
producer.flush()
</code></pre>
<p>I am having the following error when I run it</p>
<blockquote>
<p>Disconnected while requesting ApiVersion: might be caused by incorrect
security.protocol configuration (connecting to a SSL listener?) or
broker version is < 0.10 (see api.version.request) (after 2ms in state
APIVERSION_QUERY)</p>
</blockquote>
<p>I noticed the following</p>
<ul>
<li>Kafka broker version is 2.5.</li>
<li>docker-compose log shows
ssl.client.auth = none
ssl.enabled.protocols = [TLSv1.2]</li>
</ul>
<p>Can anyone suggest how to resolve this issue?</p>
| <python><docker><apache-kafka><confluent-kafka-python> | 2023-09-02 05:17:12 | 0 | 20,230 | kta |
77,026,971 | 22,070,773 | How to wrap a vector<T> in nanobind? | <p>In <code>boost::python</code>, to wrap a <code>vector<T></code> you would do something like this:</p>
<pre><code>boost::python::class_< std::vector < T > >("T")
.def(boost::python::vector_indexing_suite<std::vector< T > >());
</code></pre>
<p>How do I accomplish the same thing in nanobind?</p>
| <python><c++><nanobind> | 2023-09-02 04:30:36 | 1 | 451 | got here |
77,026,950 | 17,835,656 | How can i give a widget initial size in pyqt5? | <p>i want give a widget an initial size >>>>>> not fixed , not minimum , and not maximum size</p>
<p>because i want the user be able to control the size of the widget, when i am using splitter.</p>
<p>how ?</p>
<p>look at this image :</p>
<p><a href="https://i.sstatic.net/nb82U.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/nb82U.png" alt="enter image description here" /></a></p>
<p>i want the right side (the red) width to be 150 when i open the program > but when i try to change the size of it i want it to respond and to be changeable even if i want it to be bigger or smaller.</p>
<p>when i set a fixed size i will not be able to change its size.</p>
<p>when i set a minimum size it will expand and make the left side (the green) small.</p>
<p>when i set a maximam size i will be able to make it smaller but not bigger.</p>
<p>this is my code:</p>
<pre class="lang-py prettyprint-override"><code>from PyQt5 import QtWidgets
import sys
app = QtWidgets.QApplication(sys.argv)
window = QtWidgets.QWidget()
window.resize(800,500)
window_layout = QtWidgets.QGridLayout()
first_widget = QtWidgets.QScrollArea()
first_widget.setStyleSheet("background-color:rgb(0,150,0)")
second_widget = QtWidgets.QGroupBox()
second_widget.setStyleSheet("background-color:rgb(150,0,0)")
splitter = QtWidgets.QSplitter()
splitter.addWidget(first_widget)
splitter.addWidget(second_widget)
window_layout.addWidget(splitter)
window.setLayout(window_layout)
window.show()
app.exec()
</code></pre>
<p>when i tried the solution below i got a new error that the spacers are disabled are not working.</p>
<p>this is a code to explain the new problem</p>
<pre class="lang-py prettyprint-override"><code>from PyQt5 import QtWidgets
import sys
app = QtWidgets.QApplication(sys.argv)
window = QtWidgets.QWidget()
window.resize(800,500)
window_layout = QtWidgets.QGridLayout()
first_widget = QtWidgets.QGroupBox()
first_widget.setStyleSheet("background-color:rgb(0,150,0)")
first_widget_layout = QtWidgets.QGridLayout()
first_widget_spacer_0 = QtWidgets.QSpacerItem(100000,0,QtWidgets.QSizePolicy.Expanding,QtWidgets.QSizePolicy.Maximum)
first_widget_layout.addItem(first_widget_spacer_0)
first_widget.setLayout(first_widget_layout)
second_widget = QtWidgets.QGroupBox()
second_widget.setStyleSheet("background-color:rgb(150,0,0)")
splitter = QtWidgets.QSplitter()
splitter.addWidget(first_widget)
splitter.addWidget(second_widget)
splitter.setSizes([window.width() - 150, 150])
window_layout.addWidget(splitter)
window.setLayout(window_layout)
window.show()
app.exec()
</code></pre>
| <python><python-3.x><pyqt><pyqt5> | 2023-09-02 04:19:57 | 1 | 721 | Mohammed almalki |
77,026,844 | 21,575,627 | How can I find the time complexity of this algorithm (backtracking)? | <p>This is a function I wrote in Python for Leetcode 216. The problem statement is:</p>
<blockquote>
<p>Find all combinations of k distinct digits from [1-9] s.t they sum to n. Return a list of all valid combinations, knowing that 2 <= k <= 9, 1 <= n <= 60</p>
</blockquote>
<p>This is my algorithm:</p>
<pre><code>def combinationSum(k: int, n: int) -> list[list[int]]:
def backtrack(res, start, cur, curSum):
print(res, start, cur, curSum)
if len(cur) == k:
if curSum == n:
res.append(cur[:])
return
for i in range(start, 10):
cur.append(i)
backtrack(res, i + 1, cur, curSum + i)
cur.pop()
c = []
backtrack(c, 1, [], 0)
return c
</code></pre>
<p>and it is correct. I am having trouble with the time complexity though. I understand it is exponential, but how can I go about deducing it?</p>
| <python><algorithm><time-complexity><big-o> | 2023-09-02 03:23:08 | 1 | 1,279 | user129393192 |
77,026,714 | 3,158,876 | How to iterate through dictionary and set values from a class | <p>I have an empty dictionary (tried both completely empty and with keys from list - same results).</p>
<p>I am then trying to iterate through that same list (in this case rooms in a building), pull some data from another source into a class instance, and then set the value in the dictionary designated for that room to the class instance. However, each one overwrites the last, so at the end every value (class) in the dictionary is identical and comes from the last room.</p>
<p>I'm sure this comes from my lack of understanding of references, however I've tried copying and deep copying but not luck. Any suggestions? Here's a summary of my code. I can provide more details if they are relevant, such as the class definition, but was trying to keep it succinct:</p>
<pre><code># Initialize dict with keys but no values
results = dict.fromkeys(rooms)
for room_id in rooms: # rooms is a list of strings
# Instantiate class for results data
results_data = LoadResultsData
# Pull data for each variable and assign and divide to change units
results_data.sens_total = np.array([1, 2, 3, 4, 5])
results_data.sens_lighting = np.array([2, 2, 3, 4, 5])
results_data.sens_equipment = np.array([3, 2, 3, 4, 5])
results_data.sens_people = np.array([4, 2, 3, 4, 5])
# Assign class to overall dictionary with ID as key
results[room_id] = results_data
</code></pre>
<p>Thank you.</p>
| <python><dictionary><class><reference> | 2023-09-02 02:05:13 | 1 | 315 | Benjamin Brannon |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.