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
74,936,981
6,702,598
Python venv: automatically install requirements.txt when entering venv
<p>How do I setup my virtual environment (<code>venv</code>) to automatically install all <code>requirement</code>s (<code>.txt</code>) upon activation?</p> <h5>Unsatisfying workaround:</h5> <p>I created a file <code>activate_venv.sh</code></p> <pre><code>source venv/bin/activate pip install -r requirements.txt </code></pre> <p><em>Problem</em>: <br> If the IDE automatically enters the venv, it does not use that file and will therefore not the installation.</p> <h4>Current solution</h4> <p><a href="https://stackoverflow.com/a/74937147/6702598">Msvstl's solution</a>: (props!)</p> <blockquote> <p>Add <code>pip install -r requirements.txt</code> to <code>venv/bin/activate</code></p> </blockquote> <p><em>Drawbacks</em><br> This solution is not system agnosic. You need to edit various files depending on the system you're on (activate, activate.bat, activate.ps1, activate.csh, activate.fish).</p>
<python><python-venv><requirements.txt>
2022-12-28 06:34:39
1
3,673
DarkTrick
74,936,903
1,927,609
Why do some os functions ignore trailing spaces on Windows?
<p>I've tried the example program below on both Windows and Linux with Python 3.11.0.</p> <pre class="lang-py prettyprint-override"><code>import os if __name__ == &quot;__main__&quot;: directory_name = &quot;foo &quot; file_name = &quot;bar.txt&quot; os.mkdir(directory_name) print(os.path.exists(directory_name)) out_path = os.path.join(directory_name, file_name) try: with open(out_path, &quot;w&quot;) as bar_file: pass print(f&quot;Successfully opened {repr(out_path)}.&quot;) except FileNotFoundError: print(f&quot;Could not open {repr(out_path)}.&quot;) print(os.listdir()) </code></pre> <p>The output on Linux is what I expected:</p> <pre class="lang-plaintext prettyprint-override"><code>True Successfully opened 'foo /bar.txt'. ['foo '] </code></pre> <p>However, on Windows, I get the output below.</p> <pre class="lang-plaintext prettyprint-override"><code>True Could not open 'foo \\bar.txt'. ['foo'] </code></pre> <p>It seems like <code>os.mkdir</code> and <code>os.path.exists</code> are ignoring the trailing space in the directory name, but <code>os.path.join</code> is not.</p> <p>Why do these methods behave this way on Windows? Is the behavior intentional? Moreover, what is the best way to overcome this discrepancy and get the same behavior on both systems?</p>
<python><windows><directory><whitespace>
2022-12-28 06:22:06
1
1,483
Andrew Tapia
74,936,843
19,458,490
How can I select the entire import statements using regular expressions?
<p>I'm writing a static code analysis tool in Python.</p> <p>Here's a sample of a code that needs to be analyzed:</p> <pre><code>import { component$, useClientEffect$, } from '@builder.io/qwik' import Swiper from 'swiper' import { Navigation, Pagination } from 'swiper' import { Image } from 'Base' import Button from '../Shared/Button' import Heading from '../Shared/Heading' const Portfolio = component$( ( { items, title, linkText, link } ) =&gt; { </code></pre> <p>One item that I have to check is to ensure that there is an empty line after the last import. As you can see in the example above, the <code>const Portfolio</code> which is the component declaration is attached to the previous import. I need to make sure it has an empty line before it.</p> <p>I tried <code>(?&lt;=import).*(?=from)</code>, but it does not work. Please note that a developer might place an empty line before two imports. Or he might place empty space before an import. In other words, a developer might write the most unformatted code.</p> <p>What regular expression can I use to ensure this requirement?</p>
<python><regex><code-analysis><static-code-analysis>
2022-12-28 06:12:51
1
624
Mohammad Miras
74,936,697
10,934,636
How to open multiple persistent chrome profiles using playwright
<p>I have some Chrome profiles in which I have my different accounts logged in. I'm writing a multi-threaded script that will run each profile using <code>launch_persistent_context</code> so that I'm already logged in and script starts working from thereon.</p> <p>I'm using Playwright, on Windows 10.</p> <p>Here's my code snippet which works for only one profile (I'm not sure why, because the profile it opens is Profile 1 in my file-path, however the script works only for the parent directory, and that too for only a single profile)</p> <pre><code>def run(playwright: Playwright) -&gt; None: browser = playwright.chromium.launch_persistent_context( channel=&quot;chrome&quot;, user_data_dir=r&quot;C:\\Users\\Home\\AppData\\Local\\Google\\Chrome\\User Data&quot;, headless=False) page = browser.new_page() </code></pre> <p>I'm facing difficulties in running all the Chrome profiles simultaneously or even sequentially.</p> <p>I looked at the <a href="https://playwright.dev/python/docs/api/class-browsertype#browser-type-launch-persistent-context" rel="nofollow noreferrer">docs</a> and GitHub issues but I'm not sure what to do.</p>
<python><playwright-python>
2022-12-28 05:50:56
1
712
stuckoverflow
74,936,605
14,627,505
Merge 2 dfs, with the row if it is the only row that contains the word
<p>I have 2 pandas data frames:</p> <pre class="lang-py prettyprint-override"><code>df1 = pd.DataFrame({'keyword': ['Sox','Sox','Jays','D', 'Jays'], 'val':[1,2,3,4,5]}) df2 = pd.DataFrame({'name': ['a b c', 'Sox Red', 'Blue Jays White Sox'], 'city':[f'city-{i}' for i in [1,2,3]], 'info': [5, 6, 7]}) </code></pre> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; df1 keyword val 0 Sox 1 1 Sox 2 2 Jays 3 3 D 4 4 Jays 5 &gt;&gt;&gt; df2 name city info 0 a b c city-1 5 1 Sox Red city-2 6 2 Blue Jays White Sox city-3 7 </code></pre> <p>For each row of <code>df1</code> the merge should be taking the exact element of <code>df1['keyword']</code> and see if it is present in each of the <code>df2['name']</code> elements (e.g. using <code>.str.contains</code>). Now there can be the following options:</p> <ul> <li>if it is present in exactly 1 row of <code>df2['name']</code>: match the current row of <code>df1</code> with this 1 row of <code>df2</code>.</li> <li>otherwise (if it is present in more than 1 or in 0 rows of <code>df2['name']</code>): don't match the current row of <code>df1</code> with anything - the values will be <code>NaN</code>.</li> </ul> <p>The result should look like this:</p> <pre class="lang-py prettyprint-override"><code> keyword val name city info 0 Sox 1 NaN NaN NaN 1 Sox 2 NaN NaN NaN 2 Jays 3 Blue Jays White Sox city-3 7.0 3 D 4 NaN NaN NaN 4 Jays 5 Blue Jays White Sox city-3 7.0 </code></pre> <p>Here in the column <code>&quot;keyword&quot;</code>:</p> <ul> <li><code>&quot;Sox&quot;</code> matches multiples lines of <code>df2</code> (lines 1 and 2), so its merged with <code>NaN</code>s,</li> <li><code>&quot;D&quot;</code> matches 0 lines of <code>df2</code>, so it's also merged with <code>NaN</code>s,</li> <li><code>&quot;Jays&quot;</code> matches exactly 1 line in <code>df2</code> (line 2), so it's merged with this line.</li> </ul> <p>How to do this using pandas?</p>
<python><pandas><regex><dataframe><merge>
2022-12-28 05:37:47
2
3,903
Vladimir Fokow
74,936,282
10,305,444
tf.strings.operations raises TypeError: Value passed to parameter 'input' has DataType string not in list of allowed
<p>I'm trying to create a superficial layer to pre-process data inside models. Here is an my Layer:</p> <pre><code>class StringLayer(tf.keras.layers.Layer): def __init__(self): super(StringLayer, self).__init__() def call(self, inputs): return tf.strings.join([some_python_function(word) for word in tf.strings.split(tf.strings.as_string(inputs), sep=&quot; &quot; )], separator=&quot; &quot;) #model = tf.keras.models.Sequential() #model.add(tf.keras.Input(shape=(1,), dtype=tf.string)) #model.add(StringLayer()) </code></pre> <p>But it keeps giving me: <strong><code>TypeError: Value passed to parameter 'input' has DataType string not in list of allowed values: float32, float64, int32, uint8, int16, int8, int64, bfloat16, uint16, float16, uint32, uint64, complex64, complex128, bool, variant</code></strong></p> <p><em>I know I can do this thing out of the model, but my main goal is to somehow do this inside the model; this way, I'll be able to maximize the GPU utilization.</em></p>
<python><tensorflow><keras>
2022-12-28 04:34:48
0
4,689
Maifee Ul Asad
74,936,103
3,277,133
How to pivot and stack dataframe in pandas without group by while having duplicate values in the pivot?
<p>I have df that looks like this:</p> <pre><code>ref text id a zz 12eia a yy radf02 b aa a8adf b bb 2022a </code></pre> <p>I am trying to rotate this dataframe to look like below with values in column <code>ref</code> becoming column names and values in <code>text</code> becoming values under those columns and I dont need the 'id' column :</p> <pre><code>a b zz aa yy bb </code></pre> <p>I tried using this line, but I am not getting the result, without adding the <code>id</code> column:</p> <pre><code>df_rotated = df.pivot_table(index='ref', values='text', columns='id', aggfunc='first') </code></pre> <p>The data collapses and is not the result I want, what am I doing wrong?</p>
<python><pandas>
2022-12-28 03:56:24
1
3,707
RustyShackleford
74,936,051
8,901,144
PySpark drop Duplicates and Keep Rows with highest value in a column
<p>I have the following Spark dataset:</p> <pre><code>id col1 col2 col3 col4 1 1 5 2 3 1 1 0 2 3 2 3 1 7 7 3 6 1 3 3 3 6 5 3 3 </code></pre> <p>I would like to drop the duplicates in the columns subset ['id,'col1','col3','col4'] and keep the duplicate rows with the highest value in col2. This is what the result should look like:</p> <pre><code>id col1 col2 col3 col4 1 1 5 2 3 2 3 1 7 7 3 6 5 3 3 </code></pre> <p>How can I do that in PySpark?</p>
<python><pyspark><duplicates>
2022-12-28 03:44:05
2
1,255
Marco
74,935,787
4,503,546
How do I convert rows into a calendar performance table using Python/Pandas or Excel?
<p>I have 2 columns which hold dates and performance returns by month back several years. The data is in a csv and looks like this:</p> <pre><code>Date: Return 12/2022: -1% 11/2022: +2% 10/2022: +1% ... 1/2002: -1% </code></pre> <p>I want to convert this into a more traditional performance table/matrix which has a row for each year and a column for each month. So, the end result would look something like this:</p> <pre><code>Year Jan, Feb, Mar, ..., Dec 2022 -1%, +1%, +2%, ..., -1% 2021 -1%, +1%, +2%, ..., -1% ... 2002 -1%, +1%, +2%, ..., -1% </code></pre> <p>Please advise.</p> <p>Thx</p>
<python><excel><pandas><dataframe>
2022-12-28 02:41:32
2
407
GC123
74,935,545
15,542,245
Order of dictionary key/values changes output of script
<p>The problem occurs in a script processing lines of text like the following:</p> <pre><code>import re combo_dict = { 'Mngr': 'Manager', 'Shp': 'Shop' } rexCapDoubleWord = '(?s)\s([A-z]+\s[A-z]+)$' fileLines = ['001 AALTONEN Alan Roy 2 Berkeley_Road,_Welltown Shp Mngr'] for fileLine in fileLines: words = [] try: regexCapDouble = re.search(rexCapDoubleWord, fileLine).group(1) if(regexCapDouble): words = regexCapDouble.split(&quot; &quot;) for key, value in combo_dict.items(): if(key == words[0]): # replace the capture group with the dictionary key value found SubWordOne = re.sub(words[0], value, fileLine) else: SubWordOne = fileLine for key, value in combo_dict.items(): if(key == words[1]): # replace the capture group with the dictionary key value found SubWordTwo = re.sub(words[1], value, SubWordOne) fileLines = list(map(lambda x: x.replace(fileLine, SubWordTwo), fileLines)) else: fileLines = list(map(lambda x: x.replace(fileLine, SubWordOne), fileLines)) except AttributeError: regexCapDouble = None for fileLine in fileLines: print(fileLine) </code></pre> <p>This simple example outputs:</p> <pre><code>001 AALTONEN Alan Roy 2 Berkeley_Road,_Welltown Shop Manager </code></pre> <p>But if the dictionary contents are reversed:</p> <pre><code>combo_dict = { 'Shp': 'Shop', 'Mngr': 'Manager' } </code></pre> <p>Output:</p> <pre><code>001 AALTONEN Alan Roy 2 Berkeley_Road,_Welltown Shp Manager </code></pre> <p>I can't see I'm doing anything wrong. Is it the way I'm trying to access the dictionary keys? I want to clear this up because my 'use case' gets more complicated from here. Would appreciate any suggestions.</p>
<python><dictionary>
2022-12-28 01:49:33
2
903
Dave
74,935,303
6,346,514
Python, Looping through subdirectories for zip files, OS Error Invalid Argument \\
<p>I am trying to look into my directory for zip files and perform a function on them. It does seem to loop through some of the files correctly but gets stuck with <code>OS Error \\</code></p> <p>Directory structure is like:</p> <pre><code> //Stack/Over/Flow/2022 - 10/Original.zip //Stack/Over/Flow/2022 - 09/Next file.zip </code></pre> <p>function i call:</p> <pre><code>from io import BytesIO from pathlib import Path from zipfile import ZipFile import os import pandas as pd def process_files(files: list) -&gt; pd.DataFrame: file_mapping = {} for file in files: #data_mapping = pd.read_excel(BytesIO(ZipFile(file).read(Path(file).stem)), sheet_name=None) archive = ZipFile(file) # find file names in the archive which end in `.xls`, `.xlsx`, `.xlsb`, ... files_in_archive = archive.namelist() excel_files_in_archive = [ f for f in files_in_archive if Path(f).suffix[:4] == &quot;.xls&quot; ] # ensure we only have one file (otherwise, loop or choose one somehow) assert len(excel_files_in_archive) == 1 # read in data data_mapping = pd.read_excel( BytesIO(archive.read(excel_files_in_archive[0])), sheet_name=None, ) row_counts = [] for sheet in list(data_mapping.keys()): row_counts.append(len(data_mapping.get(sheet))) file_mapping.update({file: sum(row_counts)}) frame = pd.DataFrame([file_mapping]).transpose().reset_index() frame.columns = [&quot;file_name&quot;, &quot;row_counts&quot;] return frame </code></pre> <p>code:</p> <pre><code>dir_path = r'\\stack\over\flow' for root, dirs, files in os.walk(dir_path): for file in files: print(files) if file.endswith('.zip'): df = process_files(os.path.join(root, file)) print(df) #function else: print(&quot;nyeh&quot;) </code></pre> <p>Error:</p> <pre><code>runfile('/test.py', wdir='test python location') ['History Detail view (page 5) - Nov 2021.zip', 'Original - All fields - 11012021 - 11302021.zip', 'Other fields - 11012021 - 11302021.zip', 'Qualified - All fields - 11012021 - 11302021.zip', 'WPS Report (page 3) 11012021 - 11302021.zip'] Traceback (most recent call last): File &quot;test.py&quot;, line 75, in &lt;module&gt; df = process_files(os.path.join(root, file)) File &quot;test.py&quot;, line 21, in process_files archive = ZipFile(file) File &quot;C:\Users\user\.conda\envs\diamond\lib\zipfile.py&quot;, line 1251, in __init__ self.fp = io.open(file, filemode) OSError: [Errno 22] Invalid argument: '\\' </code></pre> <p>Why am I getting this error? How can I bypass this?</p>
<python><pandas>
2022-12-28 00:45:42
0
577
Jonnyboi
74,935,217
3,696,490
QTableWidget truncate beginning of long cell instead of end
<p>I am creating a GUI in pyqt and I use QTableWidget to show some list of files.</p> <p>When the string in a cell is too long, the end is truncated and replaced by &quot;...&quot;. Like in this photo <a href="https://i.sstatic.net/eyYE9.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/eyYE9.png" alt="enter image description here" /></a></p> <p>Is it possible to hide the beginning instead? something like .../pana/someverylongblablabla.ext</p> <p>Thanks</p>
<python><qt><pyqt><pyqt5>
2022-12-28 00:25:33
0
550
user206904
74,935,202
8,439,343
InvalidArgumentError: Graph execution error:
<p>when running this script, I get an error when calling the model.fit(dataset, epochs=5) method when I want to train the model and I get the error InvalidArgumentError: Graph executes error:</p> <p>`</p> <pre><code>import nltk nltk.download('punkt') nltk.download('wordnet') nltk.download('stopwords') nltk.download('omw-1.4') def preprocess_data(data): # Tokenize as sentences data = [nltk.word_tokenize(sent) for sent in data] # Remove stopwords stopwords = nltk.corpus.stopwords.words('portuguese') data = [[word for word in sent if word not in stopwords] for sent in data] # Perform lemmatization lemmatizer = nltk.stem.WordNetLemmatizer() data = [[lemmatizer.lemmatize(word) for word in sent] for sent in data] return data # Example usage data = [ &quot;oi tudo bem?&quot;, &quot;sim, eu estou com fome e voce?&quot;, &quot;eu estou, quero uma pizza&quot;, &quot;vou pedir duas pizzas&quot;, &quot;Gosto de livros&quot;, &quot;quais livros voce gosta de ler?&quot;, &quot;oi tudo bem?&quot;, &quot;sim, eu estou com fome e voce?&quot;, &quot;eu estou, quero uma pizza&quot;, &quot;vou pedir duas pizzas&quot;, &quot;Gosto de livros&quot;, &quot;quais livros voce gosta de ler?&quot;, &quot;eu gosto de ler thrillers e ficção científica&quot;, &quot;e você, o que mais gosta de ler?&quot;, &quot;eu também gosto de ler romances e livros de autoajuda&quot;, &quot;qual é o seu livro favorito?&quot;, &quot;um dos meus livros favoritos é o 'O Alquimista' de Paulo Coelho&quot;, &quot;eu também gosto muito desse livro! Qual é o seu gênero literário favorito?&quot;, &quot;eu gosto de todos os gêneros, mas talvez meu favorito seja a ficção científica&quot;, &quot;eu também adoro ficção científica. Qual é o seu livro de ficção científica favorito?&quot;, &quot;meu livro de ficção científica favorito é 'Dune' de Frank Herbert&quot;, &quot;que legal, eu também gosto muito de 'Dune'! Já leu algum outro livro do Frank Herbert?&quot;, &quot;sim, eu também gostei muito de 'O Imperador-Deus de Dune' e 'Herejia de Dune'&quot;] processed_data = preprocess_data(data) print(processed_data) import tensorflow as tf # Define the input and output sequences input_sequences = processed_data[:-1] output_sequences = processed_data[1:] def flatten(l): return [item for sublist in l for item in sublist] # Create a vocabulary of unique words vocab = sorted(set(flatten(input_sequences + output_sequences))) # Create word-to-index and index-to-word mappings word_to_index = {word: i for i, word in enumerate(vocab)} index_to_word = {i: word for i, word in enumerate(vocab)} # Convert the input and output sequences to integers input_sequences = [[word_to_index[word] for word in seq] for seq in input_sequences] output_sequences = [[word_to_index[word] for word in seq] for seq in output_sequences] # Find the maximum sequence length max_seq_len = max(len(seq) for seq in input_sequences + output_sequences) # Pad the sequences with zeros to the maximum sequence length input_sequences = tf.keras.preprocessing.sequence.pad_sequences( input_sequences, maxlen=max_seq_len, padding='post') output_sequences = tf.keras.preprocessing.sequence.pad_sequences( output_sequences, maxlen=max_seq_len, padding='post') # Create a dataset from the padded sequences batch_size = 32 # Replace 32 with the desired batch size dataset = tf.data.Dataset.from_tensor_slices( (input_sequences, output_sequences)).batch(batch_size) # Define the RNN model model = tf.keras.Sequential([ tf.keras.layers.Embedding(len(vocab), 64, input_length=max_seq_len), tf.keras.layers.LSTM(64), tf.keras.layers.Dense(len(vocab), activation='softmax') ]) # Compile the model # Compile the model model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) # Treinar o modelo model.fit(dataset, epochs=5) </code></pre> <p>`</p> <p>I hope to be able to train the network, but the error returned is InvalidArgumentError: Graph execution error:</p>
<python><tensorflow><machine-learning><chatbot>
2022-12-28 00:23:08
1
311
Lucas Torres
74,934,919
2,359,865
construct a python rich tree from list of descendants
<p>I am trying to construct a python <code>rich.Tree</code> from a list of descendants, <code>d</code>.</p> <pre><code>d = {0: [1, 2], 2: [3, 4, 5], 4: [6, 7]} </code></pre> <p>I expect to get something like this:</p> <pre><code># manually constructed string expected = \ &quot;&quot;&quot; 0 ├── 1 └── 2 └── 3 └── 4 └── 6 └── 7 └── 5 &quot;&quot;&quot; </code></pre> <p>But I am getting confused as to how to proceed with the construction: the following code is not correct.</p> <pre><code>from rich.tree import Tree from rich import print as rprint tree = Tree(&quot;0&quot;) tree.add(&quot;1&quot;) tree.add(&quot;2&quot;).add(&quot;3&quot;) tree.add(&quot;4&quot;).add(&quot;6&quot;).add(&quot;7&quot;) tree.add(&quot;5&quot;) rprint(tree) 0 ├── 1 ├── 2 │ └── 3 ├── 4 │ └── 6 │ └── 7 └── 5 </code></pre> <p>Any suggestions will be appreciated, thanks!</p>
<python><tree><descendant><rich>
2022-12-27 23:21:45
2
462
acortis
74,934,918
2,265,682
Run an async function from a sync function... without knowing whether there is already a running event loop?
<p>So it is a common question for someone first coming to python's async to ask, &quot;how do I run an async function from a sync function?&quot; Hopefully if you're here you already know that the answer to that question is <code>asyncio.run()</code>.</p> <p>But this is <em>not</em> really the answer. Because suppose I want to write an ad hoc set of scripts in which, in a few places within it, I want to call a few coroutines. <code>asyncio.run</code> &quot;should ideally only be called once&quot; and &quot;cannot be called when another asyncio event loop is running in the same thread.&quot; In general you cannot have two event loops running in the same thread.</p> <p>In the ad hoc scenario I imagine I would like an idiom which is &quot;block execution of this non-async function, and its event loop if there is one, until this coroutine finishes&quot;. It must tolerate being run whether an event loop exists or not and whether it is running or not. If there is no running event loop this easy. If there is, it should have the same effect as creating another event loop, calling <code>run_until_complete</code> on that, then resuming execution of the calling function (which, eventually, will pass control back to the original loop, though since it's not async, that might not be for a while.)</p> <p>For example:</p> <pre class="lang-py prettyprint-override"><code> async def coro1(): pass def function1(): better_asyncio_run(coro1()) def function2(): function1() better_asyncio_run(coro1()) async def coro2(): function2() if __name__ == '__main__': better_asyncio_run(coro2()) </code></pre> <p>One might be tempted to answer, &quot;rewrite your code to all be async&quot; which is I guess giving in to the nightmare. It surely shouldn't be necessary for the rapid prototyping we love python for. If there is some fundamental reason why it can't work, I haven't spotted it and would love to know what it is.</p>
<python><python-asyncio>
2022-12-27 23:21:44
0
421
FishFace
74,934,917
4,164,680
Neural Network on the Iris dataset convergaes very quickly
<p>I'm tasked with writing a ANN using only NumPy (no TensorFlow, PyTorch , etc.) on the iris dataset. I'm running 2000 epochs and it seems by the time of epoch 40 the accuracy of the network stays at 0.66. Also the parameters while debugging are either extremely high or extremely low (for example, for <code>self.layers[0]</code>, the <code>self.output</code> parameter is <code>[-59.2447737,-79.13719157,-57.27055739,117.26796309,127.71775426]</code> on epoch 400.</p> <p>My network has 4 input nodes, a single hidden layer with 5 nodes and an output layer with 3 nodes corresponding to the 3 types of irises.</p> <p>I'm confused as to why that's the case. The learning rate is low (0.01), the <code>weights</code> and <code>biases</code> vectors are initialized with low values, and I normalized the input data.</p> <p>Any help with this would be highly appreciated. My code:</p> <p>main.py:</p> <pre><code>import numpy as np from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from network import NeuralNetwork from layer import Layer if __name__ == &quot;__main__&quot;: iris = load_iris() data, target, target_names = iris.data, iris.target, iris.target_names scaler = StandardScaler() # One hot encoding to ap the target array to match the 3 neurons output structure one_hot_targets = [] for i in range(len(target)): vec = np.zeros(len(target_names)) vec[target[i]] = 1 one_hot_targets.append(vec) one_hot_targets = np.array(one_hot_targets) X_train, X_test, Y_train, Y_test = train_test_split(data, one_hot_targets, test_size=0.33, shuffle=True) scaler.fit(X_train) X_train_scaled = scaler.transform(X_train) X_test_scaled = scaler.transform(X_test) learning_rate = 0.01 # Init a network and add it's layers. Input layer is represented by the input, and not by an actual layer network = NeuralNetwork(learning_rate) network.add_layer(Layer(4, 5)) # hidden layer 1 network.add_layer(Layer(5, 3)) # output layer # Train the network for a number of epochs network.train(X_train_scaled, Y_train, epochs=2000) # Test for the test data seperated earlier output, accuracy = network.test(X_test_scaled, Y_test) # Print testing output for i in range(len(output)): prediction = target_names[np.argmax(output[i])] answer = target_names[np.argmax(Y_test[i])] print(f&quot;For testing row: {X_test[i]}, the prediction was {prediction} and the answer was {answer}&quot;) print(f&quot;Network test accuracy: {accuracy:.4f}&quot;) </code></pre> <p>network.py:</p> <pre><code>import numpy as np from utils import calc_error np.random.seed(10) class NeuralNetwork: def __init__(self, learning_rate=0.1): self.layers = [] self.learning_rate = learning_rate def add_layer(self, layer): # Layers must be added in order self.layers.append(layer) def forward_propagate(self, input): output = input for layer in self.layers: output = layer.forward_propagate(output) return output def back_propagate(self, error): for layer in reversed(self.layers): error = layer.back_propagate(error) def train_iteration(self, input, target): output = self.forward_propagate(input) # Calculate the error between the output and the target value error = output - target # Backpropagate the error through the network self.back_propagate(error) # Update the weights and biases of the layers for layer in self.layers: layer.weights -= self.learning_rate * layer.d_weights layer.biases -= self.learning_rate * layer.d_biases def train_epoch(self, inputs, targets): for i in range(len(inputs)): x = inputs[i] y = targets[i] self.train_iteration(x, y) def train(self, inputs, targets, epochs=4000): for epoch in range(epochs): self.train_epoch(inputs, targets) if epoch % (epochs / 100) == 0: _, accuracy = self.test(inputs, targets) print(f&quot;Epoch {epoch} --&gt; Training Accuracy:{accuracy}&quot;) def predict(self, input): output = self.forward_propagate(input) return output def test(self, inputs, targets): output, correct = [], 0 for i in range(len(inputs)): x, y = inputs[i], targets[i] guess = self.predict(x) is_correct = y[guess.argmax()] == 1 correct += is_correct output.append(guess) return output, (correct / len(inputs)) </code></pre> <p>layer.py:</p> <pre><code>import numpy as np from utils import sigmoid, deriv_sigmoid np.random.seed(10) class Layer: def __init__(self, num_inputs, num_neurons, activation_function=sigmoid, derivative_activation_function=deriv_sigmoid): self.weights = np.random.randn(num_inputs, num_neurons) * 0.01 self.biases = np.zeros((1, num_neurons)) self.activation_function = activation_function self.derivative_activation_function = derivative_activation_function def forward_propagate(self, input): self.input = input self.output = np.dot(input, self.weights) + self.biases self.activated_output = self.activation_function(self.output) return self.activated_output def back_propagate(self, error): error = self.derivative_activation_function(error) reshaped_input = self.input.T.reshape((np.max(self.input.shape), 1)) # ensures dot product always works self.d_weights = np.dot(reshaped_input, error) self.d_biases = np.sum(error, axis=0, keepdims=True) self.d_input = np.dot(error, self.weights.T) return self.d_input </code></pre> <p>utils.py:</p> <pre><code>import numpy as np def sigmoid(x): return (1 / (1 + np.exp(-x))) def deriv_sigmoid(x): return np.multiply(x, 1-x) </code></pre>
<python><numpy><neural-network><iris-dataset>
2022-12-27 23:21:24
1
351
Amit Toren
74,934,901
17,553,278
How can I print a day and a time using Python strftime?
<p><strong>Context:</strong> I'm trying to format a day and time using Python's strftime function, but I'm encountering a &quot;ValueError.&quot; I want the output to be in the format &quot;1 day, 2:45:00&quot; to represent a valid datetime object. However, my current code is throwing the following error: &quot;ValueError: time data '1 day, 2:45:00' does not match format '%H:%M:%S'.&quot; .</p> <pre><code>from datetime import datetime actualTime = '1 day, 2:45:00' strpTime = datetime.strptime(f&quot;{actualTime}&quot;, &quot;%H:%M:%S&quot;) fomtTime = strpTime.strftime(&quot;%I:%M %p&quot;) print(fomtTime) </code></pre> <p><strong>Issue:</strong> I would like to know how to format a day and time in the desired format (&quot;1 day, 2:45:00&quot;) using Python's strftime function without encountering a ValueError. I appreciate any insights or corrections to my code.</p> <p>Thank you.</p>
<python><python-datetime><valueerror><strptime><strftime>
2022-12-27 23:18:43
1
325
Baboucarr Badjie
74,934,871
11,633,074
python class function append on all instance of an object
<p>I wanted to make a script in order to manage my friends and I, walkie talkies. so I created 4 classes: a Range is a modification that can upgrade the walkie talkie a Walkie Talkie describe the radio and its possible mods(Range) a Person describe me or my friends and their radios a TalkieRangeData is a class to handle all of this</p> <p>Here is my code:</p> <pre class="lang-py prettyprint-override"><code>import json import base64 import os def is_base64(s): &quot;&quot;&quot;Check if a parameter is encoded in base64.&quot;&quot;&quot; try: base64.b64decode(s) return True and s[-1] == &quot;=&quot; except: return False def to_base64(s): &quot;&quot;&quot;Encode a parameter in base64 if it is not already encoded.&quot;&quot;&quot; if not is_base64(s): s = base64.b64encode(s.encode()).decode() return s def from_base64(s): &quot;&quot;&quot;Decode a parameter from base64 if it is encoded.&quot;&quot;&quot; if is_base64(s): s = base64.b64decode(s).decode() return s class Range: def __init__(self, mod, minrange, maxrange, commentary): self.mod = mod self.minrange = minrange self.maxrange = maxrange self.commentary = to_base64(commentary) def update_range( self, new_mod=None, new_min=None, new_max=None, new_commentary=None ): if new_mod: self.mod = new_mod if new_min: self.minrange = new_min if new_max: self.maxrange = new_max if new_commentary: self.commentary = to_base64(new_commentary) def __repr__(self): return f&quot;Mod: {self.mod}\n\tMin: {self.minrange}\n\tMax: {self.maxrange}\n\tCommentary: {from_base64(self.commentary)} &quot; def toJSON(self): return { &quot;mod&quot;: self.mod, &quot;minrange&quot;: self.minrange, &quot;maxrange&quot;: self.maxrange, &quot;commentary&quot;: self.commentary, } class WalkieTalkie: def __init__(self, model, general_commentary, ranges=list()): self.model = model self.generalCommentary = to_base64(general_commentary) self.ranges = list() for r in ranges: if isinstance(r, Range): self.ranges.append(r) else: self.ranges.append(Range(*r)) def add_range(self, mod, minrange, maxrange, commentary): self.ranges.append(Range(mod, minrange, maxrange, to_base64(commentary))) def update_range( self, mod, new_mod=None, new_min=None, new_max=None, new_commentary=None ): range = next((r for r in self.ranges if r.mod == mod), None) if range: range.update_range(new_mod, new_min, new_max, new_commentary) else: raise ValueError(&quot;No range with that mod name was found.&quot;) def delete_range(self, mod): range = next((r for r in self.ranges if r.mod == mod), None) if range: self.ranges.remove(range) else: raise ValueError(&quot;No range with that mod name was found.&quot;) def __repr__(self): ranges_str = &quot;\n&quot;.join([f&quot;{range}&quot; for range in self.ranges]) return f&quot;Model: {self.model}\nGeneral Commentary: {from_base64(self.generalCommentary)}\nRanges:\n{ranges_str}&quot; def toJSON(self): return { &quot;model&quot;: self.model, &quot;generalCommentary&quot;: self.generalCommentary, &quot;ranges&quot;: [r.toJSON() for r in self.ranges], } class Person: def __init__(self, name, color, latitude, longitude, walkie_talkies=list()): self.name = name self.color = color self.location = {&quot;latitude&quot;: latitude, &quot;longitude&quot;: longitude} self.walkie_talkies = walkie_talkies def add_walkie_talkie(self, model, general_commentary, ranges=list()): wt = WalkieTalkie(model, general_commentary, ranges) self.walkie_talkies.append(wt) def add_walkie_talkie2(self, walkie_talkie: WalkieTalkie): self.walkie_talkies.append(walkie_talkie) def update_walkie_talkie( self, model, new_model=None, new_general_commentary=None, new_ranges=None ): wt_to_update = next(wt for wt in self.walkie_talkies if wt.model == model) if new_model: wt_to_update.model = new_model if new_general_commentary: wt_to_update.generalCommentary = to_base64(new_general_commentary) if new_ranges: wt_to_update.ranges = new_ranges def delete_walkie_talkie(self, model): self.walkie_talkies = [wt for wt in self.walkie_talkies if wt.model != model] def __repr__(self): walkie_talkies_str = &quot;\n&quot;.join( [f&quot;{walkie_talkie}&quot; for walkie_talkie in self.walkie_talkies] ) return ( f&quot;Name: {self.name}\nLocation: ({self.location['latitude']}, {self.location['longitude']})\nWalkie &quot; f&quot;Talkies:\n{walkie_talkies_str} &quot; ) class TalkieRangeData: def __init__(self, filepath): self.filepath = filepath self.people = self.read_data() def read_data(self): # if file path does not exist, create it if not os.path.exists(self.filepath): with open(self.filepath, &quot;w&quot;) as f: f.write('\{&quot;people&quot;: []\}') with open(self.filepath, &quot;r&quot;) as f: try: data = json.load(f) return [ Person( person[&quot;name&quot;], person[&quot;color&quot;], person[&quot;location&quot;][&quot;latitude&quot;], person[&quot;location&quot;][&quot;longitude&quot;], [ WalkieTalkie( wt[&quot;model&quot;], from_base64(wt[&quot;generalCommentary&quot;]), [ Range( r[&quot;mod&quot;], r[&quot;minrange&quot;], r[&quot;maxrange&quot;], from_base64(r[&quot;commentary&quot;]), ) for r in wt[&quot;ranges&quot;] ], ) for wt in person[&quot;walkieTalkies&quot;] ], ) for person in data[&quot;people&quot;] ] except json.decoder.JSONDecodeError: return list() def add_person(self, name, color, latitude, longitude, overwrite=False): if not overwrite: existing_person = next( (person for person in self.people if person.name == name), None ) if existing_person: raise ValueError( &quot;A person with that name already exists. Set `overwrite` to True if you want to update the existing person.&quot; ) person = Person(name, color, latitude, longitude) self.people.append(person) self.update_json() def add_person2(self, pperson: Person, overwrite=False): if not overwrite: existing_person = next( (person for person in self.people if person.name == pperson.name), None ) if existing_person: raise ValueError( &quot;A person with that name already exists. Set `overwrite` to True if you want to update the existing person.&quot; ) self.people.append(pperson) self.update_json() def update_json(self): data = { &quot;people&quot;: [ { &quot;name&quot;: person.name, &quot;color&quot;: person.color, &quot;location&quot;: person.location, &quot;walkieTalkies&quot;: [wt.toJSON() for wt in person.walkie_talkies], } for person in self.people ] } with open(self.filepath, &quot;w&quot;) as f: json.dump(data, f, indent=2) def update_person( self, name, new_name=None, new_latitude=None, new_longitude=None, new_walkie_talkies=None, ): person_to_update = next(person for person in self.people if person.name == name) if new_name: person_to_update.name = new_name if new_latitude: person_to_update.location[&quot;latitude&quot;] = new_latitude if new_longitude: person_to_update.location[&quot;longitude&quot;] = new_longitude if new_walkie_talkies: person_to_update.walkie_talkies = new_walkie_talkies self.update_json() def delete_person(self, name): self.people = [person for person in self.people if person.name != name] self.update_json() def __repr__(self): return f&quot;TalkieRangeData&quot; </code></pre> <p>and here is my main.py file that I use to generate a kml file from input data</p> <pre class="lang-py prettyprint-override"><code>import json import os import simplekml from TalkieRangeData import ( TalkieRangeData, to_base64, from_base64, Person, WalkieTalkie, Range, ) from polycircles import polycircles def load_data(): if os.path.exists(&quot;talkies.json&quot;): trd = TalkieRangeData(&quot;talkies.json&quot;) else: print( &quot;talkies.json does not exist. Let's create it.First we need to create at least one user.&quot; ) name = input(&quot;Enter the name of the person: &quot;) color = input(&quot;Enter the color of the person: &quot;) latitude = input(&quot;Enter the latitude of the person: &quot;) longitude = input(&quot;Enter the longitude of the person: &quot;) model = input(&quot;Enter the model of the walkie talkie: &quot;) general_commentary = input( &quot;Enter the general commentary of the walkie talkie: &quot; ) mod = input(&quot;Enter the mod of the range: &quot;) rangemin = input(&quot;Enter the min of the range: &quot;) rangemax = input(&quot;Enter the max of the range: &quot;) commentary = input(&quot;Enter the commentary of the range: &quot;) json_data = { &quot;people&quot;: [ { &quot;name&quot;: name, &quot;location&quot;: {&quot;latitude&quot;: latitude, &quot;longitude&quot;: longitude}, &quot;walkieTalkies&quot;: [ { &quot;model&quot;: model, &quot;generalCommentary&quot;: to_base64(general_commentary), &quot;ranges&quot;: [ { &quot;mod&quot;: mod, &quot;min&quot;: rangemin, &quot;max&quot;: rangemax, &quot;commentary&quot;: to_base64(commentary), } ], } ], } ] } with open(&quot;talkies.json&quot;, &quot;w&quot;) as f: json.dump(json_data, f) trd = TalkieRangeData(&quot;talkies.json&quot;) return trd def main(): j = Person(&quot;J&quot;, &quot;00ff00&quot;, 0.956131, 0.587348) t = Person(&quot;T&quot;, &quot;ff0080&quot;, 0.943916, 0.609007) a = Person(&quot;A&quot;, &quot;ff00ff&quot;, 0.961872, 0.596557) l = Person(&quot;L&quot;, &quot;0000ff&quot;, 0.942723, 0.740706) bf888s = WalkieTalkie( &quot;BF-888S&quot;, &quot;This is a BF-888S&quot;, [Range(&quot;antenne normal&quot;, 1000, 2000, &quot;antenne standard&quot;)], ) uv5r = WalkieTalkie( &quot;UV-5R&quot;, &quot;This is a UV-55R&quot;, [Range(&quot;antenne normal&quot;, 5000, 7000, &quot;antenne standard&quot;)], ) thuv88 = WalkieTalkie( &quot;TH-UV88&quot;, &quot;This is a TH-UV88&quot;, [ Range(&quot;antenne normal&quot;, 3000, 5000, &quot;antenne standard&quot;), Range(&quot;antenne longue&quot;, 6000, 13000, &quot;antenne longue&quot;), ], ) # we all have a BF-888S j.add_walkie_talkie2(bf888s) t.add_walkie_talkie2(bf888s) a.add_walkie_talkie2(bf888s) l.add_walkie_talkie2(bf888s) j.add_walkie_talkie2(uv5r) l.add_walkie_talkie2(thuv88) # trd = load_data() trd = TalkieRangeData(&quot;talkies.json&quot;) trd.add_person2(j, overwrite=True) trd.add_person2(t, overwrite=True) trd.add_person2(a, overwrite=True) trd.add_person2(l, overwrite=True) kml = simplekml.Kml() # Create a folder for each person for person in trd.people: folder = kml.newfolder(name=person.name) for walkie_talkie in person.walkie_talkies: # Create a folder for each walkie talkie wt_folder = folder.newfolder( name=walkie_talkie.model, description=from_base64(walkie_talkie.generalCommentary), ) for mod in walkie_talkie.ranges: # Create a folder for each mod mod_folder = wt_folder.newfolder( name=mod.mod, description=from_base64(mod.commentary) ) # create two series of points for the ranges polygon = polycircles.Polycircle( latitude=person.location[&quot;latitude&quot;], longitude=person.location[&quot;longitude&quot;], radius=mod.minrange, number_of_vertices=100, ) polygon2 = polycircles.Polycircle( latitude=person.location[&quot;latitude&quot;], longitude=person.location[&quot;longitude&quot;], radius=mod.maxrange, number_of_vertices=100, ) # add the points to the kml using polygons in order bottomcircle = mod_folder.newpolygon( name=&quot;{}-{}-{} max range&quot;.format( person.name, walkie_talkie.model, mod.mod ), outerboundaryis=polygon2.to_kml(), ) topcircle = mod_folder.newpolygon( name=&quot;{}-{}-{} min range&quot;.format( person.name, walkie_talkie.model, mod.mod ), outerboundaryis=polygon.to_kml(), ) # set the color of the polygons bottomcircle.style.labelstyle.scale = 1 bottomcircle.style.labelstyle.color = simplekml.Color.hexa( person.color + &quot;33&quot; ) bottomcircle.style.polystyle.color = simplekml.Color.hexa( person.color + &quot;33&quot; ) topcircle.style.labelstyle.scale = 1 topcircle.style.labelstyle.color = simplekml.Color.hexa( person.color + &quot;80&quot; ) topcircle.style.polystyle.color = simplekml.Color.hexa( person.color + &quot;80&quot; ) kml.save(&quot;talkies.kml&quot;) if __name__ == &quot;__main__&quot;: main() </code></pre> <p>I'm very new to python oop and here is the issue I fall onto. My code create a json file the format seems to be correct but it gave all my Person the same talkies so it look like this:</p> <ul> <li>j <ul> <li>bf888s</li> <li>bf888s</li> <li>bf888s</li> <li>bf888s</li> <li>uv5r</li> <li>thuv88</li> </ul> </li> <li>l <ul> <li>bf888s</li> <li>bf888s</li> <li>bf888s</li> <li>bf888s</li> <li>uv5r</li> <li>thuv88</li> </ul> </li> <li>a <ul> <li>bf888s</li> <li>bf888s</li> <li>bf888s</li> <li>bf888s</li> <li>uv5r</li> <li>thuv88</li> </ul> </li> <li>t <ul> <li>bf888s</li> <li>bf888s</li> <li>bf888s</li> <li>bf888s</li> <li>uv5r</li> <li>thuv88</li> </ul> </li> </ul> <p>By running in debug mod I found out that each time I call add_walkie_talkie2(wt) it appends the wt to all my Person, does anyone knows why this occurs ?</p>
<python>
2022-12-27 23:10:44
0
436
lolozen
74,934,853
297,780
Fatal Python Error with SQLAlchemy connect_engine
<p>I'm trying to use Pandas to pull data from a remote DB2 database on an M1 Mac. My script works on a Windows 10 system, but I get a fatal error when I run from my Mac. I've never experienced fatal errors before so I'm not sure how to proceed with troubleshooting. Here's my code:</p> <pre><code>import pandas as pd from sqlalchemy import create_engine import ibm_db import ibm_db_sa import os dsn_database = &quot;mydb&quot; dsn_hostname = &quot;prod.site.com&quot; dsn_port = &quot;50001&quot; dsn_uid = &quot;...&quot; dsn_pwd = &quot;...&quot; ssl_trust_store_location = &quot;ROOT.cer&quot; ssl_trust_password = &quot;...&quot; credentials = {&quot;host&quot;:dsn_hostname,&quot;port&quot;:dsn_port,&quot;db&quot;:dsn_database,&quot;user&quot;:dsn_uid,&quot;pw&quot;:dsn_pwd} mydb_eng = create_engine(&quot;db2+ibm_db://{0}:{1}@{2}:{3}/{4};SECURITY=ssl;SSLServerCertificate={5};&quot;.format(credentials['user'],credentials['pw'],credentials['host'],str(credentials['port']),credentials['db'],ssl_trust_store_location)) mydb_conn = mydb_eng.connect() df = pd.read_sql_query('SELECT * FROM TABLE LIMIT 100;', mydb_conn) </code></pre> <p>When I run within a virtual environment in Spyder, I get the following error:</p> <pre><code>Fatal Python error: Aborted Main thread: Current thread 0x00000002034682c0 (most recent call first): File &quot;/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/ibm_db_dbi.py&quot;, line 629 in connect File &quot;/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/engine/default.py&quot;, line 598 in connect File &quot;/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/engine/create.py&quot;, line 578 in connect File &quot;/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/pool/base.py&quot;, line 680 in __connect File &quot;/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/pool/base.py&quot;, line 386 in __init__ File &quot;/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/pool/base.py&quot;, line 271 in _create_connection File &quot;/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/pool/impl.py&quot;, line 143 in _do_get File &quot;/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/pool/base.py&quot;, line 491 in checkout File &quot;/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/pool/base.py&quot;, line 888 in _checkout File &quot;/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/pool/base.py&quot;, line 325 in connect File &quot;/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/engine/base.py&quot;, line 3361 in _wrap_pool_connect File &quot;/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/engine/base.py&quot;, line 3394 in raw_connection File &quot;/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/engine/base.py&quot;, line 96 in __init__ File &quot;/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/engine/base.py&quot;, line 3315 in connect File &quot;/Users/lwd/Documents/Projects/mydb_Test/sqlalchemy_test.py&quot;, line 18 in &lt;module&gt; File &quot;/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/spyder_kernels/py3compat.py&quot;, line 356 in compat_exec File &quot;/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/spyder_kernels/customize/spydercustomize.py&quot;, line 469 in exec_code File &quot;/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/spyder_kernels/customize/spydercustomize.py&quot;, line 611 in _exec_file File &quot;/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/spyder_kernels/customize/spydercustomize.py&quot;, line 524 in runfile File &quot;/var/folders/3w/h_s63nl14p75qzww71xm_3fw0000gn/T/ipykernel_14510/3309860273.py&quot;, line 1 in &lt;cell line: 1&gt; Restarting kernel... </code></pre> <p>Line 18 of sqlalchemy_test.py is <code>mydb_conn = mydb_eng.connect()</code>. I don't know what to do with this info. So far I've tried:</p> <ol> <li>Running the code directly within Terminal.</li> <li>Running the code within Jupyter.</li> <li>Updating all of my packages.</li> <li>Using bad username or password to see if I could prompt a different error message.</li> </ol> <p>No progress yet, I get the same outcome regardless. Can anyone help decipher what Python is trying to tell me?</p>
<python><sqlalchemy><db2>
2022-12-27 23:06:00
0
1,414
Lenwood
74,934,746
2,266,881
Multiple responses/checkpoints in a flask env function from python
<p>I have a regular python script that runs some code and returns a response with some data in a flask environment. Now, i'm looking for a way to &quot;return&quot; or to somehow 'pass back' some kind of message to the request sender, without interrupting the process, to report the state of progress in the code (everytime it reaches certain points or similar).</p> <p>Something like this:</p> <pre><code>@app.route(&quot;/flask_function&quot;,methods=['GET','POST']) def flask_function: -- code -- -- code -- some_kind_of_return_function(&quot;Checkpoint A completed&quot;) -- code -- -- code -- some_kind_of_return_function(&quot;Checkpoint B completed&quot;) -- code -- -- code -- some_kind_of_return_function(&quot;Checkpoint C completed&quot;) -- code -- -- code -- return response </code></pre> <p>I have no idea how to do it, or if it's even possible in flask. Any advice would be more than welcome.</p>
<python><flask>
2022-12-27 22:47:37
0
1,594
Ghost
74,934,711
11,003,343
Couchbase / Python Access to sample project throws error UnAmbiguousTimeoutException error code 14
<p>I am trying to wrap my head arround couchbase DB. For that I am starting a couchbase cluster via docker-compose.</p> <pre class="lang-yaml prettyprint-override"><code>version: &quot;3.7&quot; services: couchbase1: # Starts a first node with the name couchbase1. image: couchbase:enterprise # defines the image that should be used the Tags enterprise and community can be used to define the version that should be used. Couchbase defaults to the enterprise version. ports: - &quot;8091-8096:8091-8096&quot; # the port 8091 supports the webinterface acsses. - &quot;11210-11211:11210-11211&quot; volumes: - ./db-data1:/opt/couchbase/var # Saves the folder &quot;/opt/couchbase/var&quot; in the folder &quot;db-data&quot; relative to this file&quot; couchbase2: # Starts a second node with the name couchbase2. image: couchbase:enterprise ports: - &quot;8090:8091&quot; # A secondary webinterterface piped to 8090 volumes: - ./db-data2:/opt/couchbase/var # A secondary memory for the second node in the test cluster volumes: db-data1: db-data2: </code></pre> <p>I assume that I can fully access <code>couchbase1</code>. I configured both and connected them via port 8091 to have a cluster with multiple nodes.</p> <p>I then tried to acces the cluster via <code>couchbase==4.1.1</code> with the code as shown in the example after loading the test data. The data exists and can be accesed over the webinterface.</p> <p>After executing the example code as given in the documentation on <a href="https://pypi.org/project/couchbase/" rel="nofollow noreferrer">pypi</a> as shown below I am recieving an error code 14</p> <pre class="lang-py prettyprint-override"><code>from couchbase.cluster import Cluster from couchbase.auth import PasswordAuthenticator # options for a cluster and SQL++ (N1QL) queries from couchbase.options import ClusterOptions, QueryOptions cluster = Cluster.connect('couchbase://localhost', ClusterOptions(PasswordAuthenticator( 'Administrator', 'some-pw-that-is-better-than-this!' ))) # get a reference to our bucket bucket = cluster.bucket('travel-sample') # get a reference to the default collection cb_coll = bucket.default_collection() # get a document result = cb_coll.get('airline_10') </code></pre> <p>I am recieving the following error at the last line:</p> <blockquote> <p>UnAmbiguousTimeoutException: &lt;ec=14, category=couchbase.common, message=unambiguous_timeout (14), context=KeyValueErrorContext:{'retry_attempts': 0, 'key': 'airline_10', 'bucket_name': 'travel-sample', 'scope_name': '_default', 'collection_name': '_default', 'opaque': 0, 'status_code': 0}, C Source=C:\Jenkins\workspace\python\sdk\python-scripted-build-pipeline\py-client\src\kv_ops.cxx:211&gt;</p> </blockquote> <p>This documentation is not realy helpfull to me: <a href="https://docs.couchbase.com/java-sdk/current/ref/error-codes.html#14-unambiguoustimeout" rel="nofollow noreferrer">docs</a> If somebody has any Idear what is wrong, how do debug something like this or anything in that direction I would apreciate it.</p>
<python><docker-compose><couchbase>
2022-12-27 22:41:56
1
664
NameVergessen
74,934,678
20,652,094
How to combine columns into a new table - Python or R
<p>Scenario:</p> <p>If I have this table, let's call it <code>df</code>:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>survey_answer_1___1</th> <th>survey_answer_1___2</th> <th>survey_answer_1___3</th> <th>survey_answer_2___1</th> <th>survey_answer_2___2</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>1</td> <td>0</td> <td>1</td> <td>0</td> </tr> <tr> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <td>0</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> </tr> <tr> <td>1</td> <td>1</td> <td>1</td> <td>0</td> <td>0</td> </tr> </tbody> </table> </div> <p>Using R or Python, how do I split and transform <code>df</code> into <code>survey_answer_1</code> and <code>survey_answer_2</code> like this:</p> <p><code>survey_answer_1</code>:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>1</th> <th>2</th> <th>3</th> </tr> </thead> <tbody> <tr> <td>2</td> <td>3</td> <td>1</td> </tr> </tbody> </table> </div> <p><code>survey_answer_2</code>:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>1</th> <th>2</th> </tr> </thead> <tbody> <tr> <td>2</td> <td>0</td> </tr> </tbody> </table> </div> <p>Where the column names of the new tables are extracted from <code>df</code> column names after <code>'___'</code>. The values in the new cells is the count of 1s in each column in <code>df</code>. This should be done automatically (tables should not be &quot;hard-coded&quot;), as there are many other columns in my data file that this should be applied on as well.</p> <p><code>split()</code> can be used to extract the numbers after <code>'___'</code> for column names. I tried implementing the rest using a dictionary, but it is not working.</p>
<python><r><python-3.x>
2022-12-27 22:36:35
5
307
user123
74,934,618
3,311,276
Getting ModuleNotFoundError: No module named 'MySQLdb'
<p>I created a virtualenv with following installed:</p> <pre><code>$ pip freeze aniso8601==9.0.1 attrs==22.2.0 click==8.1.3 configparser==5.3.0 Flask==2.2.2 flask-restplus==0.13.0 Flask-SQLAlchemy==3.0.2 greenlet==2.0.1 itsdangerous==2.1.2 Jinja2==3.1.2 jsonschema==4.17.3 MarkupSafe==2.1.1 mysql-connector-python==8.0.31 protobuf==3.20.1 PyMySQL==1.0.2 pyrsistent==0.19.2 pytz==2022.7 six==1.16.0 SQLAlchemy==1.4.45 Werkzeug==2.2.2 </code></pre> <p>You can see I have PyMySQL and mysql-connector-python installed but still I am getting this error:</p> <pre><code>Traceback (most recent call last): File &quot;/home/ciasto/Dev/crud_app/src/start.py&quot;, line 1, in &lt;module&gt; from todo_app.extensions import db File &quot;/home/ciasto/Dev/crud_app/src/todo_app/extensions.py&quot;, line 5, in &lt;module&gt; db = SQLAlchemy(app) File &quot;/home/ciasto/Dev/crud_app/crud_app_env/lib/python3.10/site-packages/flask_sqlalchemy/extension.py&quot;, line 219, in __init__ self.init_app(app) File &quot;/home/ciasto/Dev/crud_app/crud_app_env/lib/python3.10/site-packages/flask_sqlalchemy/extension.py&quot;, line 320, in init_app engines[key] = self._make_engine(key, options, app) File &quot;/home/ciasto/Dev/crud_app/crud_app_env/lib/python3.10/site-packages/flask_sqlalchemy/extension.py&quot;, line 606, in _make_engine return sa.engine_from_config(options, prefix=&quot;&quot;) File &quot;/home/ciasto/Dev/crud_app/crud_app_env/lib/python3.10/site-packages/sqlalchemy/engine/create.py&quot;, line 743, in engine_from_config return create_engine(url, **options) File &quot;&lt;string&gt;&quot;, line 2, in create_engine File &quot;/home/ciasto/Dev/crud_app/crud_app_env/lib/python3.10/site-packages/sqlalchemy/util/deprecations.py&quot;, line 309, in warned return fn(*args, **kwargs) File &quot;/home/ciasto/Dev/crud_app/crud_app_env/lib/python3.10/site-packages/sqlalchemy/engine/create.py&quot;, line 548, in create_engine dbapi = dialect_cls.dbapi(**dbapi_args) File &quot;/home/ciasto/Dev/crud_app/crud_app_env/lib/python3.10/site-packages/sqlalchemy/dialects/mysql/mysqldb.py&quot;, line 163, in dbapi return __import__(&quot;MySQLdb&quot;) ModuleNotFoundError: No module named 'MySQLdb' </code></pre> <p>I have tried reinstalling pip install MySQL-python pip install ConfigParser pip install MySQLdb</p> <p>I have tried the solutions from the <a href="https://stackoverflow.com/questions/53024891/modulenotfounderror-no-module-named-mysqldb">ModuleNotFoundError: No module named &#39;MySQLdb&#39;</a></p> <p>but it didn't worked for me. I am using ubuntu jammy on x86 platform.</p>
<python><mysql><sqlalchemy><mysql-python>
2022-12-27 22:26:20
2
8,357
Ciasto piekarz
74,934,456
2,601,293
Create an ISO9660 compliant filename using pycdlib
<p>I'm trying to implement the pycdlib <a href="https://clalancette.github.io/pycdlib/example-creating-new-basic-iso.html" rel="nofollow noreferrer">example-creating-new-basic-iso</a> example shown below. About half way down there is a line that reads, <code>iso.add_fp(BytesIO(foostr), len(foostr), '/FOO.;1')</code>. This writes a new file to the ISO that will be names &quot;FOO&quot; in the root directory of the iso. This example works for me.</p> <p>Building on the example, I'm trying to change the filename inside the iso from &quot;/FOO&quot;, to &quot;/FOO.txt&quot; but I keep getting the error, <code>PyCdlibInvalidInput: ISO9660 filenames must consist of characters A-Z, 0-9, and _</code>. How do I write an <a href="https://wiki.osdev.org/ISO_9660" rel="nofollow noreferrer">ISO9660</a> compliant filename with <a href="https://clalancette.github.io/pycdlib/pycdlib-api.html" rel="nofollow noreferrer">pycdlib</a> with &quot;.txt&quot; in it?</p> <p><strong>Example code:</strong></p> <pre><code>try: from cStringIO import StringIO as BytesIO except ImportError: from io import BytesIO import pycdlib iso = pycdlib.PyCdlib() iso.new() foostr = b'foo\n' iso.add_fp(BytesIO(foostr), len(foostr), '/FOO.;1') iso.add_directory('/DIR1') iso.write('new.iso') iso.close() </code></pre>
<python><iso9660>
2022-12-27 22:00:30
2
3,876
J'e
74,934,405
7,397,195
Scrapy Xpath or CSS Selector for next chevron
<p>consider this url: <a href="https://www.yachtworld.com/boats-for-sale/type-power/class-power-sport-fishing/?length=40-970" rel="nofollow noreferrer">boat listing</a></p> <p>I'm trying various selector methods to select the following tag for following the results to subsequent pages.</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>&lt;a rel="nofollow" class="icon-chevron-right " href="/boats-for-sale/type-power/class-power-sport-fishing/?length=40-970&amp;amp;page=2"&gt;&lt;span class="aria-fixes"&gt;2&lt;/span&gt;&lt;/a&gt;</code></pre> </div> </div> such that I select the right chevron (green highlight) to go to next page: <a href="https://i.sstatic.net/T57gC.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/T57gC.png" alt="paginator" /></a></p> <p>I've tried:</p> <pre><code>response.xpath(&quot;//a&quot;) # I get tags but none of the chevron links response.xpath('//a[@class = &quot;icon-chevron-right &quot;]') #note the space after 'right' response.xpath('//a[@rel = &quot;nofollow&quot;]') LinkExtractor.extract_links(response) # does not find these links </code></pre> <p>have also tried relative or chained selectors. Can't seem to figure this one out and think its probably some tricky nested tags to foil people like me!</p>
<python><css><xpath><scrapy>
2022-12-27 21:51:54
1
454
leeprevost
74,934,118
10,181,236
compute timeseries with values from a column of a pandas dataframe
<p>I have two dataframes df_t with columns: id, user_id, timestamp score and df_u with column user_id. A user_id in df_t may be repeated while it is unique in df_u. I want to compute a timeseries for each user_id of length 365, one step for each day of the year 2019. Each timestep needs to have the score of the user_id on that day. In df_t I can have timestamp before and after the 2019 and also there are missing days in 2019, I need to insert this day with a score o -1 on the timeseries.</p> <p>So this is the code</p> <pre><code>import pandas as pd import numpy as np df_t = pd.DataFrame({'id': [1, 2, 3, 4], 'user_id': [1, 2, 2, 2], 'timestamp': [&quot;2012-01-01&quot;, &quot;2019-01-20&quot;, &quot;2019-04-03&quot;, &quot;2019-05-01&quot;], 'score': [1, 3, 3, 4] }) print(df_t) df_u = pd.DataFrame({'user_id': [1, 2]}) print(df_u) df_u_expected = pd.DataFrame({'user_id': [1, 2], 'scores_list':[ [&quot;list of 365 '-1' since it does not have any score in 2019&quot;], [&quot;-1, ..., 3, ... 3, ..., 4 ..., -1, ...&quot;] ] }) print(df_u_expected) </code></pre> <p>Any idea on how to do this?</p>
<python><pandas>
2022-12-27 21:05:49
0
512
JayJona
74,933,925
3,572,505
regex python catch selective content inside curly braces, including curly sublevels and \n chars
<p>regex python catch <strong>selective</strong> content inside curly braces, including curly sublevels</p> <p>The best explanation is a minimum representative example (as you can see is for .bib for those who know latex..). Here is the representative input raw text:</p> <pre><code>text = &quot;&quot;&quot; @book{book1, title={tit1}, author={aut1} } @article{art2, title={tit2}, author={aut2} } @article{art3, title={tit3}, author={aut3} } &quot;&quot;&quot; </code></pre> <p>and here is my try (I failed..) to extract the content inside curly braces only for <strong>@article</strong> fields.. note that there are \n jumps inside that also want to gather.</p> <pre><code>regexpresion = r'\@article\{[.*\n]+\}' result = re.findall(regexpresion, text) </code></pre> <p>and this is actually what I wanted to obtain,</p> <pre><code>&gt;&gt;&gt; result ['art2,\ntitle={tit2},\nauthor={aut2}', 'art3,\ntitle={tit3},\nauthor={aut3}'] </code></pre> <p>Many thanks for your experience</p>
<python><regex><curly-braces>
2022-12-27 20:37:05
3
903
José Crespo Barrios
74,933,907
1,822,494
Question about copies on assignment in numpy
<p>Consider the following piece of code:</p> <pre><code>import numpy as np a = np.zeros(10) b = a b = b + 1 </code></pre> <p>If I print <code>a</code> and <code>b</code>, I get</p> <pre><code>&gt;&gt;&gt; a array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) </code></pre> <p>and</p> <pre><code>&gt;&gt;&gt; b array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]) </code></pre> <p>Why is this? According to <a href="https://stackoverflow.com/questions/19676538/numpy-array-assignment-with-copy">this answer</a>, the third line above binds the variable <code>a</code> to the new name <code>b</code>, so that both refer to the same data. So why doesn't <code>b = b + 1</code> modify <code>a</code> also?</p>
<python><numpy>
2022-12-27 20:34:25
1
818
TheProofIsTrivium
74,933,774
2,743,931
SWIG python MacOS issue
<p>I'm using MacOS on M1 Pro Macbook and I want to build a minimalistic-example SWIG binding to python.</p> <p>I have a C++ file:</p> <pre><code>// mymodule.cpp int square(int x){ return x*x; } </code></pre> <p>interface file</p> <pre><code>//mymodule.i %module mymodule %{ extern int square(int x); %} extern int square(int x); </code></pre> <p>Then I call:</p> <pre><code>swig -c++ -python -o mymodule_wrap.cpp mymodule.i gcc -c mymodule.cpp mymodule_wrap.cpp -I/Users/XXX/opt/anaconda3/include/python3.9 -fPIC gcc -shared mymodule.o mymodule_wrap.o -o _mymodule.so </code></pre> <p>and the third line gives me:</p> <pre><code>ld: symbol(s) not found for architecture arm64 clang: error: linker command failed with exit code 1 (use -v to see invocation) </code></pre> <p>What should I change to make it work?</p>
<python><c++><swig>
2022-12-27 20:16:15
0
312
user2743931
74,933,710
3,209,087
How to extract NULL and empty strings from MySQL into csv using Python with "" for empty string and nothing (not even quotes) for NULL
<p>I am trying to select specific columns from a MySQL table into csv. This table has integers, varchar, NULL and empty strings. I want to differentiate between NULL and empty strings in specific way.</p> <p>For DB row content: <code>ABC, 123,,NULL,2022-12-22</code></p> <p>The csv should have: <code>&quot;ABC&quot;|&quot;123&quot;|&quot;&quot;||&quot;2022-12-22&quot;</code></p> <p>Is there any way to do this using Python <strong>without having to do row level operations</strong>?</p> <p>I am trying to use Pandas and csv modules (open for other options as well) but couldn't find a way to represent DB NULL with nothing and empty string with &quot;&quot;.</p> <p>In csv I get either</p> <p>&quot;ABC&quot;|&quot;123&quot;|&quot;&quot;|&quot;&quot;|&quot;2022-12-22&quot; <code>#df.to_csv(r'file_name.csv', index=False, sep='|', quoting=csv.QUOTE_ALL, na_rep=None)</code></p> <p>OR</p> <p>&quot;ABC&quot;|123|&quot;&quot;|&quot;&quot;|&quot;2022-12-22&quot; <code>#df.to_csv(r'file_name.csv', index=False, sep='|', quoting=csv.QUOTE_NONNUMERIC, na_rep=None)</code></p> <p>OR</p> <p>ABC|123|||2022-12-22 <code>#df.to_csv(r'file_name.csv', index=False, sep='|', quoting=csv.QUOTE_MINIMAL, na_rep=None)</code></p> <p>My complete code is:</p> <pre><code>import mysql.connector import pandas as pd import csv mydb = mysql.connector.connect ( host = &quot;hostname&quot;, user = &quot;user_name&quot;, password = &quot;pwd&quot;, database = &quot;db_name&quot; ) sqlquery = pd.read_sql_query('''select * from db_name.table_name''') df = pd.DataFrame(sqlquery) df.to_csv(r'file_name.csv', index=False, sep='|', quoting=csv.QUOTE_ALL, na_rep=None) </code></pre> <p>I have checked many SO posts like following but none give the solution I am looking for:</p> <p><a href="https://stackoverflow.com/questions/72745917/writing-empty-string-with-quotes-and-null-value-without-quotes-while-writing-to">Writing-empty-string-with-quotes-and-null-value-without-quotes-while-writing-to</a></p> <p><a href="https://stackoverflow.com/questions/59173458/dont-convert-null-value-to-empty-string-when-exporting-mysql-data-to-csv">dont-convert-null-value-to-empty-string-when-exporting-mysql-data-to-csv</a></p> <p><a href="https://stackoverflow.com/questions/20665141/writing-a-pandas-dataframe-into-a-csv-file-with-some-empty-rows">writing-a-pandas-dataframe-into-a-csv-file-with-some-empty-rows</a></p>
<python><mysql><pandas><dataframe>
2022-12-27 20:08:09
0
1,041
300
74,933,691
19,797,660
Custom function Weighted Moving Average using Pandas.DataFrame, for some reason the value drops to 0.0 after 26 iterations
<p>I am testing my functions that calculates price indicators and I have a strange BUG that I don't know how to resolve.</p> <p>EDIT: Columns in the csv I've shared are all lower case, in case of testing the function with this csv you'd like to use this code:</p> <pre><code>data = pd.read_csv(csv_path) data = data.drop(['symbol'], axis=1) data.rename(columns={'open': 'Open', 'high': 'High', 'low': 'Low', 'close': 'Close', 'volume': 'Volume'}, inplace=True) </code></pre> <p><a href="https://www.transfernow.net/dl/202212279wwHGSDM" rel="nofollow noreferrer">Link to data .csv file</a> You can try it using the function with default arguments. (on the bottom of the post I am also sharing an auxilliary <code>input_type</code> function, just make sure not to use input mode higher than 4, since <code>HL2</code>, <code>HLC3</code>, <code>OHLC4</code> and <code>HLCC4</code> input modes are not calculated for this csv.</p> <p>So I am calculating <code>Weighted Moving Average</code> using this function:</p> <p>(I am testing this function with default arguments)</p> <pre><code>def wma(price_df: PandasDataFrame, n: int = 14, input_mode: int = 2, from_price: bool = True, *, indicator_name: str = 'None') -&gt; PandasDataFrame: if from_price: name_var, state = input_type(__input_mode__=input_mode) else: if indicator_name == 'None': raise TypeError('Invalid input argument. indicator_name cannot be set to None if from_price is False.') else: name_var = indicator_name wma_n = pd.DataFrame(index=range(price_df.shape[0]), columns=range(1)) wma_n.rename(columns={0: f'WMA{n}'}, inplace=True) weight = np.arange(1, (n + 1)).astype('float64') weight = weight * n norm = sum(weight) weight_df = pd.DataFrame(weight) weight_df.rename(columns={0: 'weight'}, inplace=True) product = pd.DataFrame() product_sum = 0 for i in range(price_df.shape[0]): if i &lt; (n - 1): # creating NaN values where it is impossible to calculate EMA to drop the later wma_n[f'WMA{n}'].iloc[i] = np.nan elif i == (n - 1): product = price_df[f'{name_var}'].iloc[:(i + 1)] * weight_df['weight'] product_sum = product.sum() wma_n[f'WMA{n}'].iloc[i] = product_sum / norm print(f'index: {i}, wma: ', wma_n[f'WMA{n}'].iloc[i]) print(product_sum) print(norm) product = product.iloc[0:0] product_sum = 0 elif i &gt; (n - 1): product = price_df[f'{name_var}'].iloc[(i - (n - 1)): (i + 1)] * weight_df['weight'] product_sum = product.sum() wma_n[f'WMA{n}'].iloc[i] = product_sum / norm print(f'index: {i}, wma: ', wma_n[f'WMA{n}'].iloc[i]) print(product_sum) print(norm) product = product.iloc[0:0] product_sum = 0 return wma_n </code></pre> <p>For some reason the value drops to <code>0.0</code> after 26 iteration, and I have no earthly idea why. Can someone please help me?</p> <p>My output:</p> <pre><code>index: 13, wma: 14467.42857142857 product_sum: 21267120.0 norm 1470.0 index: 14, wma: 14329.609523809524 product_sum: 21064526.0 norm 1470.0 index: 15, wma: 14053.980952380953 product_sum: 20659352.0 norm 1470.0 index: 16, wma: 13640.480952380953 product_sum: 20051507.0 norm 1470.0 index: 17, wma: 13089.029523809522 product_sum: 19240873.4 norm 1470.0 index: 18, wma: 12399.72 product_sum: 18227588.4 norm 1470.0 index: 19, wma: 11572.234285714285 product_sum: 17011184.4 norm 1470.0 index: 20, wma: 10607.100952380953 product_sum: 15592438.4 norm 1470.0 index: 21, wma: 9504.32 product_sum: 13971350.4 norm 1470.0 index: 22, wma: 8263.905714285715 product_sum: 12147941.4 norm 1470.0 index: 23, wma: 6885.667619047619 product_sum: 10121931.4 norm 1470.0 index: 24, wma: 5369.710476190477 product_sum: 7893474.4 norm 1470.0 index: 25, wma: 3716.270476190476 product_sum: 5462917.6 norm 1470.0 index: 26, wma: 1926.48 product_sum: 2831925.6 norm 1470.0 index: 27, wma: 0.0 product_sum: 0.0 norm 1470.0 index: 28, wma: 0.0 product_sum: 0.0 norm 1470.0 </code></pre> <p>Auxilliary function needed to run my function.</p> <pre><code>def input_type(__input_mode__: int) -&gt; (str, bool): list_of_inputs = ['Open', 'Close', 'High', 'Low', 'HL2', 'HLC3', 'OHLC4', 'HLCC4'] if __input_mode__ in range(1, 10, 1): input_name = list_of_inputs[__input_mode__ - 1] state = True return input_name, state else: raise TypeError('__input_mode__ out of range.') </code></pre>
<python><pandas>
2022-12-27 20:05:51
2
329
Jakub Szurlej
74,933,658
558,619
Python: Async function that works in script (__main__) and IPython
<p>I am struggling to wrap my head around how to get a simple class to work in both IPython (I use spyder interactive interpreter, Jupyter notebook etc a lot), as well as a traditional script launched from command line.</p> <p>At the top of my script, I have:</p> <pre><code>import asyncio import nest_asyncio nest_asyncio.apply() # &lt;--- from what I've seen, this is the easiest way to make async work in IPython. #Ultimately I'm trying to init this, and run net_position: class Surfbird_DB(): def __init__(self): # - - - - - - - - - - - - - - - - - - # MAIN ATTRIBUTES self.views = self._View_Models_Display() # - - - - - - - - - - - - - - - - - - # - - - - - - - - - - - - - #2) View Model functions / display class _View_Models_Display(): def __init__(self): pass def __run(self, fx): return Surfbird_View_Result(asyncio.run(fx)) @property def net_position(self): return self.__run(self.__get_net_position()) </code></pre> <p>However, when I run this script, I get the following error in command line.</p> <pre><code>RuntimeError: There is no current event loop in thread 'MainThread'. </code></pre> <p>Any help is appreciated!</p>
<python>
2022-12-27 20:01:31
0
3,541
keynesiancross
74,933,476
19,939,086
Finding a "good date" which has two or fewer different digits with an additional requirement
<p>I have a coding problem with determining a &quot;good date&quot; (more description below).</p> <p>I solved the original problem but got stuck on the follow-up problem. I attached my questions and solution to the original problem below. Thank you for your help in advance.</p> <h4>Original Problem:</h4> <blockquote> <p>YYYY/MM/DD format is a notation of date consisting of the zero-padded 4-digit year, zero-padded 2-digit month, and zero-padded 2-digit day, separated by slashes.</p> <p>A good date has two or fewer different digits in YYYY/MM/DD format.</p> <p>Given a date <code>S</code> in YYYY/MM/DD format. Print the first good day <strong>not earlier</strong> than <code>S</code>, in YYYY/MM/DD format. <code>S</code> is between January 1, 2001 and December 31, 2999 (inclusive).</p> </blockquote> <blockquote> <p>Ex. <code>2022/01/01</code> gives <code>2022/02/02</code> and <code>2999/12/31</code> gives <code>3000/03/03</code>.</p> </blockquote> <h3>Follow-up (stuck):</h3> <blockquote> <p>Find the closest good date instead; it can be either earlier or later than <code>S</code>.</p> </blockquote> <h3>My Questions:</h3> <ol> <li>Is there a better way to solve the original problem? I used a triple loop, so...</li> <li>How can I tackle the follow-up problem? I can only think of finding all good dates and comparing them to <code>S</code>...</li> </ol> <h3>My Solution to the Original Problem:</h3> <pre class="lang-py prettyprint-override"><code>class Solution: @staticmethod def good_date(s: str) -&gt; str: s = ''.join(s.split(&quot;/&quot;)) starting_year = eval(s + ' // 10000') for yyyy in range(starting_year, 3001): for mm in range(1, 13): for dd in range(1, 32): date = str(yyyy) + f&quot;{mm:02}&quot; + f&quot;{dd:02}&quot; if len(set(date)) == 2 and s &lt;= date: return date[:4] + &quot;/&quot; + date[4:6] + &quot;/&quot; + date[6:] if __name__ == '__main__': S = input() print(Solution.good_date(S)) </code></pre>
<python><algorithm><date><datetime>
2022-12-27 19:36:24
3
938
KORIN
74,933,414
3,612,823
Cross Join, Compare Values, and Select Closest Match - More Efficient Way?
<p>I asked a similar question in sql format here: <a href="https://stackoverflow.com/questions/74909237/cross-join-compare-values-and-select-closest-match-more-efficient-way">Cross Join, Compare Values, and Select Closest Match - More Efficient Way?</a></p> <p>I have two tables with 3 columns each. I cross join and subtract the values. I then find the t2.id that has the closest vals to t1.id</p> <p>These tables are quite large (50k rows in t1, 2m in t2, comparing 30 columns or more in real problem).</p> <p>What's the most efficient way to write this? It would be nice if <code>id_y</code> was only used once at most, but not really critical</p> <pre><code>import pandas as pd # sample tables t1 = {'id':['a1', 'a2', 'a3'], 'val1':[0.11,0.22,0.33], 'val2':[0.44,0.55,0.66]} t2 = {'id':['b1', 'b2', 'b3'], 'val1':[0.99,0.77,0.55], 'val2':[0.22,0.44,0.66]} df1 = pd.DataFrame(t1) df2 = pd.DataFrame(t2) print(df1) print(df2) # cross join df1['key'] = 0 df2['key'] = 0 df3 = df1.merge(df2, on='key', how='outer') print(df3) # calculate error df3['err'] = abs(df3['val1_x']-df3['val1_y']) + abs(df3['val2_x']-df3['val2_y']) + abs(df3['val2_x']-df3['val2_y']) # choose lowest error for each t1.id # would be nice if it used id_y max once each df4 = df3.loc[df3.groupby('id_x')['err'].idxmin()] df5 = df4[['id_x', 'id_y', 'err']] print(df5) </code></pre>
<python><pandas><numpy>
2022-12-27 19:28:19
1
1,053
Adam12344
74,933,280
157,971
How can I transform or query JSON data in my Github Workflow?
<p>I am using the <code>octokit/request-action</code> action in my Github Workflow to <a href="https://docs.github.com/en/rest/releases/releases?apiVersion=2022-11-28#get-a-release-by-tag-name" rel="nofollow noreferrer">obtain information about a certain Github Release via its tag name</a>:</p> <pre class="lang-yaml prettyprint-override"><code>- name: Get Release Info uses: octokit/request-action@v2.x id: release with: route: GET /repos/{org_repo}/releases/tags/{tag} </code></pre> <p>The response JSON structure contains information about all of the assets attached to the release. I need to use this information to build a list of download URLs for all the release artifacts and pass that into a Python script that builds a discord notification.</p> <p>Using the Github Workflow YAML, how do I &quot;query&quot; the JSON data (similar to <a href="https://jsonata.org/" rel="nofollow noreferrer">JSONata</a>) to obtain a list of all the <code>browser_download_url</code> values inside the <code>assets</code> array? The data returned looks like this (trimmed):</p> <pre class="lang-json prettyprint-override"><code>{ &quot;url&quot;: &quot;https://api.github.com/repos/octocat/Hello-World/releases/1&quot;, &quot;id&quot;: 1, &quot;assets&quot;: [ { &quot;url&quot;: &quot;https://api.github.com/repos/octocat/Hello-World/releases/assets/1&quot;, &quot;browser_download_url&quot;: &quot;https://github.com/octocat/Hello-World/releases/download/v1.0.0/example1.zip&quot;, &quot;id&quot;: 1 }, { &quot;url&quot;: &quot;https://api.github.com/repos/octocat/Hello-World/releases/assets/2&quot;, &quot;browser_download_url&quot;: &quot;https://github.com/octocat/Hello-World/releases/download/v1.0.0/example2.zip&quot;, &quot;id&quot;: 2 } ] } </code></pre> <p>The end result I want is a way to pass the two download URLs above to my script like so (using a separate step in my workflow):</p> <pre><code>python discord_notification.py &quot;https://github.com/octocat/Hello-World/releases/download/v1.0.0/example1.zip&quot; &quot;https://github.com/octocat/Hello-World/releases/download/v1.0.0/example2.zip&quot; </code></pre> <p>(Exact syntax can vary; the above snippet is just an example)</p> <p>It's possible that what I want to do just can't be achieved in the workflow YAML itself. If that's the case, I'd be OK with a solution that involves passing all or part of the response JSON to the Python script and use Python itself to parse the JSON data. I just don't know if Bash adds a layer of complexity that will make passing a multi-line response string as a parameter difficult.</p>
<python><json><github-actions><github-api>
2022-12-27 19:09:42
0
26,702
void.pointer
74,933,255
9,977,758
Tk button is not clickable and image is not loading
<p>I have created a GUI that shows data about videos from YouTube and allows me to select which video I want to download.</p> <p>The code works well, but for some reason some of the images don't load and I can't select the video.</p> <p>This is the result I get:</p> <p><a href="https://i.sstatic.net/LBg2Z.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/LBg2Z.png" alt="GUI result" /></a></p> <p>it is always the few first images that don't load. And, as I mentioned, I can't click on them at all.</p> <p>This is my code:</p> <pre><code>from __future__ import annotations import contextlib import dataclasses import datetime import tkinter as tk from io import BytesIO from typing import Iterable, Any import requests from PIL import Image, ImageTk @dataclasses.dataclass class VideoData: id: str title: str uploader: str duration: int thumbnail: str def _initialize_root(root: tk.Tk): root.title('Downloader') # root.protocol('WM_DELETE_WINDOW', lambda: ...) root.attributes('-topmost', True) root.minsize(350, 200) class Gui: def __init__(self, videos: Iterable[VideoData]): self._root = tk.Tk() _initialize_root(self._root) self._frame = tk.Frame(self._root) self._frame.grid(row=0, column=0, sticky='news') for row, video in enumerate(videos): self._create_video_line(video, row) self._frame.grid_columnconfigure('all', weight=1) self._root.grid_columnconfigure('all', weight=1) self.selected_row = -1 def start(self): self._root.mainloop() def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() def close(self): self._root.quit() with contextlib.suppress(tk.TclError): self._root.destroy() def _on_click(self, row: int): self.selected_row = row self.close() def _create_video_line(self, video_data: VideoData, row: int) -&gt; None: response = requests.get(video_data.thumbnail) image_data = response.content # Create a PhotoImage from the image data and resize it print(f'Getting thumbnail image from {video_data.thumbnail!r}') image = Image.open(BytesIO(image_data)).resize((200, 200)) # Convert to a PNG image with BytesIO() as fp: image.save(fp, 'PNG') png_image = Image.open(fp) thumbnail = ImageTk.PhotoImage(png_image) // Create the button button = tk.Button(self._frame, image=thumbnail, width=200, height=200, command=lambda: self._on_click(row)) button.grid(row=row, column=0, columnspan=1, sticky=&quot;news&quot;) duration = datetime.timedelta(seconds=video_data.duration) text_label = tk.Label(self._frame, text=f'{video_data.title} by {video_data.uploader} (duration: {duration})' , anchor='w') text_label.grid(row=row, column=1, columnspan=1, sticky=&quot;news&quot;) </code></pre> <p>How can I fix this issue? I don't mind to add a default image, but I can't find out if the image is loaded or not.</p>
<python><tkinter><tkinter-button><tkinter-photoimage>
2022-12-27 19:07:27
1
1,050
SagiZiv
74,933,254
3,928,553
Trichromy photography based on PIL
<p>I'm trying to imitate in a simple way (=&gt; without any I.A.) <a href="https://en.wikipedia.org/wiki/Trichromy" rel="nofollow noreferrer">the old trichromy process to colorize B&amp;W photographs</a>.</p> <p><a href="https://i.sstatic.net/dpFlP.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/dpFlP.jpg" alt="Source : CNRS" /></a></p> <p>Here's the start picture :</p> <p><a href="https://i.sstatic.net/JZDjn.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/JZDjn.jpg" alt="enter image description here" /></a></p> <p>I copied this picture in a red, green and blue version by using Pillow :</p> <p><a href="https://i.sstatic.net/jjE9W.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/jjE9W.png" alt="enter image description here" /></a></p> <p>Each filtered picture has a reduced opacity (I used a putalpha(round(255/3)) for this case), and these are valid PNG files.</p> <p>Then, I tried to merge this three samples, but there are no colors at the end. The results is the same by using paste or alpha_composite after a for loop :</p> <p><a href="https://i.sstatic.net/j7Xys.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/j7Xys.jpg" alt="enter image description here" /></a></p> <p>Was I too optimistic or did I miss something to achieve this ?</p> <p><strong>EDIT</strong></p> <p>Here's the filter color function. It's certainly heavy because it compared each red, green and blue level of apixel in a picture with the red, green and blue level of the filter's color. But, still :</p> <pre><code>def color_photo(file:str,color:tuple,def_file_name:str): &quot;&quot;&quot; This function colorizes a picture based on a RGB color. Example : put a red filter on a B&amp;W photo. &quot;&quot;&quot; try: format_file = file.split(&quot;.&quot;)[-1] img = Image.open(file).convert(&quot;RGB&quot;) pixels = img.load() res = img.info[&quot;dpi&quot;] w, h = img.size for px in range(w): for py in range(h): l_col = [int(new_level) if int(new_level)&lt;int(old_level) else int(old_level) for new_level,old_level in zip(color,img.getpixel((px,py)))] pixels[px,py] = tuple(l_col) img.save(def_file_name+&quot;.&quot;+format_file,dpi = res, subsampling = 0, quality = 100, optimize = True) except: print(&quot;You must do a mistake handling file names and/or the tuples of RGB's color instead of something like (234,125,89)&quot;) </code></pre>
<python><python-imaging-library><photography>
2022-12-27 19:07:06
1
617
Raphadasilva
74,933,141
3,405,980
python regex split function equivalent in golang
<p>I've below python code to match regex::</p> <pre><code>import re digits_re = re.compile(&quot;([0-9eE.+]*)&quot;) p = digits_re.split(&quot;Hello, where are you 1.1?&quot;) print(p) </code></pre> <p>It gives this output::   <code>['', '', 'H', 'e', '', '', 'l', '', 'l', '', 'o', '', ',', '', ' ', '', 'w', '', 'h', 'e', '', '', 'r', 'e', '', '', ' ', '', 'a', '', 'r', 'e', '', '', ' ', '', 'y', '', 'o', '', 'u', '', ' ', '1.1', '', '', '?', '', '']</code></p> <p>I'm trying to get the above output with <code>golang</code>.</p> <pre><code>package main import ( &quot;bytes&quot; &quot;fmt&quot; &quot;log&quot; &quot;os/exec&quot; &quot;regexp&quot; &quot;strconv&quot; ) func main() { // Execute the command and get the output cmd := exec.Command(&quot;echo&quot;, &quot;Hello, where are you 1.1?&quot;) var out bytes.Buffer cmd.Stdout = &amp;out err := cmd.Run() if err != nil { log.Fatal(err) } // Extract the numerical values from the output using a regular expression re := regexp.MustCompile(`([0-9eE.+]*)`) //matches := re.FindAllString(out.String(), -1) splits := re.Split(out.String(), -1) fmt.Println(splits) } </code></pre> <p>I get output like below::</p> <pre><code>[H l l o , w h r a r y o u ? ] </code></pre> <p>I think regex is language dependant, so <code>split()</code> function used in python won't be helpful with <code>golang</code>. Having used multiple <code>Find*()</code> functions part of <code>regexp</code> package but couldn't find one which could provide the output of the above python program.</p> <p>The goal of the output string array is to separate characters that can't be converted to <code>float</code> &amp; if a string can be parsed to float, I calculate the moving average.</p> <p>In the end, I combine everything &amp; present output like Linux <code>watch</code> command.</p> <p>Shall you need more details/context? I would be glad to share.</p> <p>Your help is much appreciated!</p>
<python><regex><go><regex-group>
2022-12-27 18:53:48
2
3,962
harshavmb
74,933,076
14,676,485
How to extract array element from array column?
<p>I'm working with a dataset available here: <a href="https://www.kaggle.com/datasets/lehaknarnauli/spotify-datasets?select=artists.csv" rel="nofollow noreferrer">https://www.kaggle.com/datasets/lehaknarnauli/spotify-datasets?select=artists.csv</a>. What I want to do is to extract first element of each array in column <code>genres</code>. For example, if I got ['pop', 'rock'] I'd like to extract 'pop'. I tried different approaches but none of them works, I don't know why.</p> <p>Here is my code:</p> <pre><code>import pandas as pd df = pd.read_csv('artists.csv') # approach 1 df['top_genre'] = df['genres'].str[0] # Error: 'str' object has no attribute 'str' # approach 2 df = df.assign(top_genre = lambda x: df['genres'].str[0]) # The result is single bracket '[' in each row. Seems like index=0 refers to first character of a string, not first array element. # approach 3 df['top_genre'] = df['genres'].apply(lambda x: '[]' if not x else x[0]) # The result is single bracket '[' in each row. Seems like index=0 refers to first character of a string, not first array element. </code></pre> <p>Why these approaches doesn't work and how to make it work out?</p>
<python><pandas>
2022-12-27 18:46:48
2
911
mustafa00
74,933,024
1,441,592
How to create new pandas dataframe column from file that contains json?
<p>I have a dataset with metadata about voice calls</p> <p>It looks like</p> <pre><code>Data columns (total 4 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 phone 100 non-null string 1 group_id 100 non-null int64 2 question_id 100 non-null int64 3 result 100 non-null bool </code></pre> <p>I want to create column #4 that will contain some dialogue statistics, e.g. <code>total_words (int64)</code>, and data must be taken from exteral json file, containing speech-to-text recognition results</p> <p><strong>Is there any build-in pandas way to do that ?</strong></p> <p>I've tested with <a href="https://pandas.pydata.org/docs/reference/api/pandas.read_json.html" rel="nofollow noreferrer">pandas.read_json</a> but getting module errors (<code>ValueError: DataFrame constructor not properly called!</code> and <code>TypeError: argument of type 'method' is not iterable</code>)</p> <p>I'm looking for something like</p> <pre><code>df['total_words'] = pd.read_json('file://localhost:8888/auido/' + df['phone'] + '.mp3.wstat.json') </code></pre> <p>I would be glad if someone will provide a working code example of solving similar issue</p> <p>UPD: output of json file is like <code>{&quot;total_words&quot;: 74}</code></p>
<python><pandas>
2022-12-27 18:40:01
1
3,341
Paul Serikov
74,932,923
1,230,479
Beautiful soup not loading new page after Selenium click
<p>The first page is loaded and parsed as expected but after the clicking on Next page, the BS4 does not get the new page from driver.page_source</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager from bs4 import BeautifulSoup as soup from urllib.request import urlopen as ureq import random import time driver = webdriver.Chrome(service=Service(ChromeDriverManager().install())) def parse_html(pagesource, count): soup = BeautifulSoup(driver.page_source, 'html.parser') tables = soup.findChildren('table') # This will get the first (and only) table. Your page may have more. my_table = tables[0] table_body = my_table.find('tbody') all_rows = table_body.find_all('tr') # print (all_rows[0]) for row in all_rows: print (count) count += 1 try: path_body = row.find(&quot;td&quot;, class_=&quot;views-field-company-name&quot;) path = path_body.find(&quot;a&quot;)['href'] company_name = path_body.find(&quot;a&quot;).text company_name = company_name.strip() print (company_name) issue_datetime = row.find(&quot;td&quot;, class_=&quot;views-field-field-letter-issue-datetime&quot;) # print (type(issue_datetime.find(&quot;time&quot;)['datetime'])) issue_recepient_office = row.find(&quot;td&quot;, class_=&quot;views-field-field-building&quot;).string issue_recepient_office = issue_recepient_office.strip() # print (issue_recepient_office) detailed_description = row.find(&quot;td&quot;, class_=&quot;views-field-field-detailed-description-2&quot;).string if detailed_description: detailed_description = detailed_description.strip() else: detailed_description = &quot;&quot; #print (detailed_description) except: pass url = 'https://www.fda.gov/inspections-compliance-enforcement-and-criminal-investigations/compliance-actions-and-activities/warning-letters' driver.get(url) count = 1 parse_html(driver.page_source, count) for i in range(0,3): time.sleep(10) #print(driver.page_source.encode('utf-8')) WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#datatable_next a'))).click() time.sleep(30) parse_html(driver.page_source, count) driver.quit() </code></pre> <p>Output:</p> <pre><code>1 Ruth Special Food Store LLC Foreign Supplier Verification Program (FSVP) 2 EarthLab, Inc., dba Wise Woman Herbals 3 Big Olaf Creamery LLC dba Big Olaf CGMP/Food/Prepared, Packed or Held Under Insanitary Conditions/Adulterated/L. monocytogenes 4 Bainbridge Beverage West, LLC Juice HACCP/CGMP for Foods/Adulterated/Insanitary Conditions 5 VapeL1FE, LLC Family Smoking Prevention and Tobacco Control Act/Adulterated/Misbranded 6 Mike Millenkamp Dairy Cattle 7 Empowered Diagnostics LLC Unapproved Products Related to the Coronavirus Disease 2019 (COVID-19) 8 RoyalVibe Health Ltd. CGMP/QSR/Medical Devices/PMA/Adulterated/Misbranded 9 Land View, Inc. CGMP/Medicated Feeds/Adulterated 10 Green Pharmaceuticals Inc. 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 </code></pre>
<python><selenium><selenium-webdriver>
2022-12-27 18:29:04
1
2,119
futurenext110
74,932,855
12,596,824
getting directories and subdirectories using python OS and outputting csv file
<p>I want to write Python code to create a CSV file based on getting information from a directory and subdirectories only if the subdirectory contains moo.</p> <pre><code>. ├── a.txt ├── b.txt ├── foo │ └── w.txt │ └── a.txt └── moo └── cool.csv └── bad.csv └── more └── wow.csv </code></pre> <p>Expected Pandas dataframe:</p> <pre><code>FilePath S:\Test\moo\cool.csv S:\Test\moo\bad.csv S:\Test\moo\cool.csv S:\Test\moo\more\wow.csv </code></pre> <p>How can I do this in python?</p> <p>So far I gave the following code but not sure how to complete:</p> <pre><code>import os import pandas as pd root = 'S:\Test' for path, subdirs, files in os.walk(root): print(path) </code></pre>
<python><operating-system>
2022-12-27 18:21:36
1
1,937
Eisen
74,932,787
18,366,396
How to make python request (oauth2)
<p>i need to get the token for making the finale api rest requests. The specs of the api are:</p> <ol> <li><p><code>basicAuthentication</code> Use: the <code>client_id</code> and <code>client_secret</code> (both URL-encoded, RFC6749) separated by a semicolon &quot;{{client_id}}:{{client_secret}}&quot; <code>base64 encoded</code></p> </li> <li><p>code for putting in the request is the <code>authorization code</code> (this code i have already)</p> </li> <li><p>its the <code>oauth2 flow</code>, so get code, then with code get the authorization code to make the finale api requests.</p> </li> </ol> <p>From the website of the api here is an example request to get the final token:</p> <pre><code>POST /connect/token HTTP/1.1 Host: identityservice.nmbrs.com Authorization: Basic {{basicAuthentication}} Content-Type: application/x-www-form-urlencoded grant_type=authorization_code &amp;code={{code}} &amp;redirect_uri={{redirect_uri}} </code></pre> <p>and this should be the response (an example from the site of the api)</p> <pre><code>{ &quot;access_token&quot;: {{access_token}}, &quot;expires_in&quot;: 3600, &quot;token_type&quot;: &quot;Bearer&quot;, &quot;refresh_token&quot;: {{refresh_token}}, &quot;scope&quot;: {{scopes}} } </code></pre> <p>Well now i want to make the request in python:</p> <pre><code>url = &quot;https://identityservice.nmbrs.com/connect/token&quot; headers = { &quot;grant_type=authorization_code&quot; 'Content-Type': &quot;application/x-www-form-urlencoded&quot;, 'client_id':&quot;23232323&quot;, //example 'client_secret':'12344555', //example 'code':'1223455', //i have this code 'redirect_uri':'http://localhost:8080/callback' } response = requests.request(&quot;POST&quot;, url, headers=headers) print(response) </code></pre> <p>i get an 403 error, i dont think my code is right. I should get the <code>access_token.</code></p>
<python>
2022-12-27 18:12:42
1
841
saro
74,932,511
13,086,128
-1 < 2 == 1 False?
<p>I am comparing an equation in python:</p> <pre><code>-1 &lt; 2 == 1 </code></pre> <p>it gives <code>False</code> as output</p> <p>The Left Hand side of the <code>==</code>:</p> <p><code>-1 &lt; 2</code> which evaluates to <code>True</code></p> <p>Right Hand side of the <code>==</code> is:</p> <p><code>1</code></p> <p>On comparing <code>L.H.S==R.H.S</code></p> <p><code>True==1</code></p> <p>which should evaluate to <code>True</code>?</p>
<python><python-3.x><math>
2022-12-27 17:42:36
1
30,560
Talha Tayyab
74,932,426
11,135,962
Faster/better way to extract string with a substring present in a list?
<p>I have a couple of lists <code>generator = [&quot;one#zade&quot;, &quot;one#zaat&quot;, &quot;one#osde&quot;, &quot;one#za&quot;]</code> &amp; <code>accepted_channels = [&quot;zade&quot;, &quot;zaat&quot;]</code>.</p> <p>I am trying to extract elements from the <code>generator</code> list which have as a substring any one of the values that are present in the <code>accepted_channels</code> list.</p> <p>I have a code and it works correctly, but it has 3 loops involved. Is there a way to write the code without any loops or with a reduced number of loops?</p> <pre><code>generator = [&quot;one#zade&quot;, &quot;one#zaat&quot;, &quot;one#osde&quot;, &quot;one#za&quot;] accepted_channels = [&quot;zade&quot;, &quot;zaat&quot;] final_records = [] for item in generator: for channel in accepted_channels: if channel in item: final_records.append(item) print(final_records) # prints ['one#zade', 'one#zaat'] </code></pre> <p>P.S.: Here, the <code>generator</code> only has 4 elements, but in real I have a list of more than 50000 elements.</p>
<python><performance><for-loop>
2022-12-27 17:32:30
1
3,620
some_programmer
74,932,417
15,637,435
How to efficiently build ngrams based on categories in a dataframe
<h2>Problem</h2> <p>I have a dataframe that consists of text which belongs to a category. I now want to get the most commonly used n-grams (bigrams in the example) per category. I managed to do this, but the code for this is way too long in my opinion.</p> <h2>Sample Code</h2> <pre><code>import pandas as pd import nltk from nltk.tokenize import word_tokenize from nltk.util import ngrams # Sample data data = {'text':['sport sport text sample sport sport text sample', 'math math text sample math math text sample', 'politics politics text sample politics politics text sample'], 'category' : [&quot;sport&quot;, &quot;math&quot;, &quot;politics&quot;]} df = pd.DataFrame(data) # Get text per category sport = [df[df['category'] == 'sport'].reset_index()['text'].iloc[0]] math = [df[df['category'] == 'math'].reset_index()['text'].iloc[0]] politics = [df[df['category'] == 'politics'].reset_index()['text'].iloc[0]] # Calculate ngrams per category n = 2 sport_ngrams = [] for sample in sport: sport_ngrams.extend(ngrams(nltk.word_tokenize(sample), n)) sport_ngrams_df = pd.DataFrame(pd.Series(sport_ngrams).value_counts()[:10]).reset_index() sport_ngrams_df['category'] = 'Business &amp; Finance' math_ngrams = [] for sample in math: math_ngrams.extend(ngrams(nltk.word_tokenize(sample), n)) math_ngrams_df = pd.DataFrame(pd.Series(math_ngrams).value_counts()[:10]).reset_index() math_ngrams_df['category'] = 'Computers &amp; Internet' politics_ngrams = [] for sample in politics: politics_ngrams.extend(ngrams(nltk.word_tokenize(sample), n)) politics_ngrams_df = pd.DataFrame(pd.Series(politics_ngrams).value_counts()[:10]).reset_index() politics_ngrams_df['category'] = 'Education &amp; Reference' # Concatenate df's bigram_df = pd.concat([sport_ngrams_df, math_ngrams_df, politics_ngrams_df ]).rename(columns={&quot;index&quot;: &quot;word&quot;, 0:'count'}) bigram_df </code></pre> <p><strong>Output</strong></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>word</th> <th>count</th> <th>category</th> </tr> </thead> <tbody> <tr> <td>('sport', 'sport')</td> <td>2</td> <td>Business &amp; Finance</td> </tr> <tr> <td>('sport', 'text')</td> <td>2</td> <td>Business &amp; Finance</td> </tr> <tr> <td>('text', 'sample')</td> <td>2</td> <td>Business &amp; Finance</td> </tr> <tr> <td>('sample', 'sport')</td> <td>1</td> <td>Business &amp; Finance</td> </tr> <tr> <td>('math', 'math')</td> <td>2</td> <td>Computers &amp; Internet</td> </tr> <tr> <td>('math', 'text')</td> <td>2</td> <td>Computers &amp; Internet</td> </tr> <tr> <td>('text', 'sample')</td> <td>2</td> <td>Computers &amp; Internet</td> </tr> <tr> <td>('sample', 'math')</td> <td>1</td> <td>Computers &amp; Internet</td> </tr> <tr> <td>('politics', 'politics')</td> <td>2</td> <td>Education &amp; Reference</td> </tr> <tr> <td>('politics', 'text')</td> <td>2</td> <td>Education &amp; Reference</td> </tr> <tr> <td>('text', 'sample')</td> <td>2</td> <td>Education &amp; Reference</td> </tr> <tr> <td>('sample', 'politics')</td> <td>1</td> <td>Education &amp; Reference</td> </tr> </tbody> </table> </div><h2>Question</h2> <p>Is there a more efficient way to build the n-grams where I don't have to get the text and create the n-grams per category separately?</p> <p>Thank you already for the help!</p>
<python><pandas><nlp><nltk><n-gram>
2022-12-27 17:32:04
1
396
Elodin
74,932,372
11,642,909
Matplotlib animation update legend using ArtistAnimation
<p>I want to update the legends in using the ArtistAnimation from Matplotlib.</p> <p>I try to adapt this solution : <a href="https://stackoverflow.com/questions/49158604/matplotlib-animation-update-title-using-artistanimation">Matplotlib animation update title using ArtistAnimation</a> to the legend but it didn't worked. I tried a bunch of others things too but nothing seems to work.</p> <p>In this case, I got no error, the result is just not what's expected. The legend appears 1 time over 3, only for the green. And the result I want is that the legends change each time with the good color and label.</p> <p>Here is a minimal example of what I've done :</p> <pre><code>import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib import animation import numpy as np a = np.random.rand(3,3) fig, ax=plt.subplots() container = [] colors = [&quot;red&quot;,&quot;blue&quot;,&quot;green&quot;] labels = [0,1,2] for i in range(a.shape[1]): line, = ax.plot(a[:,i], color=colors[i]) title = ax.text(0.5,1.05,&quot;Title {}&quot;.format(i), size=plt.rcParams[&quot;axes.titlesize&quot;], ha=&quot;center&quot;, transform=ax.transAxes, ) legend = ax.legend(handles=[mpl.patches.Patch(color=colors[i], label=labels[i])]) container.append([line, title, legend]) ani = animation.ArtistAnimation(fig, container, interval=750, blit=False) #ani.save('videos/test.gif') plt.show() </code></pre> <p>Here is the result : <a href="https://i.sstatic.net/UGyEf.gif" rel="nofollow noreferrer"><img src="https://i.sstatic.net/UGyEf.gif" alt="Result" /></a></p>
<python><matplotlib>
2022-12-27 17:26:01
1
391
Pierre Marsaa
74,932,285
1,230,479
Python Selenium: Clicking on the next page not working
<p>I am using the following code to click on the next page, by clicking the next element.</p> <p>However this code is not working. Any thoughts on what I might be doing wrong.</p> <p>Final goal:</p> <p>Use BeautifulSoup on each of the pages.</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from bs4 import BeautifulSoup as soup from urllib.request import urlopen as ureq import random import time from bs4 import BeautifulSoup from selenium.webdriver.common.by import By chrome_options = webdriver.ChromeOptions() prefs = {&quot;profile.default_content_setting_values.notifications&quot;: 2} chrome_options.add_experimental_option(&quot;prefs&quot;, prefs) # A randomizer for the delay seconds = 1 + (random.random() * 2) # create a new Chrome session driver = webdriver.Chrome(chrome_options=chrome_options) driver.implicitly_wait(30) # driver.maximize_window() # navigate to the application home page driver.get(&quot;https://www.fda.gov/inspections-compliance-enforcement-and-criminal-investigations/compliance-actions-and-activities/warning-letters&quot;) time.sleep(seconds) time.sleep(seconds) next_page = driver.find_element(By.CLASS_NAME, &quot;next&quot;) #print (next_page.get_attribute('innerHTML'), type(next_page)) next_page.find_element(By.XPATH(&quot;//a[@href='#']&quot;)).click # next_page.find_element(By.LINK_TEXT(&quot;Next&quot;)).click() </code></pre> <p>This code does not click on the next page.</p>
<python><selenium><selenium-webdriver>
2022-12-27 17:17:01
1
2,119
futurenext110
74,932,013
9,874,393
Is this proper use of a ternary operator
<p>I want a short form the remove an element from a list and use the following:</p> <pre><code>&gt;&gt;&gt; a = [1, 2, 3, 4] &gt;&gt;&gt; val = 3 &gt;&gt;&gt; a.remove(val) if val in a else None &gt;&gt;&gt; a &gt;&gt;&gt; [1, 2, 4] &gt;&gt;&gt; val = 10 &gt;&gt;&gt; a.remove(val) if val in a else None &gt;&gt;&gt; a &gt;&gt;&gt; [1, 2, 4] </code></pre> <p>Obviously it works but is it a proper use of a ternary operator?</p>
<python>
2022-12-27 16:50:42
1
3,555
Bruno Vermeulen
74,932,007
6,734,243
is it possible to iterate a Tuple traitlets?
<p>I transformed some of my lib variable into <code>traitlets</code> and I'm facing an error when iterating on a <code>Tuple</code> even though this is possible with built-in <code>tuple</code>.</p> <pre class="lang-py prettyprint-override"><code>from traitlets import Tuple a = Tuple((1,2,4)).tag(sync=True) for i in a: print(i) &gt;&gt;&gt; --------------------------------------------------------------------------- &gt;&gt;&gt; TypeError Traceback (most recent call last) &gt;&gt;&gt; /Users/pierrickrambaud/Documents/travail/FAO/app_buffer/sepal_ui/untitled.ipynb &gt;&gt;&gt; Cellule 14 in &lt;cell line: 1&gt;() &gt;&gt;&gt; ----&gt; 1 for i in a: &gt;&gt;&gt; 2 print(i) &gt;&gt;&gt; &gt;&gt;&gt; TypeError: 'Tuple' object is not iterable </code></pre> <p>with the normal <code>tuple</code>:</p> <pre class="lang-py prettyprint-override"><code>a = (1, 2, 3) for i in a: print(i) &gt;&gt;&gt; 1 &gt;&gt;&gt; 2 &gt;&gt;&gt; 3 </code></pre> <p>Is it a bug or is it the intended behavior ?</p>
<python><python-traitlets>
2022-12-27 16:49:59
1
2,670
Pierrick Rambaud
74,931,838
8,207,701
Can't pickle local object 'EvaluationLoop.advance.<locals>.batch_to_device' PyTorch
<p>I'm trying to train a model using PyTorch Lightning.</p> <pre><code>trainer = pl.Trainer( logger = logger, max_epochs = N_EPOCHS, ) trainer.fit(model,data_module) </code></pre> <p>But while doing that, I'm getting the following error after a sanity check progress bar.</p> <pre><code>AttributeError: Can't pickle local object 'EvaluationLoop.advance.&lt;locals&gt;.batch_to_device' </code></pre> <p>What am I doing wrong :(</p>
<python><pytorch><pytorch-lightning>
2022-12-27 16:34:25
2
1,216
Bucky
74,931,611
13,564,858
Function to find a continuous sub-array which adds up to a given number in python
<p>I want to know what's wrong in the below code. Will it consume more time to in some certain scenarios? Expected time complexity: O(n)</p> <pre><code>def subArraySum(self,arr, n, s): if sum(arr[0:n]) == s: return [1, n] if sum(arr[0:n]) &lt; s: return [-1] start = 0 i =1 sum_elements = 0 while i &lt; n: sum_elements = sum(arr[start:i+1]) if sum_elements == s: return [start+1, i+1] if sum_elements &lt; s: i += 1 continue if sum_elements &gt; s: start += 1 continue if sum_elements &lt; s: return [-1] </code></pre>
<python><data-structures>
2022-12-27 16:11:44
1
429
Lucky Ratnawat
74,931,530
1,211,082
How to efficiently use PyMongo cursor
<p>Please propose ways to access data returned from <code>collections.find()</code> in an efficient manner.</p> <p>Is a <code>for</code> iteration the recommended way? How do I keep the character of a cursor being an <code>Iterable</code>?</p> <p>Thx</p>
<python><performance><pymongo><database-cursor>
2022-12-27 16:03:32
1
6,069
Martin Senne
74,931,513
5,431,283
Pandas loop over each line of a column and append the corresponding value in a new column
<p>I have the following CSV with EC2 instances in them:</p> <pre><code>instanceID,region i-0020cad819e7393c0,DUB i-00006ea9f2460375f,DUB </code></pre> <p>I want to create a column based on the tags of those instances, for example, the name of those instances.</p> <pre class="lang-py prettyprint-override"><code>import boto3 import pandas as pd ec2 = boto3.resource('ec2') def get_instance_tags(instance): tags = {} instance_obj = ec2.Instance(instance) for tag in instance_obj.tags: if tag['Key'] == 'Name': tags['Instance Name'] = tag['Value'] if tag['Key'] == 'Description': tags['Description'] = tag['Value'] return tags </code></pre> <p>The above function returns a dictionary with tags for a given instance.</p> <p>I want to loop over each <code>Instance ID</code> in my .csv file, and append the corresponding value of a tag in a new column. For example:</p> <pre><code>instanceID,region,Name i-0020cad819e1234,DUB,Name1 i-00006ea9f241234,DUB,Nam2 </code></pre> <p>I thought something like this could work:</p> <pre class="lang-py prettyprint-override"><code>for i in df['instanceID']: tags = get_instance_tags(i) name = tags.get('Instance Name') df['Name'] = name </code></pre> <p>The above just copies the same value to all cells.</p> <p>I'm not sure which approach I should go with here. I find it difficult to Google the exact term to find the solution.</p>
<python><pandas>
2022-12-27 16:01:37
1
673
Daniel
74,931,485
5,281,811
Custom pattern matching with regular expressions and three lists
<p>i'm a newbie and i'm trying to build a custom pattern matcher with three dynamically generated lists with the same length. It's for a tool that stores three personal sensible informations, its not that important. I thought putting them into three lists would be good to do some custom pattern matching.<br> One list for the names, one for their address and one for their personal code. It's confidential so i won't display any names or personal information, instead i use string,regex and placeholder for this to be easier.<br><br> Some simple rules for the custom pattern matcher to understand my code:<br></p> <ol> <li>The strings are not unique, they can be repeated multiple times like string1 in my code, so the matcher should test each pattern with each subsequent string.<br/> 2.The pattern matching are done in all three lists, sequentially at the same time<br/><br/>3.The pattern matching is done by index, so if a pattern match a string in list1 at index 5,the next pattern cannot be matched with a string at index 3 in any list(list1,list2 or list3) for example, it should match a string at index 6 or higher<br/><br/> 4.The custom pattern matcher should match the strings in the list sequentially, in the order they are given, if the character '#' is not in the pattern list. <br/><br/> 5.'#' is a placeholder for one or more strings in a list in between indexes of the strings before and after the '#' in the pattern list.<br /><br/></li> </ol> <p>with these three lists and pattern_list as example</p> <pre><code> list1 = ['string1', 'string2', 'string1', 'string3'] list2 = ['regex1', 'regex2', 'regex1', 'regex3'] list3 = ['placeholder1', 'placeholder2', 'placeholder1', 'placeholder3'] pattern_list=['regex2', '#', 'string3'] #should print ['string2', 'string1', 'string3'] here in that case regex2=index 1(starting from zero)=list1[1]=string2, '#' matches one or more strings, here it's one string, regex1=index 2=list1[2]=string1 </code></pre> <p>If that is understood here's the code:</p> <pre><code>import re def search_pattern(list1, list2, list3, pattern_list): # Create the connections dictionary because list1 is connected to the strings in list2 and list3 connections = {} for i in range(len(list1)): connections[list1[i]] = (list2[i], list3[i]) # Convert the pattern list to a regex pattern pattern = '|'.join(pattern_list) # Initialize the result list result = [] # Iterate over the lists for lst in [list1, list2, list3]: # Iterate over the strings in the list for i, string in enumerate(lst): # Check if the string matches the regex pattern match = re.search(pattern, string) if match: # Append the corresponding string from the connections dictionary to the result list result.append(connections[string][0] if match.group() == list2 else string) # Return the result list return result list1 = ['string1', 'string2', 'string1', 'string3'] list2 = ['regex1', 'regex2', 'regex1', 'regex3'] list3 = ['placeholder1', 'placeholder2', 'placeholder1', 'placeholder3'] # Define the pattern to search for pattern_list = ['regex2', '#', 'string3'] # Search for the pattern in all lists result = search_pattern(list1, list2, list3, pattern_list) # Print the result list print(result) </code></pre> <p>The problem is that this code gives me ['string3', 'regex2'] instead of ['string2', 'string1', 'string3']. I'm stucked can anyone help me? Maybe it's not the best way to go about it, maybe i should change my code completly? I don't know i need your help</p>
<python><regex><list>
2022-12-27 15:59:06
2
373
Laz22434
74,931,418
8,665,843
Split large JSON file into smaller files
<p>I have a need to split very large json file (20GB) into multiple smaller json files (Say threshold is 100 MB).</p> <p>The Example file layout looks like this.</p> <p>file.json</p> <pre><code>[{&quot;name&quot;:&quot;Joe&quot;, &quot;Place&quot;:&quot;Denver&quot;, &quot;phone_number&quot;:[&quot;980283&quot;, &quot;980284&quot;, &quot;980285&quot;]},{&quot;name&quot;:&quot;kruger&quot;, &quot;Place&quot;:&quot;boston&quot;, &quot;phone_number&quot;:[&quot;980281&quot;, &quot;980282&quot;, &quot;980283&quot;]},{&quot;name&quot;:&quot;Dan&quot;, &quot;Place&quot;:&quot;Texas&quot;,&quot;phone_number&quot;:[&quot;980286&quot;, &quot;980287&quot;, &quot;980286&quot;]}, {&quot;name&quot;:&quot;Kyle&quot;, &quot;Place&quot;:&quot;Newyork&quot;, &quot;phone_number&quot;:[&quot;980282&quot;, &quot;980288&quot;, &quot;980289&quot;]}] </code></pre> <p>The output should look like this</p> <p>file1:</p> <pre><code>[{&quot;name&quot;:&quot;Joe&quot;, &quot;Place&quot;:&quot;Denver&quot;, &quot;phone_number&quot;:[&quot;980283&quot;, &quot;980284&quot;, &quot;980285&quot;]}, {&quot;name&quot;:&quot;kruger&quot;, &quot;Place&quot;:&quot;boston&quot;, &quot;phone_number&quot;:[&quot;980281&quot;, &quot;980282&quot;, &quot;980283&quot;]}] </code></pre> <p>file2:</p> <pre><code>[{&quot;name&quot;:&quot;Dan&quot;, &quot;Place&quot;:&quot;Texas&quot;,&quot;phone_number&quot;:[&quot;980286&quot;, &quot;980287&quot;, &quot;980286&quot;]}, {&quot;name&quot;:&quot;Kyle&quot;, &quot;Place&quot;:&quot;Newyork&quot;, &quot;phone_number&quot;:[&quot;980282&quot;, &quot;980288&quot;, &quot;980289&quot;]}] </code></pre> <p>May I know the best way to achieve this? Should i opt for shell command or python?</p>
<python><json><linux><shell>
2022-12-27 15:52:45
2
1,405
kites
74,931,396
18,308,393
Logits and labels must have same shape for Keras model
<p>I am new to Keras and have been practicing with resources from the web. Unfortunately, I cannot build a model without it throwing the following error:</p> <blockquote> <p>ValueError: <code>logits</code> and <code>labels</code> must have the same shape, received ((None, 10) vs (None, 1)).</p> </blockquote> <p>I have attempted the following:</p> <pre><code>DF = pd.read_csv(&quot;https://raw.githubusercontent.com/EpistasisLab/tpot/master/tutorials/MAGIC%20Gamma%20Telescope/MAGIC%20Gamma%20Telescope%20Data.csv&quot;) X = DF.iloc[:,0:-1] y = DF.iloc[:,-1] yBin = np.array([1 if x == 'g' else 0 for x in y ]) scaler = StandardScaler() X1 = scaler.fit_transform(X) X_train, X_test, y_train, y_test = train_test_split(X1, yBin, test_size=0.25, random_state=2018) print(X_train.__class__,X_test.__class__,y_train.__class__,y_test.__class__ ) model=Sequential() model.add(Dense(6,activation=&quot;relu&quot;, input_shape=(10,))) model.add(Dense(10,activation=&quot;softmax&quot;)) model.build(input_shape=(None,1)) model.summary() model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy']) model.fit(x=X_train, y=y_train, epochs=600, validation_data=(X_test, y_test), verbose=1 ) </code></pre> <p>I have read my model is likely wrong in terms of input parameters, what is the correct approach?</p>
<python><tensorflow><keras>
2022-12-27 15:50:55
3
367
Dollar Tune-bill
74,931,393
12,242,085
How to replace values in column in one DataFrame by values from second DataFrame both have major key in Python Pandas?
<p>I have 2 DataFrames in Python Pandas like below:</p> <p>DF1</p> <pre><code>COL1 | ... | COLn -----|------|------- A | ... | ... B | ... | ... A | ... | ... .... | ... | ... </code></pre> <p>DF2</p> <pre><code>G1 | G2 ----|----- A | 1 B | 2 C | 3 D | 4 </code></pre> <p>And I need to replace values from <code>DF1 COL1</code> by values from <code>DF2 G2</code></p> <p>So, as a result I need DF1 in formt like below:</p> <pre><code>COL1 | ... | COLn -----|------|------- 1 | ... | ... 2 | ... | ... 1 | ... | ... .... | ... | ... </code></pre> <p>Of course my table in huge and it could be good to do that automaticly not by manually adjusting the values :)</p> <p>How can I do that in Python Pandas?</p>
<python><pandas><dataframe><replace>
2022-12-27 15:50:41
2
2,350
dingaro
74,931,285
4,040,743
Python 2 Script to Python 3 in a Docker Container :: "No module named 'Queue'"
<p>I have a Python 2 script that I'm trying to run within the latest <a href="https://hub.docker.com/_/python" rel="nofollow noreferrer">Python docker container</a>. That container supports Python 3, and I thought could manually adapt the script. My manual adaptations worked just fine... except for this:</p> <p>The original Python 2 script contained this line:</p> <pre><code>from multiprocessing import Queue, Manager, Lock </code></pre> <p>But thanks to post like <a href="https://stackoverflow.com/questions/41150948/how-to-convert-from-queue-import-queue-empty-from-python-2-to-python-3">this</a> and <a href="https://stackoverflow.com/questions/46363871/no-module-named-queue">this</a>, I know that &quot;Queue&quot; isn't a Python 3 module; the module I need is &quot;queue&quot;. So I changed my code to this:</p> <pre><code>import queue from multiprocessing import Manager, Lock </code></pre> <p>When I spin up my container then run the script (within the container), I get this:</p> <pre><code>Traceback (most recent call last): File &quot;/usr/local/bin/myscript&quot;, line 4, in &lt;module&gt; __import__('pkg_resources').run_script('myscript==0.1.0', 'myscript') File &quot;/usr/local/lib/python3.9/site-packages/pkg_resources/__init__.py&quot;, line 651, in run_script self.require(requires)[0].run_script(script_name, ns) File &quot;/usr/local/lib/python3.9/site-packages/pkg_resources/__init__.py&quot;, line 1455, in run_script exec(script_code, namespace, namespace) File &quot;/usr/local/lib/python3.9/site-packages/myscript-0.1.0-py3.9.egg/EGG-INFO/scripts/myscript&quot;, line 21, in &lt;module&gt; File &quot;&lt;frozen zipimport&gt;&quot;, line 259, in load_module File &quot;/usr/local/lib/python3.9/site-packages/myscript-0.1.0-py3.9.egg/openbmp/myscript/logger.py&quot;, line 15, in &lt;module&gt; ModuleNotFoundError: No module named 'Queue' </code></pre> <p>The above makes little sense to me; here's the referenced part of the script, with line numbers included:</p> <pre><code>15 import sys 16 import signal 17 #from multiprocessing import queue, Manager, Lock 18 import queue 19 from multiprocessing import Manager, Lock 20 21 from myscript.logger import LoggerThread </code></pre> <p>Ugh. The Docker container is adding as extra layer of complexity and I don't understand what's going on.</p> <p>More experienced programmers: Is there a suitable fix here? Or should I just give up and use the Python 2 Docker container? Thank you.</p>
<python><docker><module><version>
2022-12-27 15:39:51
1
1,599
Pete
74,931,219
16,389,095
How to load .mat file properly
<p>I'm trying to load a .mat file with this the code:</p> <pre><code>from scipy.io import loadmat matFile = loadmat('myFile.mat') print(matFile) </code></pre> <p><a href="https://i.sstatic.net/AMIsX.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/AMIsX.png" alt="enter image description here" /></a></p> <p>But when I try to access to data with</p> <pre><code>matVar = matFile['Walking'] </code></pre> <p>I get an array of void320 (1,1). How can I read properly the data? How can I access to all the subsets / variables inside the file?</p>
<python><matlab><scipy>
2022-12-27 15:33:23
0
421
eljamba
74,931,215
2,561,452
Imported module can not find input file that exists in same directory as the Python script?
<p>I have a Python program that uses the OpenAI Whisper module to transcribe audio to text. Unfortunately, despite passing a fully resolved path to that module, it crashes with an error saying it can't find the file. I know the file exists in the directory because as you can see from my code and output below, the script itself can find it (look at the code and output where I print the input file's timestamp). I am running on a Windows 10 PC.</p> <p>Why can't the imported module find the input file and how can I fix this problem? I read several posts on SO regarding paths and the <code>subprocess</code> module, but none of the solutions worked for me.</p> <p>Here is the code:</p> <pre class="lang-py prettyprint-override"><code>import whisper import pandas as pd import os import sys from datetime import datetime # Show the current working directory cwd = os.getcwd() print (&quot;Current working directory: {0}\n&quot;.format(cwd)) # Transcript a previously downloaded audio file. # audio_file = &quot;./audio.mp4&quot; # with open(os.path.join(sys.path[0], &quot;audio.mp4&quot;), &quot;r&quot;) as f: audio_file = os.path.join(cwd, &quot;audio.mp4&quot;) print (&quot;Using audio input file: {0}\n&quot;.format(audio_file)) # Get the timestamp for the file timestamp = os.path.getmtime(audio_file) # Convert the timestamp to a datetime object dt = datetime.fromtimestamp(timestamp) # Format the datetime object in the desired format formatted_timestamp = dt.strftime(&quot;%m/%d/%Y&quot;) # Print the formatted timestamp print(&quot;Input file timestamp: {0}\n\n&quot;.format(formatted_timestamp)) #Load the OpenAI Whisper model whisper_model = whisper.load_model(&quot;tiny&quot;) # Transcribe the audio. transcription = whisper_model.transcribe(audio_file) # Display the transcription. This will display # the transcription result in segments with # start and end time. The full concatenated # string is available as transcription['text'] # print as DataFrame df = pd.DataFrame(transcription['segments'], columns=['start', 'end', 'text']) print(df) # or, print as String print(transcription['text']) </code></pre> <p>Here is the program output:</p> <pre><code>C:\Users\main\Documents\GitHub\ME\open-ai\whisper\python-utilities&gt;python transcribe-audio.py Current working directory: C:\Users\main\Documents\GitHub\ME\open-ai\whisper\python-utilities Using audio input file: C:\Users\main\Documents\GitHub\ME\open-ai\whisper\python-utilities\audio.mp4 Input file timestamp: 12/27/2022 C:\Python310\lib\site-packages\whisper\transcribe.py:78: UserWarning: FP16 is not supported on CPU; using FP32 instead warnings.warn(&quot;FP16 is not supported on CPU; using FP32 instead&quot;) Traceback (most recent call last): File &quot;C:\Users\main\Documents\GitHub\ME\open-ai\whisper\python-utilities\transcribe-audio.py&quot;, line 36, in &lt;module&gt; transcription = whisper_model.transcribe(audio_file) File &quot;C:\Python310\lib\site-packages\whisper\transcribe.py&quot;, line 84, in transcribe mel = log_mel_spectrogram(audio) File &quot;C:\Python310\lib\site-packages\whisper\audio.py&quot;, line 111, in log_mel_spectrogram audio = load_audio(audio) File &quot;C:\Python310\lib\site-packages\whisper\audio.py&quot;, line 42, in load_audio ffmpeg.input(file, threads=0) File &quot;C:\Python310\lib\site-packages\ffmpeg\_run.py&quot;, line 313, in run process = run_async( File &quot;C:\Python310\lib\site-packages\ffmpeg\_run.py&quot;, line 284, in run_async return subprocess.Popen( File &quot;C:\Python310\lib\subprocess.py&quot;, line 966, in __init__ self._execute_child(args, executable, preexec_fn, close_fds, File &quot;C:\Python310\lib\subprocess.py&quot;, line 1435, in _execute_child hp, ht, pid, tid = _winapi.CreateProcess(executable, args, FileNotFoundError: [WinError 2] The system cannot find the file specified </code></pre>
<python><path><subprocess><createprocess>
2022-12-27 15:32:54
1
14,395
Robert Oschler
74,931,209
12,349,101
Getting Nth permutation of a sequence and getting back original using its index and modified sequence
<p>I know the most popular permutation algorithms (thanks to wonderful question/answer on SO, and other related sites, such as Wikipedia, etc), but I recently wanted to see if I could get the Nth permutation without exhausting the whole permutation space.</p> <p>Factorial comes to mind, so I ended up looking at posts such as <a href="https://codegolf.stackexchange.com/questions/114883/i-give-you-nth-permutation-you-give-me-n/115024#115024%5D">this one that implements the unrank and rank algorithm</a>, as well as <a href="https://stackoverflow.com/questions/6884708/ranking-and-unranking-of-permutations-with-duplicates">many</a>, <a href="https://rosettacode.org/wiki/Permutations/Rank_of_a_permutation" rel="nofollow noreferrer">many</a> other ones. (Here as mentioned, I take into account other sites as &quot;post&quot;)</p> <p>I stumbled upon <a href="https://code.activestate.com/recipes/126037-getting-nth-permutation-of-a-sequence/" rel="nofollow noreferrer">this ActiveState recipe</a> which seems like it fit what I wanted to do, but it doesn't support doing the reverse (using the result of the function and reusing the index to get back the original sequence/order).</p> <p>I also found a similar and related answer on SO: <a href="https://stackoverflow.com/a/38166666/12349101">https://stackoverflow.com/a/38166666/12349101</a></p> <p>But the same problem as above.</p> <p>I tried and made different versions of the unrank/rank implementation(s) above, but they require that the sorted sequence be passed as well as the index given by the rank function. If a random (even within the range of the total permutation count) is given, it won't work (most of the time I tried at least).</p> <p>I don't know how to implement this and I don't think I saw anyone on SO doing this yet. Is there any existing algorithm or way to do this/approach this?</p> <p><em>To make things clearer</em>:</p> <p>Here is the Activestate recipe I posted above (at least the one posted in the comment):</p> <pre><code>from functools import reduce def NPerms (seq): &quot;computes the factorial of the length of &quot; return reduce(lambda x, y: x * y, range (1, len (seq) + 1), 1) def PermN (seq, index): &quot;Returns the th permutation of (in proper order)&quot; seqc = list (seq [:]) result = [] fact = NPerms (seq) index %= fact while seqc: fact = fact // len (seqc) choice, index = index // fact, index % fact result += [seqc.pop (choice)] return result </code></pre> <p>As mentioned, this handles doing part of what I mentioned in the title, but I don't know how to get back the original sequence/order using both the result of that function + the same index used.</p> <p>Say I use the above on a string such as <code>hello world</code> inside a list:</p> <pre><code>print(PermN(list(&quot;hello world&quot;), 20)) </code></pre> <p>This output: <code>['h', 'e', 'l', 'l', 'o', ' ', 'w', 'd', 'r', 'o', 'l']</code> Now to see if this can go back to the original using the same index + result of the above:</p> <pre><code>print(PermN(['h', 'e', 'l', 'l', 'o', ' ', 'w', 'd', 'r', 'o', 'l'], 20)) </code></pre> <p>Output: <code>['h', 'e', 'l', 'l', 'o', ' ', 'w', 'l', 'r', 'd', 'o']</code></p>
<python><algorithm><permutation>
2022-12-27 15:32:23
1
553
secemp9
74,931,165
5,982,721
RTSP connection issue on IP Camera
<p>I have flir blackfly s bfs-pge-04s2c-cs model ip camera. I have poe injector that is connected to router and to camera. I can find the camera ip. My problem is I cannot connect with rtsp.</p> <p>with EasyPySpin I can get a frame with the code below.</p> <pre><code>import cv2 import EasyPySpin cap = EasyPySpin.VideoCapture(0) print(cap.get(0)) for i in range(100): ret, frame = cap.read() cv2.imwrite(&quot;frame.png&quot;, frame) cap.release() </code></pre> <p>I need rtsp connection for my other processes the ip is shown with the matched mac adress in my system. I tried like that</p> <pre><code>import cv2 import os RTSP_URL = 'rtsp://192.168.1.240' os.environ['OPENCV_FFMPEG_CAPTURE_OPTIONS'] = 'rtsp_transport;udp' cap = cv2.VideoCapture(RTSP_URL, cv2.CAP_FFMPEG) if not cap.isOpened(): print('Cannot open RTSP stream') exit(-1) while True: _, frame = cap.read() print('hehe') cv2.imshow('RTSP stream', frame) if cv2.waitKey(1) == 27: break cap.release() cv2.destroyAllWindows() </code></pre> <p>I cannot make a connection with this code.</p>
<python><connection><rtsp><ip-camera>
2022-12-27 15:27:44
2
487
nogabemist
74,931,079
7,333,766
Can I safely remove from __future__ import absolute_import in python 3 files?
<p>I am working on a project that used to use python 2, but does not anymore.</p> <p>I see many lines of code like these :</p> <pre><code>from __future__ import absolute_import </code></pre> <p><strong>Can I safely remove them all ?</strong></p> <p>From what I read, it seems it was only used in python 2 to mimic Python 3 behavior</p> <p>CF linked question : <a href="https://stackoverflow.com/questions/33743880/what-does-from-future-import-absolute-import-actually-do">What does from __future__ import absolute_import actually do?</a></p> <p>As well <a href="https://www.twobraids.com/2020/01/from-future-import-absoluteimport.html" rel="nofollow noreferrer">this source</a> :</p> <blockquote> <p>Using the absolute_import line in Python 2 changes the search strategy to mimic the Python 3 search strategy</p> </blockquote>
<python><python-3.x>
2022-12-27 15:18:42
1
2,215
Eli O.
74,931,053
7,058,363
How to make Plotly Pie charts the same size always
<p>I'm generating different Pie charts that have legends of different lengths. The problem is that when the legend is long, the Pie chart is smaller, I'd like to make the Pie chart always the same size.</p> <p>This is my code:</p> <pre class="lang-py prettyprint-override"><code>pie_chart = go.Pie(labels=labels, values=y) fig = go.Figure(data=[pie_chart]) fig.update_layout(legend={'font': {'size': 17}}) io_bytes = fig.to_image(format=&quot;png&quot;, scale=2.5, width=900, height=500) </code></pre> <p>These are the results:</p> <p><strong>Big pie chart, short legend:</strong></p> <p><a href="https://i.sstatic.net/E1mqf.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/E1mqf.png" alt="Big Pie chart" /></a></p> <p><strong>Small pie chart, long legend:</strong></p> <p><a href="https://i.sstatic.net/34pH9.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/34pH9.png" alt="enter image description here" /></a></p>
<python><charts><plotly>
2022-12-27 15:15:50
2
3,493
Genarito
74,930,978
7,805,917
Pyspark add columns to existing dataframe
<p>I have the following code to do the implementation of having multiple condition columns in a single dataframe.</p> <pre class="lang-py prettyprint-override"><code>small_list = [&quot;INFY&quot;,&quot;TCS&quot;, &quot;SBIN&quot;, &quot;ICICIBANK&quot;] frame = spark_frame.where(col(&quot;symbol&quot;) == small_list[0]).select('close') ## spark frame is a pyspark.sql.dataframe.DataFrame for single_stock in small_list[1:]: print(single_stock) current_stock = spark_frame.where(col(&quot;symbol&quot;) == single_stock).select(['close']) current_stock.collect() frame.collect() frame = frame.withColumn(single_stock, current_stock.close) </code></pre> <p>But when I do <code>frame.collect</code>, I get:</p> <pre><code>[Row(close=736.85, TCS=736.85, SBIN=736.85, ICICIBANK=736.85), Row(close=734.7, TCS=734.7, SBIN=734.7, ICICIBANK=734.7), Row(close=746.0, TCS=746.0, SBIN=746.0, ICICIBANK=746.0), Row(close=738.85, TCS=738.85, SBIN=738.85, ICICIBANK=738.85)] </code></pre> <p>Which is wrong since all the values belong to the first reference. What am I doing wrong, and what is the best way to solve this one?</p> <p>Edit: The spark_frame looks like this</p> <pre><code>[Row(SYMBOL='LINC', SERIES=' EQ', TIMESTAMP=datetime.datetime(2021, 12, 20, 0, 0), PREVCLOSE=235.6, OPEN=233.95, HIGH=234.0, LOW=222.15, LAST=222.15, CLOSE=224.2, AVG_PRICE=226.63, TOTTRDQTY=6447, TOTTRDVAL=14.61, TOTALTRADES=206, DELIVQTY=5507, DELIVPER=85.42), Row(SYMBOL='LINC', SERIES=' EQ', TIMESTAMP=datetime.datetime(2021, 12, 21, 0, 0), PREVCLOSE=224.2, OPEN=243.85, HIGH=243.85, LOW=222.85, LAST=226.0, CLOSE=225.6, AVG_PRICE=227.0, TOTTRDQTY=8447, TOTTRDVAL=19.17, TOTALTRADES=266, DELIVQTY=3401, DELIVPER=40.26), Row(SYMBOL='SCHAEFFLER', SERIES=' EQ', TIMESTAMP=datetime.datetime(2020, 8, 6, 0, 0), PREVCLOSE=3593.9, OPEN=3611.85, HIGH=3618.35, LOW=3542.5, LAST=3594.95, CLOSE=3573.1, AVG_PRICE=3580.73, TOTTRDQTY=12851, TOTTRDVAL=460.16, TOTALTRADES=1886, DELIVQTY=9649, DELIVPER=75.08), Row(SYMBOL='SCHAEFFLER', SERIES=' EQ', TIMESTAMP=datetime.datetime(2020, 8, 7, 0, 0), PREVCLOSE=3573.1, OPEN=3591.0, HIGH=3591.0, LOW=3520.0, LAST=3548.95, CLOSE=3543.85, AVG_PRICE=3554.6, TOTTRDQTY=2406, TOTTRDVAL=85.52, TOTALTRADES=688, DELIVQTY=1452, DELIVPER=60.35)] </code></pre> <p>Expected results should look like this:</p> <pre><code>[Row(LINC=224.2, SCHAEFFLER=3573.1, Row(LINC=225.6, SCHAEFFLER=3543.85)] </code></pre>
<python><pyspark><apache-spark-sql>
2022-12-27 15:07:41
2
3,836
Inder
74,930,970
39,939
In python flask with mysql, can I use the same connection throught the app life cycle?
<p>Here is my python flask code:</p> <pre><code>from flask import * import mysql.connector app = Flask(__name__) conn = mysql.connector.connect( host=&quot;&lt;my db host&gt;&quot;, user=&quot;&lt;my db user&gt;&quot;, password = &quot;&lt;my db password&gt;&quot;, database = '&lt;my db&gt;' ) @app.route('/posts/&lt;int:post_id&gt;') def get_post(post_id): with conn.cursor(dictionary=True) as cur: cur.execute('select * from posts where ID=%s',(post_id,)) result = cur.fetchone() ans=result['post_content'] return ans app.run(debug=False,threaded=True,host='0.0.0.0',port=80) </code></pre> <p>Note how I don't create a new connection for each request. Instead, I use the same connection for all requests.</p> <p>My question is: is there any potential problems in this approach?</p>
<python><flask><mysql-python><mysql-connector>
2022-12-27 15:07:00
1
4,915
yigal
74,930,955
11,956,484
Piviot dataframe with duplicate indexes without applying aggfunction
<p>I have data that is in long form. It looks like this</p> <pre><code>Analysis Mode SID Run ID Accession ID Analyte Concentration QC - 111522 QC L Be 0.01 QC - 111522 QC M Be 0.04 SAMPLE EM123 111522 E2214172001 Be 1.20 SAMPLE EM124 111522 E2214172002 Be 1.40 ............ QC - 111522 QC L Be 0.02 QC - 111522 QC M Be 0.05 ............ QC - 111522 QC L V 0.1 QC - 111522 QC M V 0.2 SAMPLE EM123 111522 E2214172001 V 1.0 SAMPLE EM124 111522 E2214172002 V 1.3 ............ QC - 111522 QC L V 0.1 QC - 111522 QC M V 0.3 </code></pre> <p>In total the df is size <code>(12879,8)</code>. There are <code>23</code> different analytes. I want to pivot the data so that the <strong>analytes are <code>columns</code> and the values are <code>concentration</code></strong></p> <pre><code>columns= [Analysis Mode , SID , Run ID ,Accession ID, Be, V] </code></pre> <p>This issue is there are duplicate IDs- In the example above QC L was analyzed for Be in run 111522 twice. I need to retain these numbers exactly meaning I do not want to average or do anything to them. It needs to be its own row</p> <p>The output df I want would look something like this</p> <pre><code> Analysis Mode SID Run ID Accession ID Be V QC - 111522 QC L 0.01 0.1 QC - 111522 QC M 0.04 0.2 SAMPLE EM123 111522 E2214172001 1.20 1.0 SAMPLE EM124 111522 E2214172002 1.40 1.3 ............ QC - 111522 QC L 0.02 0.1 QC - 111522 QC M 0.05 0.3 </code></pre> <p>I tried using pivot and piviot table but I keep getting duplicate index errors. I also trying using groupby and cumsum but it also gives me duplicate index errors</p>
<python><pandas>
2022-12-27 15:05:50
1
716
Gingerhaze
74,930,934
11,795,918
Frappe save objects in another doctype based on the base doctype?
<p>I am tring to trigger an event to save doctype data based on another doctype.</p> <p>This is how my doctype are:</p> <ol> <li>Employee has a Job Role.</li> <li>Job Role has tow doctypes as Table 'Job Role Course Item' and 'Job Role Skill Item'.</li> <li>'Job Role Course Item' is a Table type linked with 'Course Template'.</li> <li>'Job Role Skill Item' ia a Table type linked with 'Skill'.</li> </ol> <p>What I want to achiave is this:</p> <ol> <li>When use saves data into db usign Frappe in the Employee DocType I want to save the data also into another two DocTypes 'Course Assignment' and 'Employee Skill'.</li> <li>This will achive by using the Job Role that is linked with the Employee DocType as Table field.</li> <li>Also I have another issue is that when I save the DocType for the first time it tells me that DocType doesn't exsists.</li> </ol> <h1>Please Note:</h1> <p>My code is working and what I need is to replace the inner for to search just for the Courses or Skills in the 'Job Role', 'Course Assignmant' or 'Employee Skill' that is not prsented in the 'Course Assignmant' and 'Employee Skill' based on name and employee.</p> <p>This is my whole code for the Employee DocType.</p> <pre><code>import frappe from frappe import _ from frappe.model.document import Document class Employee(Document): def before_save(self): if not self.full_name: self.full_name = ((self.first_name + ' ' if self.first_name else '') + (self.middle_name + ' ' if self.middle_name else '') + (self.last_name if self.last_name else '')).strip() if self._doc_before_save: if self._doc_before_save.job_roles != self.job_roles: self.trigger_job_roles() # DocType dosn't exsists if the DocType of saved as first time. else: self.trigger_job_roles() def validate(self): if (self.work_start_date and self.work_end_date): if (self.work_start_date &gt;= self.work_end_date): frappe.throw(_('The Work End Date should be greater than the Work Start Date')) def trigger_job_roles(self): frappe.enqueue( &quot;medad_tms.trainee_management.doctype.employee.employee.assign_employee&quot;, doc=self, ) def assign_employee(doc): try: for job_role in doc.job_roles: for course in frappe.get_doc(&quot;Job Role&quot;, job_role.job_role).required_courses: # I want to replace this to enhance the code performace. if not frappe.db.exists(&quot;Course Assignment&quot;, f&quot;{course.course}-{doc.related_user}&quot;): course_doc = frappe.new_doc(&quot;Course Assignment&quot;) course_doc.trainee = doc.related_user course_doc.course = course.course course_doc.source = &quot;Job Role&quot; course_doc.due_date = frappe.get_doc(&quot;Course Template&quot;, course.course).start_date course_doc.insert() for skill in frappe.get_doc(&quot;Job Role&quot;, job_role.job_role).required_skills: # I want to replace this to enhance the code performace. if not frappe.db.exists(&quot;Employee Skill&quot;, f&quot;{doc.name}-{skill.skill}&quot;): skill_doc = frappe.new_doc(&quot;Employee Skill&quot;) skill_doc.employee = doc.name skill_doc.skill = skill.skill skill_doc.skill_type = &quot;Training Programs&quot; skill_doc.proficiency_scale_level = 1 skill_doc.required_scale_level = 5 skill_doc.insert() frappe.db.commit() frappe.publish_realtime( &quot;assign_employee&quot;, {&quot;progress&quot;: 1, &quot;total&quot;: 3, &quot;message&quot;: &quot;Assigning Courses and Skills to Employee&quot;}, user=frappe.session.user, after_commit=True, ) except Exception: frappe.db.rollback() frappe.log_error(frappe.get_traceback(), &quot;Employee&quot;) frappe.throw(_(&quot;Error in Assigning Courses and Skills to Employee&quot;)) </code></pre>
<python><postgresql><query-builder><frappe>
2022-12-27 15:04:06
1
1,567
Dhia Shalabi
74,930,922
9,957,710
How to load a custom Julia package in Python using Python's juliacall
<p>I already know <a href="https://stackoverflow.com/questions/73070845/how-to-import-julia-packages-into-python">How to import Julia packages into Python</a>.</p> <p>However, now I have created my own simple Julia package with the following command: <code>using Pkg;Pkg.generate(&quot;MyPack&quot;);Pkg.activate(&quot;MyPack&quot;);Pkg.add(&quot;StatsBase&quot;)</code> where the file <code>MyPack/src/MyPack.jl</code> has the following contents:</p> <pre><code>module MyPack using StatsBase function f1(x, y) return 3x + y end g(x) = StatsBase.std(x) export f1 end </code></pre> <p>Now I would like to load this Julia package in Python via <code>juliacall</code> and call <code>f1</code> and <code>g</code> functions. I have already run <code>pip3 install juliacall</code> from command line. How do I call the above functions from Python?</p>
<python><julia>
2022-12-27 15:03:17
1
42,537
Przemyslaw Szufel
74,930,795
5,172,570
Is it possible to iteratively build up legend entries through multiple plot function calls?
<p>Based on the question and answer here (<a href="https://stackoverflow.com/questions/40736920/line-plus-shaded-region-for-error-band-in-matplotlibs-legend;">Line plus shaded region for error band in matplotlib&#39;s legend</a> and similar to <a href="https://stackoverflow.com/questions/26217687/combined-legend-entry-for-plot-and-fill-between">Combined legend entry for plot and fill_between</a>) I was able to create a legend entry which combines a line and patch elements.</p> <p>In my use-case I need to plot multiple of these. When I do, I only get a legend entry for the last line+patch combination.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import matplotlib.pyplot as plt def plot(x, y, ax, col, group, **kwargs): hline, = ax.plot(x, y, 'k--', color=col) hpatch = ax.fill_between(x, y+10, y-10, color=col, alpha=0.5) ax.legend([(hline, hpatch)], [f&quot;group {group}: Mean + interval&quot;]) fig, ax = plt.subplots() x = np.linspace(1, 100, 100) plot(x, x, ax, &quot;C0&quot;, 1) plot(x, x+30, ax, &quot;C1&quot;, 2) plot(x, x+60, ax, &quot;C2&quot;, 3) </code></pre> <p><a href="https://i.sstatic.net/lyRSZ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/lyRSZ.png" alt="enter image description here" /></a></p> <p>Note the presence of only the final (group 3) entry in the legend.</p> <p>Is there a way to get all line/path groups included in the legend so that (in this case) there are 3 items in the legend?</p> <p>Bonus points if this can be handled entirely within the <code>plot</code> function, avoiding having to pass out handles from the plot function.</p> <p>This question is not asking about multiple separate legends.</p>
<python><matplotlib><legend>
2022-12-27 14:52:38
3
381
Ben Vincent
74,930,743
14,676,485
How to extract array's element from column of arrays?
<p>I have a dataframe where one of the columns consist of arrays. I need to extract first element from each array in this column. So, for the first row it would be 'classical harp', for 2nd - 'classic persian pop' etc. Here is an example:</p> <p><a href="https://i.sstatic.net/qf5qz.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/qf5qz.png" alt="enter image description here" /></a></p> <p>And my code below. I tried using lambda along with <code>apply</code> or <code>assign</code> but it doesn't work - I mean I can't take first element of each array in a column:</p> <pre><code>df = df.assign(top_genre = lambda x: x['genres'][0]) df['new'] = df['genres'].apply(lambda x: x[0]) </code></pre> <p>How to amend my code to make it work properly?</p>
<python><pandas>
2022-12-27 14:47:19
1
911
mustafa00
74,930,597
597,858
how do I breakdown a string in multiple components
<p>I have a string 'ABCAPITAL23JAN140CE'. This is the symbol for an option traded on stock exchange. ABCAPITAL part of the string is the company name. 23 is year 2023. JAN is for month. 140 is the strike price and CE is the type of the option.</p> <p>All these components can vary for different options.</p> <p>I need a function such that <strong>pieces_of_string = splitstring('ABCAPITAL23JAN140CE')</strong></p> <p>where <strong>pieces_of_string = ['ABCAPITAL', 23, 'JAN', 140, 'CE']</strong> is returned</p> <p>how do I do that?</p>
<python><string>
2022-12-27 14:33:25
4
10,020
KawaiKx
74,930,552
13,038,144
Matplotlib groupby scatter colormap Warning: " No data for colormapping provided via 'c' "
<p>I'm having issues with colormapping of simple scatter plots when created using pandas <code>groupby</code>.</p> <h3>Example</h3> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame(data= {'class': ['A']*5 + ['B']*5, 'index': [i for i in range(10)], 'data': [i for i in range(5)] + [i+1 for i in range(5)]}) # Plotting fig, ax = plt.subplots() for key, grp in df.groupby('class'): grp.plot.scatter(ax=ax, x='index', y='data', label=key) </code></pre> <h3>The Warning I get</h3> <blockquote> <p>/opt/miniconda3/lib/python3.8/site-packages/pandas/plotting/_matplotlib/core.py:1114: UserWarning: No data for colormapping provided via 'c'. Parameters 'cmap' will be ignored scatter = ax.scatter(</p> </blockquote> <h3>The Output plot</h3> <p>The scatter plot is produced, but matplotlib uses the same color for both classes.</p> <p><a href="https://i.sstatic.net/BqCUO.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/BqCUO.png" alt="enter image description here" /></a></p> <p>If I use <code>df.plot()</code> instead of <code>df.plot.scatter()</code> the warning is not printed, and the plot shows as expected, with different colors for the two classes. So it seems to be an issue with <code>scatter</code>. What am I doing wrong?</p> <h3>Package versions:</h3> <pre><code>pandas: 1.4.3 matplotlib: 3.6.2 </code></pre>
<python><pandas><matplotlib><plot><scatter-plot>
2022-12-27 14:28:54
1
458
gioarma
74,930,492
1,492,613
is there a way to determine udisks default mount path?
<p>It can be <code>/media/</code> or <code>/media/$USER</code> or <code>/run/media/$USER</code> depends on distro or customization. Is there a unified way to get its value programmatically regardless distros?</p>
<python><bash><udisks>
2022-12-27 14:24:12
1
8,402
Wang
74,930,487
16,690,173
Difference in cv2.imshow window size with and without waitkey commented out
<p>I'm trying to use <code>cv2.imshow</code> to display a specific section of my screen.</p> <p>However, while running, I noticed the displayed window is smaller than expected. I've stepped through the code with the debugger and noticed that when <code>cv2.waitKey(1)</code> triggers the <code>cv2.imshow</code> window resizes itself and I'm not sure why.</p> <p>If I comment out <code>cv2.waitKey(1)</code> the display window remains the expected size, <a href="https://docs.opencv.org/4.x/d7/dfc/group__highgui.html#ga5628525ad33f52eab17feebcfba38bd7" rel="nofollow noreferrer">the documentation</a> that would suggest <code>cv2.waitKey</code> does anything other than wait for a specified amount of time 0 = infinite, x = time in milliseconds.</p> <p><strong>Why is <code>waitKey</code> resizing <code>cv2.imshow</code> and how do I fix this?</strong></p> <pre><code>import cv2 as cv import numpy as np from mss import mss sct = mss() def screenshot(top, left, width, height): monitor = {'top': top, 'left': left, 'width': width, 'height': height} haystack = np.array(sct.grab(monitor)) cv.imshow(&quot;Objects&quot;, haystack) cv.moveWindow(&quot;Objects&quot;,5000,50) cv.setWindowProperty('Objects', cv.WND_PROP_TOPMOST, 1) cv.waitKey(1) return haystack top = 350 left = 1000 width = 500 height = 800 while True: screenshot(top, left, width, height) </code></pre> <p>With <code>cv.waitKey(1)</code> commented out:</p> <p><a href="https://i.sstatic.net/eYYx9.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/eYYx9.png" alt="enter image description here" /></a></p> <p>and with <code>cv.waitKey(1)</code> not commented out:</p> <p><a href="https://i.sstatic.net/LTd6f.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/LTd6f.png" alt="enter image description here" /></a></p> <p>Contents of <code>haystack</code> saved to file using <code>cv2.imwrite</code>:</p> <p><a href="https://i.sstatic.net/VaXms.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/VaXms.png" alt="enter image description here" /></a></p>
<python><opencv>
2022-12-27 14:23:50
0
303
mak47
74,930,366
4,796,942
Conditionally format cells in a google sheet using pygsheets
<p>I am trying to learn how to conditionally format cells in a worksheet using pygsheets. The reason for this is to only allow the end user interacting with a google sheet to only be able to input values that are in the correct format.</p> <p>For example, how can we format the sheet so that:</p> <ul> <li>cells A2 to A5 to be numbers between 0 and 50.</li> <li>cells B2 to B5 to be an email address (a string say having @gmail.com or @yahoo.com).</li> <li>cells C2 to C5 to be some string corresponding to a date.</li> </ul> <p>If the cell does not meet the correct format the colour can change to a slight red to signify that it is not the correct format.</p> <p>Using the two <a href="https://readthedocs.org/projects/pygsheets/downloads/pdf/stable/" rel="nofollow noreferrer">documentation for pygsheets</a> I was able to create the sheet and start with formatting for the headers. I was however unable to use a conditional statement to change the colour as need be, I think I am supposed to use the <code>set_data_validation</code> function to do this but I could not get it to work. The documentation referred me to <a href="https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/other#conditiontype" rel="nofollow noreferrer">google sheets API spreadsheets conditional page</a> but I could not understand this documentation well enough to do set up these conditions.</p> <p>I have added my example and solution for the first point which did not do what I thought it should.</p> <p><strong>Working example</strong></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>number int</th> <th>string</th> <th>date</th> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> </tr> </tbody> </table> </div> <pre><code>import pygsheets import pandas as pd # get credentials from the json file service = pygsheets.authorize(service_file='key.json') spread_sheet_id = &quot;.... insert id here ....&quot; # id to get example worksheet spreadsheet = pygsheets.Spreadsheet(client=service,id=spread_sheet_id) # open work sheet worksheet = spreadsheet.worksheet(0) header_list = [&quot;number int&quot;,&quot;string&quot;,&quot;date&quot;] for index, element in enumerate(header_list): # get the cell A1,B1 and C1 and set elements to header_list elements header_cell = wksheet.cell( str(chr(65+index)+&quot;1&quot;)) header_cell.value = element # format colour and make bold header_cell.text_format['bold'] = True # make the header bold header_cell.color = (0.9529412, 0.9529412, 0.9529412, 0) # set background color of this cell as a tuple (red, green, blue, alpha) # update header_cell.update() # format A2 to A5 to be an integer between 0 and 53 (DIDN'T WORK) for index in [&quot;A2&quot;,&quot;A3&quot;,&quot;A4&quot;,&quot;A5&quot;]: model_cell = pygsheets.Cell(index) print(index) model_cell.set_number_format(format_type = pygsheets.FormatType.NUMBER, pattern = &quot;^(?:[1-9]|[1-4][0-9]|5[0-3])$&quot;) # This pattern will match any integer between 0 and 53, inclusive header_cell.update() # (TRY OTHER WAY as a number between 0 and 53) (DIDN'T WORK) cells = worksheet.range('B2:B5') # select the cells to be formatted # create the data validation rule # rule = pygsheets.data_validation.RangeRule(minimum=0, maximum=53) # model_cell = pygsheets.Cell(&quot;A1&quot;) # model_cell.set_number_format(format_type = pygsheets.FormatType.NUMBER,pattern = &quot;0&quot;) # worksheet.add_conditional_formatting('C2', 'C6', 'NUMBER_BETWEEN', {'backgroundColor':{'red':1}}, ['0','53']) # ... format B2 to B5 to be a string less than 30 characters # ... format C2 to C5 to be a string that is a relevent email address less than 50 characters </code></pre> <p>From the google sheets API documentation, I think that each rule can be set up as:</p> <pre><code>|# create pygsheets conditional formatting rule using # https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/other#conditiontype rule = { &quot;type&quot;: enum (NUMBER_BETWEEN), &quot;values&quot;: [ { object (ConditionValue) } ] } </code></pre>
<python><google-sheets><formatting><gspread><pygsheets>
2022-12-27 14:12:12
1
1,587
user4933
74,930,335
2,301,970
Adjust matplotlib RadioButtons font size
<p>I wonder if anyone has an advice on how to adjust the font size on the <code>RadiouButtons</code> side text. Taking the <a href="https://matplotlib.org/stable/gallery/widgets/radio_buttons.html" rel="nofollow noreferrer">widget example</a> from matplotlib</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import RadioButtons t = np.arange(0.0, 2.0, 0.01) s0 = np.sin(2*np.pi*t) s1 = np.sin(4*np.pi*t) s2 = np.sin(8*np.pi*t) fig, ax = plt.subplots() l, = ax.plot(t, s0, lw=2, color='red') fig.subplots_adjust(left=0.3) axcolor = 'lightgoldenrodyellow' rax = fig.add_axes([0.05, 0.7, 0.15, 0.15], facecolor=axcolor) radio = RadioButtons(rax, ('2 Hz', '4 Hz', '8 Hz')) def hzfunc(label): hzdict = {'2 Hz': s0, '4 Hz': s1, '8 Hz': s2} ydata = hzdict[label] l.set_ydata(ydata) plt.draw() radio.on_clicked(hzfunc) rax = fig.add_axes([0.05, 0.4, 0.15, 0.15], facecolor=axcolor) radio2 = RadioButtons(rax, ('red', 'blue', 'green')) def colorfunc(label): l.set_color(label) plt.draw() radio2.on_clicked(colorfunc) rax = fig.add_axes([0.05, 0.1, 0.15, 0.15], facecolor=axcolor) radio3 = RadioButtons(rax, ('-', '--', '-.', ':')) def stylefunc(label): l.set_linestyle(label) plt.draw() radio3.on_clicked(stylefunc) plt.show() </code></pre> <p><a href="https://i.sstatic.net/uuy6i.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/uuy6i.png" alt="enter image description here" /></a></p> <p>How could I make &quot;2Hz, 4Hz, 8Hz&quot; larger?</p> <p>It is possible to adjust the buttons size by accessing the <code>Circle</code> objects on the <code>RadioButtons</code>. Is there something similar to the font size? (the <a href="https://matplotlib.org/stable/gallery/widgets/buttons.html" rel="nofollow noreferrer">buttons</a> widget have the <code>.label.set_fontsize()</code> attribute but I have not found a similar thing for this widget)</p>
<python><matplotlib><widget>
2022-12-27 14:09:48
1
693
Delosari
74,930,327
893,254
Python Pandas and Matplotlib - How can I control the relative size of the figure to text labels?
<p>Here is a figured produced by Python Pandas + Matplotlib</p> <p><a href="https://i.sstatic.net/Sqcc1.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Sqcc1.png" alt="pandas and matplotlib bar graph" /></a></p> <p>The problem is obvious: The x-axis labels are too large relative to the overall figure size.</p> <p>There are two ways to solve this:</p> <ul> <li>Increase the overall figure size, keeping the label font size the same</li> <li>Reduce the label font size while keeping the figure size the same</li> </ul> <p>I am saving the output as pdf. I would ideally like to use the first option, as when I open this file on my computer, the actual screen rendered size is about 400 pixels wide, which isn't very large. But this may not be possile when saving as pdf?</p> <p>The code relevant is just two lines. <code>data_age</code> created from a Pandas dataframe.</p> <pre><code> # data is a Panadas dataframe, one of the columns is `'age'`. data_age = data['age'].value_counts().sort_index() plot = data_age.plot.bar() pplt.savefig('age.pdf') </code></pre> <p>I searched around to find a solution to what I would have assumed would be a commonly encountered problem. I then went and read the documentation for matplotlib. There was an option <code>dpi</code> but this doesn't seem to have any effect when writing to a pdf file - which isn't surprising since pdf isn't a rasterized format.</p> <p><code>pplt</code> is obtained from <code>import matplotlib.pyplot as pplt</code>.</p>
<python><pandas><matplotlib><pdf>
2022-12-27 14:09:14
1
18,579
user2138149
74,930,294
2,409,793
Unable to use google.cloud (storage) from within a python script
<p>I am trying to run the following simple script</p> <pre><code>#!/usr/local/bin/python3.9 from google.cloud import storage client = storage.Client() for blob in client.list_blobs('my-bucket', prefix='some/path'): print(str(blob)) </code></pre> <p>This fails as follows:</p> <pre><code>▶ ./test.py Traceback (most recent call last): File &quot;/Users/pkaramol/Desktop/./test.py&quot;, line 3, in &lt;module&gt; from google.cloud import storage ModuleNotFoundError: No module named 'google.cloud' </code></pre> <p>However, <code>google-cloud-storage</code> is already installed:</p> <pre><code>▶ pip freeze | grep -i google google-api-core==2.11.0 google-auth==2.15.0 google-cloud==0.34.0 google-cloud-core==2.3.2 google-cloud-storage==2.7.0 google-crc32c==1.5.0 google-resumable-media==2.4.0 googleapis-common-protos==1.57.0 </code></pre> <p>Why is that?</p>
<python><python-3.x><google-cloud-platform><gcloud>
2022-12-27 14:06:20
1
19,856
pkaramol
74,930,282
2,007,927
How to install cryptography library on Docker container?
<p>I develop our company website with Odoo 14. I installed Odoo on my local machine (<code>macOS Monterey (12.5.1)</code>) via Docker. I use Docker Desktop and I have created <code>docker-compose.yaml</code> taking <a href="https://hub.docker.com/_/odoo" rel="nofollow noreferrer">official Odoo docker image page</a> as reference.</p> <pre><code>version: '2' services: web: image: odoo:14.0 depends_on: - db ports: - &quot;8069:8069&quot; volumes: - odoo-web-data:/var/lib/odoo© - ./config:/etc/odoo - ./addons:/mnt/extra-addons db: image: postgres:10 environment: - POSTGRES_DB=postgres - POSTGRES_PASSWORD=odoo - POSTGRES_USER=odoo - PGDATA=/var/lib/postgresql/data/pgdata volumes: - odoo-db-data:/var/lib/postgresql/data/pgdata - ./db:/db volumes: odoo-web-data: odoo-db-data: </code></pre> <p>I wanted to install Odoo eCommerce module but I couldn't. It gives that error:</p> <blockquote> <p>Unable to install module &quot;account_edi_proxy_client&quot; because an external dependency is not met: Python library not installed: cryptography</p> </blockquote> <p>I already installed it but it still gives the same error.</p> <pre><code>$ pip3 install cryptography Requirement already satisfied: cryptography in /usr/local/lib/python3.10/site-packages (38.0.4) Requirement already satisfied: cffi&gt;=1.12 in /usr/local/lib/python3.10/site-packages (from cryptography) (1.15.1) Requirement already satisfied: pycparser in /usr/local/lib/python3.10/site-packages (from cffi&gt;=1.12-&gt;cryptography) (2.21) </code></pre> <p>There were some suggestion to install <code>pycryptodome</code> instead, I installed it as well but still the same result.</p> <p>After all, I realised that I was trying installing cryptography library on my local machine and actually I had to install it in the docker container.</p> <p>So, I ran this command:</p> <pre><code>docker exec -it [container_name] pip3 install cryptography </code></pre> <p>and I got this error now:</p> <blockquote> <p>Command &quot;/usr/bin/python3 -m pip install --ignore-installed --no-user --prefix /tmp/pip-build-env-ynyd_o0_ --no-warn-script-location --no-binary :none: --only-binary :none: -i <a href="https://pypi.org/simple" rel="nofollow noreferrer">https://pypi.org/simple</a> -- setuptools&gt;=40.6.0,!=60.9.0 wheel &quot;cffi&gt;=1.12; platform_python_implementation != 'PyPy'&quot; setuptools-rust&gt;=0.11.4&quot; failed with error code 1 in None</p> </blockquote> <p>What is missing here, any idea?</p>
<python><docker><odoo><odoo-14>
2022-12-27 14:05:20
2
586
george
74,929,989
12,057,138
How can I get a value only if it exist else return an empty dict in one line?
<p>How to I check if a value exist and then return it and if it doesnt, return an empty dict {} (or any other operation) in one line?</p> <p>I currently do the following which is will crash on none existing value + I also feel it could be written in a much more <em>python</em> way:</p> <pre><code>if (test[0].value): value = test[0].value else value = {} </code></pre>
<python>
2022-12-27 13:39:34
3
688
PloniStacker
74,929,947
4,295,805
Twisted application ignoring a certain UNIX signal - is it possible?
<p>Let's say we have the following situation:</p> <p><code>kill &lt;pid&gt;</code> sends <code>SIGTERM</code></p> <p><code>kill -&lt;SIGNAL&gt; &lt;pid&gt;</code> sends <code>&lt;SIGNAL&gt;</code></p> <p>Sometimes, during development, I need to kill my application and restart it, at the moment - using the first type of command. But, if I have a production console opened, I have a chance to kill our production (let's say, I've forgotten about it - <strong>THIS HAPPENED RIGHT NOW</strong>).</p> <p>The solution that came into my mind is based on ignoring <code>SIGTERM</code> in production mode, but killing the app gracefully in development mode. This way, if, for some reason, I want to kill our prod, I'll need to specify a <code>SIGNAL</code> to do it, and it'll be impossible to be done accidentally.</p> <p>The app is built on Twisted.</p> <p>Twisted has a number useful of methods to use signals with it - for example:</p> <pre><code>reactor.addSystemEventTrigger('before', 'shutdown', shutdown_callback) </code></pre> <p>But is it possible to make it ignore a certain signal? I need only one, and I don't want to go this [<code>reactor.run(installSignalHandlers=False)</code>] way (some people say that it doesn't even work) - it'll require me to rewrite the whole signal handling by myself, and that's not what I'm looking for.</p> <p>Thanks!</p>
<python><unix><signals><posix><twisted>
2022-12-27 13:35:38
2
1,345
Leontyev Georgiy
74,929,803
139,271
How to Retain Expicit Zero Values in a Python Scipy Sparse COO (Coordinate Format) Matrix?
<p>I create a COO matrix, with zero values in the data array. When I query the new COO matrix data array, I can see those zero values in the array. However, I cannot get the indices for those zero values. I use the nonzero() method to retrieve the indices and indices for those zero values are missing. Does anyone know how to get the indices of those zero values? If not is this a bug in the COO code?</p> <p>Below is example code to recreate the problem. The final assert is false, as the number of values is seven, but there are only six non-zero indices. I know that non-zero would clearly not include my zero value, but is there a way to use another similar method to get the explicit zero values?</p> <pre><code>sparse_simple = sp.coo_matrix( [ [1.1, 0, 1.1], [0, 1.1, 4.1], [1.1, 4.1, 1.1] ] ) sparse_simple_data = sparse_simple.data sparse_simple_nz = sparse_simple.nonzero() sparse_simple_data[1] = 0 (n_rows, n_cols) = sparse_simple.shape sparse_simple_with_explicit_close_to_zero = sp.coo_matrix( (sparse_simple_data, (sparse_simple_nz[0], sparse_simple_nz[1])), shape=(n_rows, n_cols) ) num_explicit_vals = len(sparse_simple_with_explicit_close_to_zero.data) nz_idcs = sparse_simple_with_explicit_close_to_zero.nonzero() num_nzs = len(nz_idcs[0]) assert num_explicit_vals == num_nzs </code></pre> <p>I have tried to find another way to extract the indices of the values, including non-zero values, in the documentation of Scipy sparse arrays but failed to find anything.</p> <p>I have a fix for this, but it is a bit of a hack. I simply add a small number to all the nvalues in the data array and then this 'works'.</p> <p>By adding this to the line above creating the COO matrix, this will identify the 'zero' value which is now a very small value. I fixed my code with this but I do not like it.</p> <pre><code>sparse_simple.data += 0.1e-09 </code></pre>
<python><scipy><sparse-matrix>
2022-12-27 13:21:13
1
484
JStrahl
74,929,673
1,807,163
How to get original payload body in except block after raise_for_status is called()
<p>I have a python web server endpoint that calls an external API</p> <pre><code> try: resp = requests.post( url, json={...}, ) resp.raise_for_status() resp_result = resp.json() except requests.exceptions.HTTPError as e: print(e) err_msg = str(e) resp_result = {&quot;error&quot;: err_msg} return JSONResponse(resp_result) </code></pre> <p>The issue is that when the API I call returns a 400, it goes into the <code>except</code> block as expected, but then the returned error message isn't the complete error message that the external API returned.</p> <p>When the external API fails, it returns a 400 with a body like this</p> <pre><code>{ &quot;error&quot;: { &quot;message&quot;: &quot;API key invalid&quot;, &quot;type&quot;: &quot;invalid_request_error&quot;, &quot;param&quot;: null, &quot;code&quot;: null } } </code></pre> <p>But when I do <code>print(e)</code>, all I get is</p> <p><code>400 Client Error: Bad Request for url: https://X</code></p> <p>But I want to return the full external API error message to caller of my endpoint here. So how do I get the full error body while in the except block? Do I need to not use raise_for_status if I want to do that?</p>
<python><python-requests>
2022-12-27 13:07:54
1
5,201
rasen58
74,929,665
7,657,152
Download files using Python-Telegram-bot
<p>I was trying to download the file send by the user via telegram app using python script, I am using the Python-telegram-bot library, I was not able to download the file, below is my code.</p> <pre><code>from telegram.ext import ApplicationBuilder, MessageHandler, filters BOT_TOKEN = '...' # Enable logging logging.basicConfig( format=&quot;%(asctime)s - %(name)s - %(levelname)s - %(message)s&quot;, level=logging.INFO ) logger = logging.getLogger(__name__) def downloader(bot, update, context): logger.info(update.message.document.file_name) logger.info(update.message.document.file_id) context.bot.get_file(update.message.document).download() # writing to a custom file with open(&quot;custom/file.doc&quot;, 'wb') as f: context.bot.get_file(update.message.document).download(out=f) application = ApplicationBuilder().token(BOT_TOKEN).build() # on different commands - answer in Telegram application.add_handler(MessageHandler(filters.Document.ALL, downloader)) # Run the bot until the user presses Ctrl-C application.run_polling() </code></pre> <p><strong>Edited (Working code)</strong>:</p> <p>After going through the telegram-bot document as suggested by @CallMeStag, below code is working, I have few more doubts</p> <ol> <li>I am able to download file, only if the sender types the command(any text with slash-&quot;/&quot;) while sending file.</li> </ol> <p><a href="https://i.sstatic.net/5GZqn.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/5GZqn.png" alt="File sent with command" /></a></p> <ol start="2"> <li>I am unable to download multiple files, sent by user.</li> <li>It is more appreciated, if anyone can edit my code and make it work for multiple file.</li> </ol> <pre><code>import logging from telegram.ext import ApplicationBuilder, MessageHandler, filters, CommandHandler, ContextTypes BOT_TOKEN = '.....' # Enable logging logging.basicConfig( format=&quot;%(asctime)s - %(name)s - %(levelname)s - %(message)s&quot;, level=logging.INFO ) logger = logging.getLogger(__name__) async def downloader(update, context): # Download file fileName = update.message.document.file_name new_file = await update.message.effective_attachment.get_file() await new_file.download_to_drive(fileName) # Acknowledge file received await update.message.reply_text(f&quot;{fileName} saved successfully&quot;) # Send the file chat_id = update.message.chat.id file_id = '20221222-.pptx' await context.bot.send_document(chat_id=chat_id, document=file_id) application = ApplicationBuilder().token(BOT_TOKEN).build() # on different commands - answer in Telegram application.add_handler(MessageHandler(filters.ALL, downloader)) # Run the bot until the user presses Ctrl-C application.run_polling() </code></pre>
<python><telegram><python-telegram-bot>
2022-12-27 13:07:09
2
564
Bhuvan Kumar
74,929,454
9,078,185
Pandas perform identical transformation on multiple dataframes where inline is not an option
<p>I have a situation where I want to <code>shift</code> multiple dataframes by one line. A <code>for</code> loop is the first thing that comes to mind, but that does not actually store the dataframe. Other SO posts suggest using the <code>inline=True</code> option, which works for certain transformations but not <code>shift</code> as inline is not an option. Obviously I could just manually do it by writing several lines of <code>df = df.shift(1)</code> but in the spirit of learning the most pythonic method... Here's a MRE, showing both a standard <code>for</code> loop and a function-based method:</p> <pre><code>import pandas as pd import numpy as np def shifter(df): df = df.shift(1) return df data1 = {'a':np.random.randint(0, 5, 20), 'b':np.random.randint(0, 5, 20), 'c':np.random.randint(0, 5, 20)} data2 = {'foo':np.random.randint(0, 5, 20), 'bar':np.random.randint(0, 5, 20), 'again':np.random.randint(0, 5, 20)} df1 = pd.DataFrame(data=data1) df2 = pd.DataFrame(data=data2) print(df1) for x in [df1, df2]: x = x.shift(1) print(df1) for x in [df1, df2]: x = shifter(x) print(df1) </code></pre>
<python><pandas>
2022-12-27 12:47:54
2
1,063
Tom
74,929,204
11,998,258
Using processing.py in Anaconda
<p>On page below I read that processing.py is in fact &quot;add-on called Python Mode&quot;:</p> <p><a href="https://py.processing.org/tutorials/gettingstarted/" rel="nofollow noreferrer">https://py.processing.org/tutorials/gettingstarted/</a></p> <p>Does it mean that I cannot by any means use processing inside my python code - let's say - in some Anaconda IDE like Spyder? And to run some equivalent of processing sketches in python?</p> <p>In other words: How to run some non-trivial code like setup() and draw() functions from sketches like: <a href="https://py.processing.org/tutorials/p3d/" rel="nofollow noreferrer">https://py.processing.org/tutorials/p3d/</a> ?</p>
<python><anaconda><processing>
2022-12-27 12:22:06
1
302
RunTheGauntlet
74,929,195
15,775,069
Why is rust-mongodb library slow compared to c++ version?
<p>I've loaded this <a href="http://data.insideairbnb.com/spain/catalonia/barcelona/2022-09-10/data/calendar.csv.gz" rel="nofollow noreferrer">airbnb dataset</a> into a local mongodb(version 4.4.17) database called <code>sample_db</code> and collection called <code>barcelona_cal</code>. There are <code>6175334</code> records in the collection.</p> <p>I created a small experiment to compare rust, c++ and python performances. The code for each langugage will simply get a cursor for the collection and iterate over it, increment a counter and note the time taken.</p> <p>here's the python code:</p> <pre><code>import pymongo from bson.raw_bson import RawBSONDocument db = &quot;sample_db&quot; collection = &quot;barcelona_cal&quot; def get_docs(db, collection, document_class=RawBSONDocument): url = &quot;mongodb://localhost:27017&quot; client = pymongo.MongoClient(url, document_class=document_class) coll = client.get_database(db).get_collection(collection) count = 0 for doc in coll.find({}): count += 1 print('Doc count: ', count) def main(): get_docs(db, collection, dict) if __name__ == &quot;__main__&quot;: main() </code></pre> <p>running this code using <code>time python3 test.py</code> returns the following times:</p> <pre><code>real 0m32.784s user 0m28.076s sys 0m1.888s </code></pre> <p>considering most of the time is spent in decoding the bson into python objects, I ran it again with the the default argument <code>document_class=RawBSONDocument</code>. It gave the following times:</p> <pre><code>real 0m12.132s user 0m8.113s sys 0m1.266s </code></pre> <p>Now, I repeated the same experiment with c++ with the following code:</p> <pre><code>#include &lt;iostream&gt; #include &lt;mongocxx/client.hpp&gt; #include &lt;mongocxx/uri.hpp&gt; #include &lt;mongocxx/instance.hpp&gt; #include &lt;bsoncxx/types.hpp&gt; void mongo_connection_test(){ mongocxx::instance instance{}; mongocxx::client client{mongocxx::uri{}}; mongocxx::database database = client[&quot;sample_db&quot;]; mongocxx::collection collection = database[&quot;barcelona_cal&quot;]; mongocxx::cursor cursor = collection.find({}); bsoncxx::document::element el; uint32_t count = 0; for(auto doc: cursor) { count += 1; } std::cout &lt;&lt; &quot;Leads: &quot; &lt;&lt; count &lt;&lt; std::endl; } int main(){ mongo_connection_test(); } </code></pre> <p>This resulted in the following times:</p> <pre><code>real 0m3.347s user 0m0.388s sys 0m1.004s </code></pre> <p>Now, coming to the rust code. On rustc 1.65, with latest mongodb crate version 2.3.1, this is the equivalent code:</p> <pre><code>use std::io::Read; use mongodb::{sync::Client, options::ClientOptions, bson::doc, bson::Document}; fn cursor_iterate()-&gt; mongodb::error::Result&lt;()&gt;{ // setup let mongo_url = &quot;mongodb://localhost:27017&quot;; let db_name = &quot;sample_db&quot;; let collection_name = &quot;barcelona_cal&quot;; let client = Client::with_uri_str(mongo_url)?; let database = client.database(db_name); let collection = database.collection::&lt;Document&gt;(collection_name); let mut cursor = collection.find(None, None)?; let mut count = 0; for result in cursor { count += 1; } println!(&quot;Doc count: {}&quot;, count); Ok(()) } fn main() { cursor_iterate(); } </code></pre> <p>The code was built with <code>cargo build --release</code> and ran with <code>time cargo run --release</code>. I got the following times</p> <pre><code>real 0m18.727s user 0m15.541s sys 0m0.790s </code></pre> <p>I've run every version multiple times and got identical results. so all these numbers can be considered representative.</p> <p><strong>Edit: I've run the rust binary separately like <code>time target/release/bbson</code> and that made very little, if no difference cos I did the build and run steps separately.</strong></p> <p>So the question is why is the mongodb rust library so much slower than c++? One interesting thing that I noticed, which may explain this partly is that in the system monitor (ubuntu 22.04), the Network part shows that the tranfer rate is no higher than 64MB/s. Meanwhile for c++ it goes up to 600MB/s. I see similar thing when running the python with dict and that explains the slow bson decoding in python, so is the deserializer that slow in rust too?</p> <p><a href="https://i.sstatic.net/dKmGT.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/dKmGT.png" alt="enter image description here" /></a></p>
<python><c++><mongodb><rust>
2022-12-27 12:20:54
0
361
yuser099881232
74,928,639
11,092,636
When opening word file "/" doesn't work but "\\" does (package os in python)
<p>Create a <code>main.py</code> file and a <code>test.docx</code> file in the parent directory.</p> <p>This works:</p> <pre class="lang-py prettyprint-override"><code>import os os.startfile(&quot;..\\test.docx&quot;) </code></pre> <p>This does not</p> <pre class="lang-py prettyprint-override"><code>import os os.startfile(&quot;../test.docx&quot;) </code></pre> <p>It returns</p> <pre class="lang-py prettyprint-override"><code>FileNotFoundError: [WinError 2] The system cannot find the file specified: '../test.docx' </code></pre> <p>What's even more surprising is that <code>/</code> works in other contexts, e.g.</p> <pre class="lang-py prettyprint-override"><code>print(os.listdir(&quot;../&quot;)) </code></pre> <p>does return a list with <code>test.docx</code> in it.</p> <p>I'm using <code>Windows 11</code>, <code>Python 3.11.1</code> and <code>Pycharm 2022.3</code></p>
<python><operating-system>
2022-12-27 11:21:20
1
720
FluidMechanics Potential Flows
74,928,552
707,145
Converting or printing all sections of rendered quarto document into html in one go
<p>I want to convert <a href="https://shiny.rstudio.com/py/docs/get-started.html" rel="nofollow noreferrer">Shiny for Python</a> document into pdf. Jumping to each section and then printing into pdf is possible. However, wondering if there is a more compact way to print all sections in a one go.</p>
<python><html><quarto><py-shiny>
2022-12-27 11:10:50
1
24,136
MYaseen208
74,928,500
5,680,504
Python module install error when I tried to pip numpy
<p>When I install <code>numpy</code> lib using <code>python -m pip install numpy==1.18.1</code> command, I got the following errors.</p> <pre><code>ramirami-pc:anomalydetector sclee01$ python -m pip install numpy==1.18.1 DEPRECATION: Configuring installation scheme with distutils config files is deprecated and will no longer work in the near future. If you are using a Homebrew or Linuxbrew Python, please see discussion at https://github.com/Homebrew/homebrew-core/issues/76621 Collecting numpy==1.18.1 Using cached numpy-1.18.1.zip (5.4 MB) Installing build dependencies ... done Getting requirements to build wheel ... done Preparing metadata (pyproject.toml) ... done Building wheels for collected packages: numpy Building wheel for numpy (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for numpy (pyproject.toml) did not run successfully. │ exit code: 1 ╰─&gt; [705 lines of output] /private/var/folders/9x/grsv4dws25j7wc9f16mt6fzx7nz37c/T/pip-install-sh2vo79x/numpy_2f275be08abf460d9f7ebbc831c5ddb7/tools/cythonize.py:75: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. required_version = LooseVersion('0.29.14') /private/var/folders/9x/grsv4dws25j7wc9f16mt6fzx7nz37c/T/pip-install-sh2vo79x/numpy_2f275be08abf460d9f7ebbc831c5ddb7/tools/cythonize.py:77: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. if LooseVersion(cython_version) &lt; required_version: numpy/random/_bounded_integers.pxd.in has not changed numpy/random/_philox.pyx has not changed numpy/random/_bit_generator.pyx has not changed numpy/random/_bounded_integers.pyx.in has not changed numpy/random/_sfc64.pyx has not changed numpy/random/_mt19937.pyx has not changed Processing numpy/random/_bounded_integers.pyx numpy/random/mtrand.pyx has not changed numpy/random/_generator.pyx has not changed numpy/random/_pcg64.pyx has not changed numpy/random/_common.pyx has not changed Cythonizing sources blas_opt_info: blas_mkl_info: customize UnixCCompiler ......... C compiler: clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.sdk creating build/temp.macosx-12-arm64-cpython-38 creating build/temp.macosx-12-arm64-cpython-38/numpy creating build/temp.macosx-12-arm64-cpython-38/numpy/core creating build/temp.macosx-12-arm64-cpython-38/numpy/core/src creating build/temp.macosx-12-arm64-cpython-38/numpy/core/src/npymath creating build/temp.macosx-12-arm64-cpython-38/build creating build/temp.macosx-12-arm64-cpython-38/build/src.macosx-12-arm64-3.8 creating build/temp.macosx-12-arm64-cpython-38/build/src.macosx-12-arm64-3.8/numpy creating build/temp.macosx-12-arm64-cpython-38/build/src.macosx-12-arm64-3.8/numpy/core creating build/temp.macosx-12-arm64-cpython-38/build/src.macosx-12-arm64-3.8/numpy/core/src creating build/temp.macosx-12-arm64-cpython-38/build/src.macosx-12-arm64-3.8/numpy/core/src/npymath compile options: '-Ibuild/src.macosx-12-arm64-3.8/numpy/core/src/npymath -Inumpy/core/include -Ibuild/src.macosx-12-arm64-3.8/numpy/core/include/numpy -Inumpy/core/src/common -Inumpy/core/src -Inumpy/core -Inumpy/core/src/npymath -Inumpy/core/src/multiarray -Inumpy/core/src/umath -Inumpy/core/src/npysort -I/opt/homebrew/opt/python@3.8/Frameworks/Python.framework/Versions/3.8/include/python3.8 -Ibuild/src.macosx-12-arm64-3.8/numpy/core/src/common -Ibuild/src.macosx-12-arm64-3.8/numpy/core/src/npymath -c' clang: numpy/core/src/npymath/npy_math.c clang: build/src.macosx-12-arm64-3.8/numpy/core/src/npymath/ieee754.c clang: build/src.macosx-12-arm64-3.8/numpy/core/src/npymath/npy_math_complex.c clang: numpy/core/src/npymath/halffloat.c In file included from numpy/core/src/npymath/npy_math.c:9: numpy/core/src/npymath/npy_math_internal.h.src:490:21: warning: incompatible pointer types passing 'npy_longdouble *' (aka 'double *') to parameter of type 'long double *' [-Wincompatible-pointer-types] return modfl(x, iptr); ^~~~ /Library/Developer/CommandLineTools/SDKs/MacOSX12.sdk/usr/include/math.h:394:52: note: passing argument to parameter here extern long double modfl(long double, long double *); ^ 1 warning generated. ar: adding 4 object files to build/temp.macosx-12-arm64-cpython-38/libnpymath.a ranlib:@ build/temp.macosx-12-arm64-cpython-38/libnpymath.a building 'npysort' library compiling C sources C compiler: clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.sdk creating build/temp.macosx-12-arm64-cpython-38/build/src.macosx-12-arm64-3.8/numpy/core/src/npysort compile options: '-Ibuild/src.macosx-12-arm64-3.8/numpy/core/src/common -Inumpy/core/include -Ibuild/src.macosx-12-arm64-3.8/numpy/core/include/numpy -Inumpy/core/src/common -Inumpy/core/src -Inumpy/core -Inumpy/core/src/npymath -Inumpy/core/src/multiarray -Inumpy/core/src/umath -Inumpy/core/src/npysort -I/opt/homebrew/opt/python@3.8/Frameworks/Python.framework/Versions/3.8/include/python3.8 -Ibuild/src.macosx-12-arm64-3.8/numpy/core/src/common -Ibuild/src.macosx-12-arm64-3.8/numpy/core/src/npymath -c' clang: build/src.macosx-12-arm64-3.8/numpy/core/src/npysort/quicksort.c clang: build/src.macosx-12-arm64-3.8/numpy/core/src/npysort/mergesort.c clang: build/src.macosx-12-arm64-3.8/numpy/core/src/npysort/timsort.c clang: build/src.macosx-12-arm64-3.8/numpy/core/src/npysort/heapsort.c clang: build/src.macosx-12-arm64-3.8/numpy/core/src/npysort/radixsort.c clang: build/src.macosx-12-arm64-3.8/numpy/core/src/npysort/selection.c clang: build/src.macosx-12-arm64-3.8/numpy/core/src/npysort/binsearch.c numpy/core/src/npysort/selection.c.src:328:9: warning: code will never be executed [-Wunreachable-code] npy_intp k; ^~~~~~~~~~~ numpy/core/src/npysort/selection.c.src:326:14: note: silence by adding parentheses to mark code as explicitly dead else if (0 &amp;&amp; kth == num - 1) { ^ /* DISABLES CODE */ ( ) numpy/core/src/npysort/selection.c.src:328:9: warning: code will never be executed [-Wunreachable-code] npy_intp k; ^~~~~~~~~~~ numpy/core/src/npysort/selection.c.src:326:14: note: silence by adding parentheses to mark code as explicitly dead else if (0 &amp;&amp; kth == num - 1) { ^ /* DISABLES CODE */ ( ) numpy/core/src/npysort/selection.c.src:328:9: warning: code will never be executed [-Wunreachable-code] npy_intp k; ^~~~~~~~~~~ numpy/core/src/npysort/selection.c.src:326:14: note: silence by adding parentheses to mark code as explicitly dead else if (0 &amp;&amp; kth == num - 1) { ^ /* DISABLES CODE */ ( ) numpy/core/src/npysort/selection.c.src:328:9: warning: code will never be executed [-Wunreachable-code] npy_intp k; ^~~~~~~~~~~ numpy/core/src/npysort/selection.c.src:326:14: note: silence by adding parentheses to mark code as explicitly dead else if (0 &amp;&amp; kth == num - 1) { ^ /* DISABLES CODE */ ( ) numpy/core/src/npysort/selection.c.src:328:9: warning: code will never be executed [-Wunreachable-code] npy_intp k; ^~~~~~~~~~~ numpy/core/src/npysort/selection.c.src:326:14: note: silence by adding parentheses to mark code as explicitly dead else if (0 &amp;&amp; kth == num - 1) { ^ /* DISABLES CODE */ ( ) numpy/core/src/npysort/selection.c.src:328:9: warning: code will never be executed [-Wunreachable-code] npy_intp k; ^~~~~~~~~~~ numpy/core/src/npysort/selection.c.src:326:14: note: silence by adding parentheses to mark code as explicitly dead else if (0 &amp;&amp; kth == num - 1) { ^ /* DISABLES CODE */ ( ) numpy/core/src/npysort/selection.c.src:328:9: warning: code will never be executed [-Wunreachable-code] npy_intp k; ^~~~~~~~~~~ numpy/core/src/npysort/selection.c.src:326:14: note: silence by adding parentheses to mark code as explicitly dead else if (0 &amp;&amp; kth == num - 1) { ^ /* DISABLES CODE */ ( ) numpy/core/src/npysort/selection.c.src:328:9: warning: code will never be executed [-Wunreachable-code] npy_intp k; ^~~~~~~~~~~ numpy/core/src/npysort/selection.c.src:326:14: note: silence by adding parentheses to mark code as explicitly dead else if (0 &amp;&amp; kth == num - 1) { ^ /* DISABLES CODE */ ( ) numpy/core/src/npysort/selection.c.src:328:9: warning: code will never be executed [-Wunreachable-code] npy_intp k; ^~~~~~~~~~~ numpy/core/src/npysort/selection.c.src:326:14: note: silence by adding parentheses to mark code as explicitly dead else if (0 &amp;&amp; kth == num - 1) { ^ /* DISABLES CODE */ ( ) numpy/core/src/npysort/selection.c.src:328:9: warning: code will never be executed [-Wunreachable-code] npy_intp k; ^~~~~~~~~~~ numpy/core/src/npysort/selection.c.src:326:14: note: silence by adding parentheses to mark code as explicitly dead else if (0 &amp;&amp; kth == num - 1) { ^ /* DISABLES CODE */ ( ) numpy/core/src/npysort/selection.c.src:328:9: warning: code will never be executed [-Wunreachable-code] npy_intp k; ^~~~~~~~~~~ numpy/core/src/npysort/selection.c.src:326:14: note: silence by adding parentheses to mark code as explicitly dead else if (0 &amp;&amp; kth == num - 1) { ^ /* DISABLES CODE */ ( ) numpy/core/src/npysort/selection.c.src:328:9: warning: code will never be executed [-Wunreachable-code] npy_intp k; ^~~~~~~~~~~ numpy/core/src/npysort/selection.c.src:326:14: note: silence by adding parentheses to mark code as explicitly dead else if (0 &amp;&amp; kth == num - 1) { ^ /* DISABLES CODE */ ( ) numpy/core/src/npysort/selection.c.src:328:9: warning: code will never be executed [-Wunreachable-code] npy_intp k; ^~~~~~~~~~~ numpy/core/src/npysort/selection.c.src:326:14: note: silence by adding parentheses to mark code as explicitly dead else if (0 &amp;&amp; kth == num - 1) { ^ /* DISABLES CODE */ ( ) numpy/core/src/npysort/selection.c.src:328:9: warning: code will never be executed [-Wunreachable-code] npy_intp k; ^~~~~~~~~~~ numpy/core/src/npysort/selection.c.src:326:14: note: silence by adding parentheses to mark code as explicitly dead else if (0 &amp;&amp; kth == num - 1) { ^ /* DISABLES CODE */ ( ) numpy/core/src/npysort/selection.c.src:328:9: warning: code will never be executed [-Wunreachable-code] npy_intp k; ^~~~~~~~~~~ numpy/core/src/npysort/selection.c.src:326:14: note: silence by adding parentheses to mark code as explicitly dead else if (0 &amp;&amp; kth == num - 1) { ^ /* DISABLES CODE */ ( ) numpy/core/src/npysort/selection.c.src:328:9: warning: code will never be executed [-Wunreachable-code] npy_intp k; ^~~~~~~~~~~ numpy/core/src/npysort/selection.c.src:326:14: note: silence by adding parentheses to mark code as explicitly dead else if (0 &amp;&amp; kth == num - 1) { ^ /* DISABLES CODE */ ( ) numpy/core/src/npysort/selection.c.src:328:9: warning: code will never be executed [-Wunreachable-code] npy_intp k; ^~~~~~~~~~~ numpy/core/src/npysort/selection.c.src:326:14: note: silence by adding parentheses to mark code as explicitly dead else if (0 &amp;&amp; kth == num - 1) { ^ /* DISABLES CODE */ ( ) numpy/core/src/npysort/selection.c.src:328:9: warning: code will never be executed [-Wunreachable-code] npy_intp k; ^~~~~~~~~~~ numpy/core/src/npysort/selection.c.src:326:14: note: silence by adding parentheses to mark code as explicitly dead else if (0 &amp;&amp; kth == num - 1) { ^ /* DISABLES CODE */ ( ) numpy/core/src/npysort/selection.c.src:328:9: warning: code will never be executed [-Wunreachable-code] npy_intp k; ^~~~~~~~~~~ numpy/core/src/npysort/selection.c.src:326:14: note: silence by adding parentheses to mark code as explicitly dead else if (0 &amp;&amp; kth == num - 1) { ^ /* DISABLES CODE */ ( ) numpy/core/src/npysort/selection.c.src:328:9: warning: code will never be executed [-Wunreachable-code] npy_intp k; ^~~~~~~~~~~ numpy/core/src/npysort/selection.c.src:326:14: note: silence by adding parentheses to mark code as explicitly dead else if (0 &amp;&amp; kth == num - 1) { ^ /* DISABLES CODE */ ( ) numpy/core/src/npysort/selection.c.src:328:9: warning: code will never be executed [-Wunreachable-code] npy_intp k; ^~~~~~~~~~~ numpy/core/src/npysort/selection.c.src:326:14: note: silence by adding parentheses to mark code as explicitly dead else if (0 &amp;&amp; kth == num - 1) { ^ /* DISABLES CODE */ ( ) numpy/core/src/npysort/selection.c.src:328:9: warning: code will never be executed [-Wunreachable-code] npy_intp k; ^~~~~~~~~~~ numpy/core/src/npysort/selection.c.src:326:14: note: silence by adding parentheses to mark code as explicitly dead else if (0 &amp;&amp; kth == num - 1) { ^ /* DISABLES CODE */ ( ) 22 warnings generated. ar: adding 7 object files to build/temp.macosx-12-arm64-cpython-38/libnpysort.a ranlib:@ build/temp.macosx-12-arm64-cpython-38/libnpysort.a running build_ext customize UnixCCompiler customize UnixCCompiler using new_build_ext building 'numpy.core._multiarray_tests' extension compiling C sources C compiler: clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.sdk creating build/temp.macosx-12-arm64-cpython-38/build/src.macosx-12-arm64-3.8/numpy/core/src/multiarray creating build/temp.macosx-12-arm64-cpython-38/numpy/core/src/common compile options: '-DNPY_INTERNAL_BUILD=1 -DHAVE_NPY_CONFIG_H=1 -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE=1 -D_LARGEFILE64_SOURCE=1 -Inumpy/core/include -Ibuild/src.macosx-12-arm64-3.8/numpy/core/include/numpy -Inumpy/core/src/common -Inumpy/core/src -Inumpy/core -Inumpy/core/src/npymath -Inumpy/core/src/multiarray -Inumpy/core/src/umath -Inumpy/core/src/npysort -I/opt/homebrew/opt/python@3.8/Frameworks/Python.framework/Versions/3.8/include/python3.8 -Ibuild/src.macosx-12-arm64-3.8/numpy/core/src/common -Ibuild/src.macosx-12-arm64-3.8/numpy/core/src/npymath -c' clang: build/src.macosx-12-arm64-3.8/numpy/core/src/multiarray/_multiarray_tests.c clang: numpy/core/src/common/mem_overlap.c In file included from numpy/core/src/multiarray/_multiarray_tests.c.src:7: In file included from numpy/core/include/numpy/npy_math.h:643: numpy/core/src/npymath/npy_math_internal.h.src:490:21: warning: incompatible pointer types passing 'npy_longdouble *' (aka 'double *') to parameter of type 'long double *' [-Wincompatible-pointer-types] return modfl(x, iptr); ^~~~ /Library/Developer/CommandLineTools/SDKs/MacOSX12.sdk/usr/include/math.h:394:52: note: passing argument to parameter here extern long double modfl(long double, long double *); ^ numpy/core/src/multiarray/_multiarray_tests.c.src:1923:61: warning: format specifies type 'long double' but the argument has type 'npy_longdouble' (aka 'double') [-Wformat] PyOS_snprintf(str, sizeof(str), &quot;%.*Lg&quot;, precision, x); ~~~~~ ^ %.*g 2 warnings generated. clang -bundle -undefined dynamic_lookup -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.sdk build/temp.macosx-12-arm64-cpython-38/build/src.macosx-12-arm64-3.8/numpy/core/src/multiarray/_multiarray_tests.o build/temp.macosx-12-arm64-cpython-38/numpy/core/src/common/mem_overlap.o -Lbuild/temp.macosx-12-arm64-cpython-38 -lnpymath -o build/lib.macosx-12-arm64-cpython-38/numpy/core/_multiarray_tests.cpython-38-darwin.so ld: warning: -undefined dynamic_lookup may not work with chained fixups building 'numpy.core._multiarray_umath' extension compiling C sources C compiler: clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.sdk creating build/temp.macosx-12-arm64-cpython-38/numpy/core/src/multiarray creating build/temp.macosx-12-arm64-cpython-38/numpy/core/src/umath creating build/temp.macosx-12-arm64-cpython-38/build/src.macosx-12-arm64-3.8/numpy/core/src/umath creating build/temp.macosx-12-arm64-cpython-38/private creating build/temp.macosx-12-arm64-cpython-38/private/var creating build/temp.macosx-12-arm64-cpython-38/private/var/folders creating build/temp.macosx-12-arm64-cpython-38/private/var/folders/9x creating build/temp.macosx-12-arm64-cpython-38/private/var/folders/9x/grsv4dws25j7wc9f16mt6fzx7nz37c creating build/temp.macosx-12-arm64-cpython-38/private/var/folders/9x/grsv4dws25j7wc9f16mt6fzx7nz37c/T creating build/temp.macosx-12-arm64-cpython-38/private/var/folders/9x/grsv4dws25j7wc9f16mt6fzx7nz37c/T/pip-install-sh2vo79x creating build/temp.macosx-12-arm64-cpython-38/private/var/folders/9x/grsv4dws25j7wc9f16mt6fzx7nz37c/T/pip-install-sh2vo79x/numpy_2f275be08abf460d9f7ebbc831c5ddb7 creating build/temp.macosx-12-arm64-cpython-38/private/var/folders/9x/grsv4dws25j7wc9f16mt6fzx7nz37c/T/pip-install-sh2vo79x/numpy_2f275be08abf460d9f7ebbc831c5ddb7/numpy creating build/temp.macosx-12-arm64-cpython-38/private/var/folders/9x/grsv4dws25j7wc9f16mt6fzx7nz37c/T/pip-install-sh2vo79x/numpy_2f275be08abf460d9f7ebbc831c5ddb7/numpy/_build_utils creating build/temp.macosx-12-arm64-cpython-38/private/var/folders/9x/grsv4dws25j7wc9f16mt6fzx7nz37c/T/pip-install-sh2vo79x/numpy_2f275be08abf460d9f7ebbc831c5ddb7/numpy/_build_utils/src compile options: '-DNPY_INTERNAL_BUILD=1 -DHAVE_NPY_CONFIG_H=1 -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE=1 -D_LARGEFILE64_SOURCE=1 -DNO_ATLAS_INFO=3 -DHAVE_CBLAS -Ibuild/src.macosx-12-arm64-3.8/numpy/core/src/umath -Ibuild/src.macosx-12-arm64-3.8/numpy/core/src/npymath -Ibuild/src.macosx-12-arm64-3.8/numpy/core/src/common -Inumpy/core/include -Ibuild/src.macosx-12-arm64-3.8/numpy/core/include/numpy -Inumpy/core/src/common -Inumpy/core/src -Inumpy/core -Inumpy/core/src/npymath -Inumpy/core/src/multiarray -Inumpy/core/src/umath -Inumpy/core/src/npysort -I/opt/homebrew/opt/python@3.8/Frameworks/Python.framework/Versions/3.8/include/python3.8 -Ibuild/src.macosx-12-arm64-3.8/numpy/core/src/common -Ibuild/src.macosx-12-arm64-3.8/numpy/core/src/npymath -c' extra options: '-faltivec -I/System/Library/Frameworks/vecLib.framework/Headers' clang: numpy/core/src/multiarray/alloc.c clang: numpy/core/src/multiarray/array_assign_scalar.c clang: numpy/core/src/multiarray/common.c clang: numpy/core/src/multiarray/conversion_utils.c clang: numpy/core/src/multiarray/buffer.c clangclang: : error: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitlythe clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: numpy/core/src/multiarray/descriptor.c clang: numpy/core/src/multiarray/hashdescr.c clang: numpy/core/src/multiarray/datetime_strings.c clang: build/src.macosx-12-arm64-3.8/numpy/core/src/multiarray/einsum.c clang: build/src.macosx-12-arm64-3.8/numpy/core/src/multiarray/lowlevel_strided_loops.c clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: numpy/core/src/multiarray/multiarraymodule.c clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: numpy/core/src/multiarray/nditer_constr.c clang: numpy/core/src/multiarray/refcount.c clang: numpy/core/src/multiarray/scalarapi.c clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: numpy/core/src/multiarray/temp_elide.c clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: numpy/core/src/multiarray/vdot.c clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: build/src.macosx-12-arm64-3.8/numpy/core/src/umath/loops.c clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: numpy/core/src/umath/ufunc_object.c clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: build/src.macosx-12-arm64-3.8/numpy/core/src/umath/scalarmath.c clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: numpy/core/src/npymath/npy_math.c clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: numpy/core/src/npymath/halffloat.c clang: numpy/core/src/common/numpyos.c clang: numpy/core/src/common/npy_longdouble.c clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: /private/var/folders/9x/grsv4dws25j7wc9f16mt6fzx7nz37c/T/pip-install-sh2vo79x/numpy_2f275be08abf460d9f7ebbc831c5ddb7/numpy/_build_utils/src/apple_sgemv_fix.c clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly Running from numpy source directory. /private/var/folders/9x/grsv4dws25j7wc9f16mt6fzx7nz37c/T/pip-build-env-vcfnfhxr/overlay/lib/python3.8/site-packages/setuptools/_distutils/dist.py:265: UserWarning: Unknown distribution option: 'define_macros' warnings.warn(msg) error: Command &quot;clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.sdk -DNPY_INTERNAL_BUILD=1 -DHAVE_NPY_CONFIG_H=1 -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE=1 -D_LARGEFILE64_SOURCE=1 -DNO_ATLAS_INFO=3 -DHAVE_CBLAS -Ibuild/src.macosx-12-arm64-3.8/numpy/core/src/umath -Ibuild/src.macosx-12-arm64-3.8/numpy/core/src/npymath -Ibuild/src.macosx-12-arm64-3.8/numpy/core/src/common -Inumpy/core/include -Ibuild/src.macosx-12-arm64-3.8/numpy/core/include/numpy -Inumpy/core/src/common -Inumpy/core/src -Inumpy/core -Inumpy/core/src/npymath -Inumpy/core/src/multiarray -Inumpy/core/src/umath -Inumpy/core/src/npysort -I/opt/homebrew/opt/python@3.8/Frameworks/Python.framework/Versions/3.8/include/python3.8 -Ibuild/src.macosx-12-arm64-3.8/numpy/core/src/common -Ibuild/src.macosx-12-arm64-3.8/numpy/core/src/npymath -c numpy/core/src/multiarray/alloc.c -o build/temp.macosx-12-arm64-cpython-38/numpy/core/src/multiarray/alloc.o -MMD -MF build/temp.macosx-12-arm64-cpython-38/numpy/core/src/multiarray/alloc.o.d -faltivec -I/System/Library/Frameworks/vecLib.framework/Headers&quot; failed with exit status 1 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for numpy Failed to build numpy ERROR: Could not build wheels for numpy, which is required to install pyproject.toml-based projects. </code></pre> <p>I don't know why this errors happened. Note that I should install 1.18.1 numpy for the project.</p> <p>Could you help me?</p> <p>Thanks.</p>
<python>
2022-12-27 11:03:47
3
1,329
sclee1
74,928,439
14,661,648
How to specify the years on an axis when using plot() on DateTime objects
<p>The plotting goes like this:</p> <p><code>plt.plot(df['Date'], df['Price'])</code></p> <p><code>df['Date']</code> consists of DateTime objects with several years and <code>df['Price']</code> are integers. However on the actual line graph, it automatically selects about 4 years spaced apart in the graph with large intervals:</p> <p><a href="https://i.sstatic.net/byE4v.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/byE4v.png" alt="enter image description here" /></a></p> <p>How do I make it so that I can specify the number of years to show on the X axis? Or perhaps show all the years (year only)?</p> <p>Example:</p> <pre><code>import pandas as pd import datetime import random dates = [] prices = [] for count in range(10000): prices.append(random.randint(0, 10)) dates.append(datetime.datetime(random.randint(1960, 2022), random.randint(1, 12), random.randint(1, 27)).strftime(&quot;%Y-%m-%d&quot;)) data = { 'Date': dates, 'Price': prices } df = pd.DataFrame(data) df = df.sort_values(by=['Date'], ignore_index = True) df_temp = df.copy() df_temp['Date DT'] = pd.to_datetime(df_temp['Date']) df_temp = df_temp.drop(axis = 'columns', columns = 'Date') df = df_temp df </code></pre> <pre><code>import numpy as np import matplotlib.pyplot as plt from matplotlib.pyplot import figure plt.figure(figsize=(15, 5), dpi = 1000) plt.plot(df['Date DT'], df['Price']) # Labels plt.xlabel('Dates', fontsize = 8) plt.ylabel('Prices', fontsize = 8) # Save plt.title('Example', fontsize = 15) plt.savefig('example.png', bbox_inches = 'tight') </code></pre>
<python><matplotlib>
2022-12-27 10:57:39
1
1,067
Jiehfeng
74,928,438
5,994,555
Using python 3.8 but importing pytest from 2.8 instead of 3.8
<p>I'm using python 3.8 but pytest keeps getting imported from 2.7 These are my commands:</p> <pre><code>python3.8 -m venv venv . ./venv/bin/activate pip3.8 install --upgrade pip pip3.8 install -U pytest pip3.8 install -r requirements.txt </code></pre> <p>Then I check:</p> <pre><code>(venv) xxx@xxx:~/Documents/my-dashboard$ pytest --version This is pytest version 3.3.2, imported from /usr/lib/python2.7/dist-packages/pytest.pyc </code></pre> <p>Why is pytest imported from 2.7 version if my environment is using 3.8? How do I import pytest from 3.8?</p>
<python><pytest><version>
2022-12-27 10:57:32
1
497
Sabina Orazem
74,928,324
11,867,978
How to remove the Scientific notation E getting stored in CSV using Python without pandas?
<p>I am trying to get details from DB and store in CSV, but when i open the csv I see the rows for Id reflecting as below: Id 4.98518E+11</p> <p>How to remove the E+ from csv wihtout using Pandas.</p>
<python><amazon-web-services><dynamodb-queries>
2022-12-27 10:43:59
1
448
Mia
74,928,180
10,924,836
Probit regression in Python
<p>I am trying to implement Probit regression. Dependent values are credit which has integer values 0 and 1. The other three features are salaries, sales, and stores. Before I put in the model I scaled these three features with a Robust Scaler. Below you can see the result of the regression</p> <pre><code>import statsmodels.api as smf probit_model=smf.Probit(y,X) result=probit_model.fit_regularized () print(result.summary2()) </code></pre> <p><a href="https://i.sstatic.net/KYyvp.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/KYyvp.jpg" alt="enter image description here" /></a></p> <p>The final output of this regression you can see above. But I am badly surprised that other values are NaN expect coefficients.</p> <p>So can anybody help me how to solve this problem?</p>
<python><regression>
2022-12-27 10:27:05
0
2,538
silent_hunter
74,928,054
15,852,600
How do I create a new dataframe from another existing one by applying a changing formula?
<p>I have the following dataframe :</p> <pre><code>df_1 = pd.DataFrame({ 'col1' : [20, 60, 55, 80, 32, 33], 'col2' : [10, 16, 18, 12, 19, 20], 'col3' : [5, 2, 7, 9, 1, 2] }) </code></pre> <p>It has the following display:</p> <pre><code> col1 col2 col3 0 20 10 5 1 60 16 2 2 55 18 7 3 80 12 9 4 32 19 1 5 33 20 2 </code></pre> <p>From this <code>df_1</code> I want to get <code>df_2</code> by applying to its columns the following formula : <code>(x**coef - 1) / coef</code> where <code>coef = [0.2, 0.3, 0.4]</code> so <code>df_2</code> will be:</p> <pre><code> col1 col2 col3 0 4.102821 3.317541 2.259135 1 6.339666 4.324656 0.798770 2 6.144037 4.600088 2.944766 3 7.011244 3.691453 3.520562 4 5.000000 4.729818 0.000000 5 5.061733 4.854854 0.798770 </code></pre> <p>To get df_2 I used the follwoing code:</p> <pre><code>coefs = [0.2, 0.3, 0.4] df_2 = pd.DataFrame() cols = df_1.columns df_2[cols[0]] = (df_1[cols[0]]**coefs[0] - 1)/ coefs[0] df_2[cols[1]] = (df_1[cols[1]]**coefs[1] - 1)/ coefs[1] df_2[cols[2]] = (df_1[cols[2]]**coefs[2] - 1)/ coefs[2] </code></pre> <p>There is a way to apply the formula by using some indexing / loop or any other tips ?</p> <p>Any help from your side will be highly appreciated (upvoted indeed !)</p> <p>Best regards !</p>
<python><pandas><dataframe>
2022-12-27 10:14:37
1
921
Khaled DELLAL
74,928,052
12,181,414
SQLModel with Pydantic validator
<p>I want to use <code>SQLModel</code> which combines pydantic and SQLAlchemy.</p> <p>I have a <code>UserCreate</code> class, which should use a custom validator.</p> <p>This is my Code:</p> <pre><code>class UserBase(SQLModel): firstname: str lastname: str username: str email: str password: str age: int class UserCreate(UserBase): repeat_password: str @validator(&quot;repeat_password&quot;) def check_repeat_password(cls, value): if value != cls.password: raise HTTPException( status_code=400, detail=&quot;Repeat password does not match password.&quot; ) return value class UserTable(UserBase, table=True): __tablename__ = &quot;users&quot; id: Optional[int] = Field(default=None, primary_key=True) </code></pre> <p>This results in the following error:</p> <pre><code>line 44, in check_repeat_password if value != cls.password: AttributeError: type object 'UserCreate' has no attribute 'password' </code></pre> <p>Can anyone help me? How can I apply a custom validator when I use the <code>SQLModel</code> Library?</p>
<python><sqlalchemy><pydantic><sqlmodel>
2022-12-27 10:14:29
1
2,155
Data Mastery
74,928,049
17,148,496
How to multiply all columns with each other
<p>I have a pandas dataframe and I want to add to it new features, like this:</p> <p>Say I have features <code>X_1,X_2,X_3 and X_4</code>, then I want to add <code>X_1 * X_2, X_1 * X_3, X_1 * X_4</code>, and similarly <code>X_2 * X_3, X_2 * X_4</code> and <code>X_3 * X_4</code>. I want to add them, not replace the original features.</p> <p>How do I do that?</p>
<python><pandas>
2022-12-27 10:14:06
2
375
Kev
74,927,703
2,983,359
django: Page not found (404)
<p><a href="https://i.sstatic.net/15jEu.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/15jEu.png" alt="Project view" /></a></p> <p>project/urls.py</p> <pre><code>from django.contrib import admin from django.urls import path, include from django.http import HttpResponse urlpatterns = [ path(&quot;admin/&quot;, admin.site.urls), path(&quot;&quot;, include('todo.urls')), ] </code></pre> <p>setting.py</p> <pre><code>TEMPLATES = [ { &quot;BACKEND&quot;: &quot;django.template.backends.django.DjangoTemplates&quot;, &quot;DIRS&quot;: [os.path.join(BASE_DIR, &quot;templates&quot;)], &quot;APP_DIRS&quot;: True, &quot;OPTIONS&quot;: { &quot;context_processors&quot;: [ &quot;django.template.context_processors.debug&quot;, &quot;django.template.context_processors.request&quot;, &quot;django.contrib.auth.context_processors.auth&quot;, &quot;django.contrib.messages.context_processors.messages&quot;, ], }, }, ] </code></pre> <p>todo/ulrs.py</p> <pre><code>from django.urls import path from . import views urlpatterns = [ path(&quot;login&quot;, views.home), ] </code></pre> <p>todo/views.py</p> <pre><code>from django.http import HttpResponse from django.shortcuts import render def home(request): return render(request, 'index.html') </code></pre> <p><a href="https://i.sstatic.net/ybsbV.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ybsbV.png" alt="enter image description here" /></a></p> <p>I don't know why it is not showing my page... I have created django project called taskly. And in that project I have only 1 app called todo. I have referred templates folder as well as you can see above. In that template folder there is only 1 page index.html</p>
<python><django>
2022-12-27 09:36:01
3
1,035
bizimunda