content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
TypeError: linear(): argument 'input' (position 1) must be Tensor, not Flatten
I am new to Neural Networks and I have the following N.N. in a python notebook below that takes in images as the input. I am trying to get it to run but I keep getting the following error: TypeError: linear(): argument 'input' (position... | TypeError: linear(): argument 'input' (position 1) must be Tensor, not Flatten | I am new to Neural Networks and I have the following N.N. in a python notebook below that takes in images as the input. I am trying to get it to run but I keep getting the following error: TypeError: linear(): argument 'input' (position 1) must be Tensor, not Flatten. (Please let me know if any additional information i... | [
"You are using the wrong Flatten!\nThere are two options:\n\nA \"flatten layer\": https://pytorch.org/docs/stable/generated/torch.nn.Flatten.html#torch.nn.Flatten\n\nThe flatten function itself: https://pytorch.org/docs/stable/generated/torch.flatten.html\n\n\nIn your network you are using the first, but you should... | [
0
] | [] | [] | [
"conv_neural_network",
"deep_learning",
"neural_network",
"python"
] | stackoverflow_0074340273_conv_neural_network_deep_learning_neural_network_python.txt |
Q:
Pandas - Blanking out values of one column if value of another column has a specific value
I have the following DataFrame:
import pandas as pd
df = pd.DataFrame({'Status': ['','To Do', '','Completed', 'To Do', 'In Progress', 'Completed'],
'Date': ['','9/1/2022','','12/5/2019','8/12/2020','4/19/2020','12/31/2018'... | Pandas - Blanking out values of one column if value of another column has a specific value | I have the following DataFrame:
import pandas as pd
df = pd.DataFrame({'Status': ['','To Do', '','Completed', 'To Do', 'In Progress', 'Completed'],
'Date': ['','9/1/2022','','12/5/2019','8/12/2020','4/19/2020','12/31/2018']})
I want to blank out the Date column for those rows where the Status is anything but "Comple... | [
"There is a typo here:\ndf = df.loc[df['Status'] != 'Completed', 'Date'] = ''\n\nShould be\ndf.loc[df['Status'] != 'Completed', 'Date'] = ''\n\n"
] | [
3
] | [] | [] | [
"pandas_loc",
"python"
] | stackoverflow_0074340353_pandas_loc_python.txt |
Q:
Python Regex: Match text between two keywords when the text contain a specific word
I'm looking for a Regex to match the whole text of every sentence between the OR operators that contains one or more ANDs, if and only if, one or more ANDs is in the sentence between two ORs. For instance:
this should match
OR "Mes... | Python Regex: Match text between two keywords when the text contain a specific word | I'm looking for a Regex to match the whole text of every sentence between the OR operators that contains one or more ANDs, if and only if, one or more ANDs is in the sentence between two ORs. For instance:
this should match
OR "Message:\"An Arm and a Leg \<Meaning\>: Something that is extremely expensive.\"" AND "Messa... | [
"If I understand you correctly, you want to search for one/or more AND between the OR:\n(?<=OR)((?:(?!OR).)+AND(?:(?!OR).)+)(?=OR)\n\nRegex demo.\n",
"I suggest to use a simple regex for splitting by ' OR ' and adjusting the result in a list comprehension instead of a complex regex for searching (in order to spee... | [
3,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074340051_python_regex.txt |
Q:
Python frequency table, exclude characters
Good evening,
I'm wondering how i can exclude certain characters from a frequency table?
first i read the file, creates a frequency table. after this i change it to a tuple to be able to get a percentage of occourence for each letter.
however i am wondering how i can impl... | Python frequency table, exclude characters | Good evening,
I'm wondering how i can exclude certain characters from a frequency table?
first i read the file, creates a frequency table. after this i change it to a tuple to be able to get a percentage of occourence for each letter.
however i am wondering how i can implement that it does not count certain letters.
ie... | [
"Sounds like you need an if at the end of your dictionary comprension:\nfrequency_table = {char : data.count(char) for char in set(data) if char not in EXCLUDE} \n\nYou can then set your EXCLUDE as, for example:\n\na list, i.e. ['a', 'b', 'c', 'd'] or list('abcd')\nor, you can just use a string of characters direct... | [
1,
0
] | [] | [] | [
"frequency",
"python",
"python_3.x"
] | stackoverflow_0074340339_frequency_python_python_3.x.txt |
Q:
python class to be used everywhere
I have some dictionaries in python with headers similar to this one:
HEADERS['companies-details'] = ["company_id","company_url","company_name",
"free_places","accepted_perc","domain_raw",
"domain_cleaned","email","email_domain","phone_main","phone_main_cleaned",
"founded_year","e... | python class to be used everywhere | I have some dictionaries in python with headers similar to this one:
HEADERS['companies-details'] = ["company_id","company_url","company_name",
"free_places","accepted_perc","domain_raw",
"domain_cleaned","email","email_domain","phone_main","phone_main_cleaned",
"founded_year","employee_count","employee_count_cleaned",... | [
"I'd like to share the way I solved:\nFirst, I created those objects, like this one.\npyndatic automatically parse value and can be used also to evaluate correctness of data, if needed\nfrom pydantic import BaseModel\nfrom typing import List,Optional\n\nclass CompanyDetail(BaseModel):\n company_id: str\n comp... | [
0
] | [] | [] | [
"class",
"python"
] | stackoverflow_0074339177_class_python.txt |
Q:
how to get the foreignkey attribute value
I'm trying to print out the email related to a specific OrderItem for a Customer, I've followed the logic from the answer below and I get the terminology but I'm definitely missing something, can't figure out what exactly, as of now I get the error name 'email' is not defi... | how to get the foreignkey attribute value | I'm trying to print out the email related to a specific OrderItem for a Customer, I've followed the logic from the answer below and I get the terminology but I'm definitely missing something, can't figure out what exactly, as of now I get the error name 'email' is not defined
#Models
class Customer(models.Model):
... | [
"There can be multiple OrderItems for such customer. You filter with:\ndef test():\n email = 'foo@bar.com'\n customer_email = OrderItem.objects.filter(order__customer__email=email)\n print(customer_email)\nIf you have an OrderItem object you use:\nmyorderitem.order.customer.email\n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074340446_django_python.txt |
Q:
Python pandas Chunk Multiprocessing is slow
So, this is my use case.
I need to read the data from pipe separated CSV and then process it (just map as variables) and then send it to a third party.
Originally, the CSV is around 600MB with 1million rows, which can also increase in size or variable.
I tried to load in... | Python pandas Chunk Multiprocessing is slow | So, this is my use case.
I need to read the data from pipe separated CSV and then process it (just map as variables) and then send it to a third party.
Originally, the CSV is around 600MB with 1million rows, which can also increase in size or variable.
I tried to load in chunks using pandas and print it to console
impo... | [
"Expanding on my comments above: the bottleneck in your process is likely to be posting data to the network rather than reading the file from disk. I have run a set of benchmarks below to illustrate this:\n\n\n\n\nMethod\nTime\n\n\n\n\noriginal method with print statement\n10.600501500070095\n\n\nreading file but n... | [
0
] | [] | [] | [
"csv",
"multiprocessing",
"pandas",
"python",
"python_multiprocessing"
] | stackoverflow_0074311995_csv_multiprocessing_pandas_python_python_multiprocessing.txt |
Q:
SQLAlchemy filter with many-to-many relations
A store can have many interests. User request a product that is tagged. Query required is to get the product requests that have tags shared with current store.
# in Store -> relationship('Tag', secondary=store_interest_tags, lazy='dynamic', backref=backref('store', laz... | SQLAlchemy filter with many-to-many relations | A store can have many interests. User request a product that is tagged. Query required is to get the product requests that have tags shared with current store.
# in Store -> relationship('Tag', secondary=store_interest_tags, lazy='dynamic', backref=backref('store', lazy=True))
store_tags = store.interests
matched_requ... | [
"A query like this might work, I think it could be done with less joins but this is less rigid than dropping into using the secondary tables directly and specifying the individual joins:\nq = session.query(\n ProductRequest\n).join(\n ProductRequest.tags\n).join(\n Tag.stores\n).filter(\n Store.id == st... | [
0,
0
] | [] | [] | [
"postgresql",
"python",
"sqlalchemy"
] | stackoverflow_0074340175_postgresql_python_sqlalchemy.txt |
Q:
How to get the number of total scattergather items in Snakemake scatter/gather?
I'm trying out Snakemake's scatter/gather inbuilts but am stumbling over how to get the number of total splits configured.
The documentation doesn't mention how I can access that variable as defined in the workflow or passed through CL... | How to get the number of total scattergather items in Snakemake scatter/gather? | I'm trying out Snakemake's scatter/gather inbuilts but am stumbling over how to get the number of total splits configured.
The documentation doesn't mention how I can access that variable as defined in the workflow or passed through CLI.
Docs say I should define a scattergather directive:
scattergather:
split=8
Bu... | [
"There is a possibility of accessing specific setting via workflow internal property ._scatter:\nscattergather:\n split=8\n\n# downstream rule can refer to the python variable\nrule split:\n input: \"input.txt\"\n output: scatter.split(\"splitted/{scatteritem}.txt\")\n params: split_total = workflow._sc... | [
1
] | [] | [] | [
"bioinformatics",
"python",
"snakemake"
] | stackoverflow_0074340191_bioinformatics_python_snakemake.txt |
Q:
Pivot this table in pandas
I have this data here, image follows:
I need to pivot the table, the expected output is:
Description From To 2021-11-01
A A X VALUE COLUMN
B B P VALUE COLUMN
C D T VALUE COLUMN
I already tried
final_data.pivot_table(... | Pivot this table in pandas | I have this data here, image follows:
I need to pivot the table, the expected output is:
Description From To 2021-11-01
A A X VALUE COLUMN
B B P VALUE COLUMN
C D T VALUE COLUMN
I already tried
final_data.pivot_table(index=[['Description', 'From', '... | [
"The issue likely comes from the nested list used as value of the index parameter.\nUse a simple list:\nfinal_data.pivot_table(index=['Description', 'From', 'To'], columns='Date', values='Value', aggfunc=len).reset_index()\n\n"
] | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074340536_pandas_python.txt |
Q:
AttributeError: 'Tensor' object has no attribute 'numpy'
How can I fix this error I downloaded this code from GitHub.
predicted_id = tf.multinomial(tf.exp(predictions), num_samples=1)[0][0].numpy()
throws the error
AttributeError: 'Tensor' object has no attribute 'numpy'
Please help me fix this!
I used:
sess = ... | AttributeError: 'Tensor' object has no attribute 'numpy' | How can I fix this error I downloaded this code from GitHub.
predicted_id = tf.multinomial(tf.exp(predictions), num_samples=1)[0][0].numpy()
throws the error
AttributeError: 'Tensor' object has no attribute 'numpy'
Please help me fix this!
I used:
sess = tf.Session()
with sess.as_default():
predicted_id =... | [
"I suspect the place where you copied the code from had eager execution enabled, i.e. had invoked tf.enable_eager_execution() at the start of the program.\nYou could do the same.\nUPDATE: Note that eager execution is enabled by default in TensorFlow 2.0. So the answer above applies only to TensorFlow 1.x\n",
"Sin... | [
95,
78,
26,
18,
9,
1,
1,
0,
0,
0
] | [] | [] | [
"attributeerror",
"numpy",
"python",
"tensor",
"tensorflow"
] | stackoverflow_0052357542_attributeerror_numpy_python_tensor_tensorflow.txt |
Q:
Calculator not working if you enter a letter instead of a number
My Calculator is half working. I really put my brain in it but I cant figure out why its not working. Can someone help me?
number1 = input("Enter first number: ")
number2 = input("Enter second number: ")
operator = input("Enter the operation characte... | Calculator not working if you enter a letter instead of a number | My Calculator is half working. I really put my brain in it but I cant figure out why its not working. Can someone help me?
number1 = input("Enter first number: ")
number2 = input("Enter second number: ")
operator = input("Enter the operation character: ")
result = number1 + operator + number2
if operator == '+':
r... | [
"You have lines like these:\nif operator == '+':\n result = int(number1) + int(number2)\n\nBefore lines like these:\nif number1.isdigit() == True:\n print (result)\nelif number2.isdigit() == True:\n print(result)\nelse:\n print(\"Enter a number.\")\n\nSo, if operater is indeed a +, Python will try to ev... | [
0,
0,
0
] | [] | [] | [
"calculator",
"if_statement",
"python"
] | stackoverflow_0074340280_calculator_if_statement_python.txt |
Q:
Tweepy .get_me() error when using OAuth 2.0 User Auth flow with PKCE
I'm trying to get an authenticated user's Twitter ID and Twitter username via the Tweepy package. With authentication through the OAuth 2.0 flow (using a Django view). I've been able to create an instance of the Tweepy pkg's Client class using th... | Tweepy .get_me() error when using OAuth 2.0 User Auth flow with PKCE | I'm trying to get an authenticated user's Twitter ID and Twitter username via the Tweepy package. With authentication through the OAuth 2.0 flow (using a Django view). I've been able to create an instance of the Tweepy pkg's Client class using the OAuth 2.0 User Context flow, but when I use the .get_me() method on it, ... | [
"This issue was solved for me by a Contributor to the project, Harmon758, here.\nThe solution required two things. First, setting the user_auth parameter to False when calling the .get_me() method. This must be done because the function defaults to OAuth 1.0 if not.\nAnd then second, to get around the 401 unauthori... | [
0
] | [] | [] | [
"django",
"oauth_2.0",
"python",
"tweepy",
"twitter_oauth"
] | stackoverflow_0074331503_django_oauth_2.0_python_tweepy_twitter_oauth.txt |
Q:
Discord channel members only returns one member?
I am running a bot on a test server. There are currently three members in the channel (member_count of 3), but it only returns one member. This member is the Bot.
The code:
import discord
from discord.ext import commands
TOKEN = "<Token>"
CHANNEL_ID = 1234
@clien... | Discord channel members only returns one member? | I am running a bot on a test server. There are currently three members in the channel (member_count of 3), but it only returns one member. This member is the Bot.
The code:
import discord
from discord.ext import commands
TOKEN = "<Token>"
CHANNEL_ID = 1234
@client.event
async def on_ready():
channel = client.get... | [
"Discord recently changed their bot api, which may be responsible for what you're seeing.\nThe good news is that the fix is reasonably easy, you just need to enable the \"Server Members Intent\" in your bot's admin page. Follow the instructions here.\n",
"Try to looping through the channel.members\nFor example:\n... | [
6,
0,
0,
0
] | [] | [] | [
"discord.py",
"python"
] | stackoverflow_0064330906_discord.py_python.txt |
Q:
output_shape of custom keras layer is None (or cannot be determined automatically)
I am building a custom Keras layer that it is essentially the softmax function with a base parameter which is trainable. While the layer works on its own, when placed inside a sequential model, model.summary() determines its output ... | output_shape of custom keras layer is None (or cannot be determined automatically) | I am building a custom Keras layer that it is essentially the softmax function with a base parameter which is trainable. While the layer works on its own, when placed inside a sequential model, model.summary() determines its output shape as None and model.fit() raises a presumably linked exception:
ValueError: as_list... | [
"This doesn't directly solves the issue, rather side-stepping it: Instead of using squeeze and expand_dims, the former of which seems to be problematic for Tensorflow to keep track of, we use keepdims=True in the summation to keep the axes aligned correctly for the softmax denominator.\ndef call(self, inputs):\n ... | [
2,
1,
0
] | [] | [] | [
"keras",
"python",
"tensorflow"
] | stackoverflow_0074339733_keras_python_tensorflow.txt |
Q:
What is faster, scipy fsolve vs root?
I am trying to find the root of a function. I have used fsolve in the past but as my data sets get larger, it seems to get more inconsistent (--> n = 187). Now I am looking for alternatives and have found scipy.root. I don't understand what the difference is between the two, a... | What is faster, scipy fsolve vs root? | I am trying to find the root of a function. I have used fsolve in the past but as my data sets get larger, it seems to get more inconsistent (--> n = 187). Now I am looking for alternatives and have found scipy.root. I don't understand what the difference is between the two, and which one is better in my scenario.
I am... | [
"As @Bob suggests, step 1 must be to vectorise your inner function. After that, to your main question: it's not the right thing to ask, because\n\nfsolve is just a wrapper around the hybr algorithm, which is already provided as one option in root; and\nworry about correctness before performance.\n\nIt's almost cert... | [
0
] | [] | [] | [
"optimization",
"performance",
"python",
"scipy"
] | stackoverflow_0050786498_optimization_performance_python_scipy.txt |
Q:
Number doesn't seem to multiply
import random
money=int(0) # money starts at 0 always
bet=int(input("enter a bet.")) # user inputs a bet.
winningnumber=(random.randint(0,30)) # chooses random integer from 0 - 30, stores it as variable winningnumber
number = int(input("Pick a number 0-30"))
if number % 2 == 0: #ch... | Number doesn't seem to multiply | import random
money=int(0) # money starts at 0 always
bet=int(input("enter a bet.")) # user inputs a bet.
winningnumber=(random.randint(0,30)) # chooses random integer from 0 - 30, stores it as variable winningnumber
number = int(input("Pick a number 0-30"))
if number % 2 == 0: #checks if number is divisible by 2
... | [
"You have three different if-else blocks. All three do different things to money if their respective conditions evaluate to True. However, if the last if-else block evaluates False, then regardless of what happened in the previous if-else blocks, the code in the final else block will run. That code sets money back ... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074340534_python.txt |
Q:
How to add field variables from the HomePage to a stream StructBlock
Hi i have a doubt around how can i show info from the model page onto a block, specifically, a structblock.
On my homepage model i have multiple charfields, where i store the link of the social media of the website, and i wish to know how can i p... | How to add field variables from the HomePage to a stream StructBlock | Hi i have a doubt around how can i show info from the model page onto a block, specifically, a structblock.
On my homepage model i have multiple charfields, where i store the link of the social media of the website, and i wish to know how can i print these links inside the template of a structblock on my streams, addit... | [
"So a couple of things. In your template footer_plus.html, self is the StructBlock so it won't have a facebook_link. Right now you are only storing that information on instances of the HomePage model. If you somehow put FooterPlus on your homepage instance, you could probably reference it as page.facebook_link.\nBu... | [
0
] | [] | [] | [
"django",
"python",
"wagtail"
] | stackoverflow_0074340620_django_python_wagtail.txt |
Q:
Getting foreign key instead of relationship table in marshmallow_sqlalchemy schema
I have a flask-sqlalchemy table composed of a relationship with 4 other tables as follows:
office_cardgroups = db.Table('office_cardgroups',
db.Column('officedata_id', db.Integer, db.ForeignKey('officed... | Getting foreign key instead of relationship table in marshmallow_sqlalchemy schema | I have a flask-sqlalchemy table composed of a relationship with 4 other tables as follows:
office_cardgroups = db.Table('office_cardgroups',
db.Column('officedata_id', db.Integer, db.ForeignKey('officedata.id')),
db.Column('cardgroups_id', db.Integer, db.Foreig... | [
"I just ran into this too thinking that include_relationships = True would automatically populate the nested fields but also had to define the relationships in the Schema (as you've done with OfficeDataSchema) but I think the nested fields need to be part of the OfficeDataSchema itself rather than Meta (one indenta... | [
1
] | [] | [] | [
"flask_marshmallow",
"flask_sqlalchemy",
"marshmallow",
"marshmallow_sqlalchemy",
"python"
] | stackoverflow_0071720473_flask_marshmallow_flask_sqlalchemy_marshmallow_marshmallow_sqlalchemy_python.txt |
Q:
how to convert rle format of label-studio to black and white image masks
Given array of values as follows: full array here
[{"format": "rle", "rle": [0, 18, 192, 0, 57, 27, 255, 255, 255, 0, 259, 96, 17, 192, 97, 255, 248, 239, 227, 16, 2....., 255, 142, 3, 130, 21, 128, 0], "brushlabels": ["crack"], "original_wid... | how to convert rle format of label-studio to black and white image masks | Given array of values as follows: full array here
[{"format": "rle", "rle": [0, 18, 192, 0, 57, 27, 255, 255, 255, 0, 259, 96, 17, 192, 97, 255, 248, 239, 227, 16, 2....., 255, 142, 3, 130, 21, 128, 0], "brushlabels": ["crack"], "original_width": 640, "original_height": 480}]
how can i convert to get image.png?
| [
"You can use the np.reshape() method to reshape the array into the image's original dimensions:\nimport cv2\nimport numpy as np\n\ndata = [{\"format\": \"rle\", \"rle\": [255, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 255, 0, 0, 0, 255, 0, 0], \"brushlabels\": [\"crack\"], \"original_width\": 2, \"original_height\": 3}]\n\n#... | [
0
] | [] | [] | [
"image_processing",
"opencv",
"python"
] | stackoverflow_0074339154_image_processing_opencv_python.txt |
Q:
AttributeError: module 'config' has no attribute 'TWITTER_ACCESS_TOKEN_SECRET'. Did you mean: 'TWITTER_ACCESS_TOKEN'?
import streamlit as st
import pandas as pd
import numpy as np
import requests
import tweepy
import config
import psycopg2
import psycopg2.extras
import plotly.graph_objects as go
auth = tweepy.OAu... | AttributeError: module 'config' has no attribute 'TWITTER_ACCESS_TOKEN_SECRET'. Did you mean: 'TWITTER_ACCESS_TOKEN'? | import streamlit as st
import pandas as pd
import numpy as np
import requests
import tweepy
import config
import psycopg2
import psycopg2.extras
import plotly.graph_objects as go
auth = tweepy.OAuthHandler(config.TWITTER_CONSUMER_KEY,
config.TWITTER_CONSUMER_SECRET)
auth.set_access_token(con... | [
"The config module that you are attempting to import and read off of is not what you want.\nTWITTER_CONSUMER_KEY and TWITTER_CONSUMER_SECRET are not constants that you can get from a module. These are values that you must input yourself. There is perhaps a piece of code missing at the start of your application that... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074340170_python.txt |
Q:
Find the missing starting number of shuffled cumsum series
a and b are two arrays of floats of length n each. a can have both negative and positive entries.
b is cumulative sum of a.
b[0] != a[0]. In fact, b[0] = a[0] + k
Both a and b are shuffled such that the relative order between them is maintained, i.e., if s... | Find the missing starting number of shuffled cumsum series |
a and b are two arrays of floats of length n each. a can have both negative and positive entries.
b is cumulative sum of a.
b[0] != a[0]. In fact, b[0] = a[0] + k
Both a and b are shuffled such that the relative order between them is maintained, i.e., if say a[0] becomes a[6] then b[0] will become b[6] and so on.
Can ... | [
"We have:\nb = np.cumsum(a) + k\n\nWe can compute b-a to get the previous elements of the sum. Thus the only element of b-a that does not belong to b indicates the position of the start.\nAs we are working with floating point numbers, we need a function to match floating point values. I used isin_tolerance that is ... | [
0
] | [] | [] | [
"algorithm",
"python",
"sorting"
] | stackoverflow_0074340560_algorithm_python_sorting.txt |
Q:
How to reorder the matrix
Does anyone could tell me how to reorder the matrix:
[[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15]]
To:
[[15, 10, 5],
[14, 9, 4],
[13, 8, 3],
[12, 7, 2],
[11, 6, 1]]
A:
I'd suggest using numpy, like so:
import numpy as np
matrix = np.array([[1, 2, 3, 4, 5],
... | How to reorder the matrix | Does anyone could tell me how to reorder the matrix:
[[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15]]
To:
[[15, 10, 5],
[14, 9, 4],
[13, 8, 3],
[12, 7, 2],
[11, 6, 1]]
| [
"I'd suggest using numpy, like so:\nimport numpy as np\n\nmatrix = np.array([[1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15]])\n\ntransformed_matrix = matrix[::-1].T[::-1]\n\n\n# array([[15, 10, 5],\n# [14, 9, 4],\n# [13, 8, 3],\n# [12, 7, ... | [
2,
2,
0
] | [] | [] | [
"matrix",
"numpy",
"python"
] | stackoverflow_0074340785_matrix_numpy_python.txt |
Q:
Automatically tuning the batch size by catching out of memory errors
I would like my application to automatically find the maximum batch size possible so I set up a binary search that catches OOM exceptions like this:
min_batch_size = 3072
max_batch_size = 16384
min_range = 512 # Exit when the search range is sma... | Automatically tuning the batch size by catching out of memory errors | I would like my application to automatically find the maximum batch size possible so I set up a binary search that catches OOM exceptions like this:
min_batch_size = 3072
max_batch_size = 16384
min_range = 512 # Exit when the search range is smaller than this.
sample_iterations = 5
while max_batch_size - min_batch_siz... | [
"Try writing it as a separate script that writes the final batch size to a file.\nAfter the script ends, I think the GPU would reset properly and you could read that file to get the desired batch size.\n"
] | [
0
] | [] | [] | [
"python",
"tensorflow"
] | stackoverflow_0053820713_python_tensorflow.txt |
Q:
i want to use only 6 months of every year to work with in dataframe
i have dates in dataframe from 2015-01-01 00:00:00 to 2022-09-05 23:59:00
I want to extract all the data inbetween 04-01 00:00:00 and 10-31 23:59:59
i tried
`
filtered_df = df.loc[(df['date'] >= '04-01 00:00:00')
& (df['date... | i want to use only 6 months of every year to work with in dataframe | i have dates in dataframe from 2015-01-01 00:00:00 to 2022-09-05 23:59:00
I want to extract all the data inbetween 04-01 00:00:00 and 10-31 23:59:59
i tried
`
filtered_df = df.loc[(df['date'] >= '04-01 00:00:00')
& (df['date'] < '10-31 23:59:59')]
filtered_df.head()
`it says
TypeError: Invalid c... | [
"df[(df.date.dt.month>=4) & (df.date.dt.month<=10)]\n\nKey point is .dt that allows datetime specific accessor (a little bit like .str allows string specific methods.\n"
] | [
1
] | [] | [] | [
"dataframe",
"date",
"extract",
"pandas",
"python"
] | stackoverflow_0074340640_dataframe_date_extract_pandas_python.txt |
Q:
Why pool.imap() does not even execute one task at Jupyter Notebook?
Even a very simple piece of code does not return anything but always keeps running.
pool = mp.Pool(processes=10)
def add1(x):
return x + 1
for x in pool.imap(add1, [1,2,3]):
print(x)
pool.close()
And any other operations can not be done i... | Why pool.imap() does not even execute one task at Jupyter Notebook? | Even a very simple piece of code does not return anything but always keeps running.
pool = mp.Pool(processes=10)
def add1(x):
return x + 1
for x in pool.imap(add1, [1,2,3]):
print(x)
pool.close()
And any other operations can not be done if it's running, including shutting down the kernel!
| [
"Multiprocessing only works reliably when you're doing it from a file. If you are on a Mac or Windows, multiprocessing starts a new Python process. That Python process reads the file from which it was started in order to know its own code, but doesn't execute the __main__ code. It then executes what it was to exe... | [
0
] | [] | [] | [
"jupyter_notebook",
"multiprocessing",
"python"
] | stackoverflow_0074332923_jupyter_notebook_multiprocessing_python.txt |
Q:
How do I get the name of the rows from the index of a data frame?
Consider a data frame with row names that aren't a column of their own per se, such as the following:
X Y
Row 1 0 5
Row 2 8 1
Row 3 3 0
How would I extract the name of these rows as a list, if I have their index?
For example, it w... | How do I get the name of the rows from the index of a data frame? | Consider a data frame with row names that aren't a column of their own per se, such as the following:
X Y
Row 1 0 5
Row 2 8 1
Row 3 3 0
How would I extract the name of these rows as a list, if I have their index?
For example, it would look something like:
function_name(dataframe[indices])
> ['Row 1'... | [
"df.index \n\noutputs the row names as pandas Index object. \n\nlist(df.index) \n\ncasts to a list.\n\ndf.index['Row 2':'Row 5'] \n\nsupports label slicing similar to columns.\n\n",
"this seems to work fine :\ndataframe.axes[0].tolist()\n\n",
"If you want to pull out only the index values for certain integer-b... | [
108,
6,
5,
4,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0026640145_dataframe_pandas_python.txt |
Q:
How do I do a search in the google lens window from the url?
search from url
if a normal search can be done like this
www.google.com/search?q=search_here
how do i search here !?
search from url with picture url in google lens
enable search with image url, from the url
in the same place that appears in the image
... | How do I do a search in the google lens window from the url? | search from url
if a normal search can be done like this
www.google.com/search?q=search_here
how do i search here !?
search from url with picture url in google lens
enable search with image url, from the url
in the same place that appears in the image
help me pls... TnT
| [
"Use this link to search image with Google Lens:\nhttps://lens.google.com/uploadbyurl?url=<image_url>\n\nexample: https://lens.google.com/uploadbyurl?url=https://stackoverflow.design/assets/img/logos/so/logo-stackoverflow.png\n",
"you can use this link: \"https://www.google.com/searchbyimage?image_url=https://www... | [
1,
0
] | [] | [] | [
"html",
"python",
"url"
] | stackoverflow_0074272887_html_python_url.txt |
Q:
create separate dataframes from single time series dataframe based on value in one column
I have a time series dataframe (date is index) with 10 columns of values. One column is an 'indicator' column that is 0 or 1. When the indicator = 1 for a given set of dates/rows I'd like to create a separate dataframe for th... | create separate dataframes from single time series dataframe based on value in one column | I have a time series dataframe (date is index) with 10 columns of values. One column is an 'indicator' column that is 0 or 1. When the indicator = 1 for a given set of dates/rows I'd like to create a separate dataframe for that group of rows and save it as a csv. Then for the next group of rows where 'indicator' = 1 in... | [
"You can use:\n# which rows are to keep?\nm = df['indicator'].eq(1)\n\n# group by successive 1s\ndfs = [g for _,g in df[m].groupby((~m).cumsum())]\n\nprint(dfs)\n\n"
] | [
0
] | [] | [] | [
"group_by",
"pandas",
"python"
] | stackoverflow_0074340858_group_by_pandas_python.txt |
Q:
I am having trouble displaying images for prediction data. ValueError: Expected image array to have rank 3 (single image). Got array with shape: ()
Here I am trying to display the prediction data and the image along with it. But I am struggling quite allot to solve this. I am expecting this to show a random image ... | I am having trouble displaying images for prediction data. ValueError: Expected image array to have rank 3 (single image). Got array with shape: () | Here I am trying to display the prediction data and the image along with it. But I am struggling quite allot to solve this. I am expecting this to show a random image from the prediction and show if it a normal xray or the other.
I have tried allot to show this data accurately. sometimes I have succeeded in showing the... | [
"you can create dataset and use dataset.shuffle() for random input, please follow the templates that are easy. You can do more experiments by adding\n\nRandom sequences\nImage augmentations\nMultiple dataset, larger input, different image types\nMasking or other techniques\n\n\nSample: dataset input shuffles\n\ndat... | [
0
] | [] | [] | [
"dataset",
"keras",
"prediction",
"python",
"tensorflow"
] | stackoverflow_0074340574_dataset_keras_prediction_python_tensorflow.txt |
Q:
How do I remove line breaks and only return characters between two substrings in a list?
If I have a string like:
query = """
SELECT
alias.column_one,
alias.column_two,
alias.column_three
FROM
table_name
"""
How do I just return the characters between "SELECT" and "FROM" in a list so I have a list lik... | How do I remove line breaks and only return characters between two substrings in a list? | If I have a string like:
query = """
SELECT
alias.column_one,
alias.column_two,
alias.column_three
FROM
table_name
"""
How do I just return the characters between "SELECT" and "FROM" in a list so I have a list like below which also accounts for line breaks:
columns = ['alias.column_one', 'alias.column_two'... | [
"You could try this:\nquery = \"\"\"\nSELECT\n alias.column_one,\n alias.column_two,\n alias.column_three\nFROM\n table_name\n\"\"\"\n\ncolumns = query.split('\\n') # split the string at every line break - '\\n'\ncolumns = [column.strip() for column in columns] # strip out the leading spaces\n\n# take the s... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074340724_python.txt |
Q:
Why does this print everything on one line? I want each list to print one it's own line separated by a '|'
lcolhead = ['ID', 'Name', 'Email']
lrow1 = [1, 'Jane Doe', 'janedoe@doemail.com']
lrow2 = [2, 'Jake Doe', 'jakedoe@doemail.com']
lrow3 = [3, 'Jane Fox', 'janefox@foxmail.com']
ltable1 = [lcolhead, lrow1, lro... | Why does this print everything on one line? I want each list to print one it's own line separated by a '|' | lcolhead = ['ID', 'Name', 'Email']
lrow1 = [1, 'Jane Doe', 'janedoe@doemail.com']
lrow2 = [2, 'Jake Doe', 'jakedoe@doemail.com']
lrow3 = [3, 'Jane Fox', 'janefox@foxmail.com']
ltable1 = [lcolhead, lrow1, lrow2, lrow3]
for row in ltable1:
for item in row:
print(item, end=' | ')
output is each value on a ... | [
"Using your solution, adding a simple print() statement in the outer loop fixes it:\nlcolhead = ['ID', 'Name', 'Email']\nlrow1 = [1, 'Jane Doe', 'janedoe@doemail.com']\nlrow2 = [2, 'Jake Doe', 'jakedoe@doemail.com']\nlrow3 = [3, 'Jane Fox', 'janefox@foxmail.com']\n\nltable1 = [lcolhead, lrow1, lrow2, lrow3]\n\nfor ... | [
1
] | [
"for row in ltable1:\n print( \" | \".join( row) + \" | \")\n\nBut I'm questioning the utility of the last vertical bar.\n"
] | [
-1
] | [
"list",
"nested_lists",
"python"
] | stackoverflow_0074340744_list_nested_lists_python.txt |
Q:
Is it possible to make a timeline in TKinter and Matplotlib similar to excel?
I wish to make a scrolling timeline for an applet using tkinter. I can currently create charts using matplotlib and update these dynamically, but I want to be able to scroll along this by passing in data about the start and end date, sim... | Is it possible to make a timeline in TKinter and Matplotlib similar to excel? | I wish to make a scrolling timeline for an applet using tkinter. I can currently create charts using matplotlib and update these dynamically, but I want to be able to scroll along this by passing in data about the start and end date, similar to the excel image I have attached.
I have tried using timeline tools built i... | [
"Tkinter, matplotlib, and ttkwidgets don't have a built-in timeline widget exactly like you want. However, tkinter has all of the basic building blocks to be able to do it. It's just a matter of putting all of the widgets together in a class.\nHere's something I threw together. It's not exactly production-ready, bu... | [
0
] | [] | [] | [
"matplotlib",
"python",
"tkinter",
"ttkwidgets"
] | stackoverflow_0074340578_matplotlib_python_tkinter_ttkwidgets.txt |
Q:
No results when implementing NLTK recursive descent parser
I am trying to implement a NLTK recursive descent parser using a grammar I constructed. When I run the code below, it does not print anything and the result is 'None'.
Why is this happening?
from nltk import Nonterminal, nonterminals, Production, CFG
from ... | No results when implementing NLTK recursive descent parser | I am trying to implement a NLTK recursive descent parser using a grammar I constructed. When I run the code below, it does not print anything and the result is 'None'.
Why is this happening?
from nltk import Nonterminal, nonterminals, Production, CFG
from nltk.parse import RecursiveDescentParser
nt1 = Nonterminal('NP'... | [
"You're not getting any results because your grammar isn't correct/functional. I've posted a solution below that works with the sentences you have. Please note that the solution does not use a comprehensive grammar so you'll have to add more rules/cases to suit your needs. But first, I want to explain the gist of t... | [
1
] | [] | [] | [
"nlp",
"nltk",
"parsing",
"python",
"recursion"
] | stackoverflow_0074339800_nlp_nltk_parsing_python_recursion.txt |
Q:
removing the last comma and print the list inside square bracket
# Program to display the Fibonacci sequence up to n-th term
nterms = int(input("How many Fibonacci numbers would you like to generate? "))
# first two terms
n1, n2 = 1, 1
count = 0
# check if the number of terms is valid
if nterms == 0:
print(f... | removing the last comma and print the list inside square bracket | # Program to display the Fibonacci sequence up to n-th term
nterms = int(input("How many Fibonacci numbers would you like to generate? "))
# first two terms
n1, n2 = 1, 1
count = 0
# check if the number of terms is valid
if nterms == 0:
print(f'The first 0 Fibonacci numbers are [].')
elif nterms == 1:
print(f... | [
"You could just store your result in list and print it on the end. With such approach your program could be simplified!\n# Program to display the Fibonacci sequence up to n-th term\n\nnterms = int(input(\"How many Fibonacci numbers would you like to generate? \"))\n\n# first two terms\nnumbers = [1,1]\ncount = 2\n\... | [
1,
1
] | [] | [] | [
"fibonacci",
"python"
] | stackoverflow_0074341024_fibonacci_python.txt |
Q:
User has no customer
In a Django project, i have two apps; ecommerce and users. Ecommerce app has situation where logged in users are expected to be customers and they can add to cart. Non logged in users can as well add to cart. In the users app, new users are to register, logged in and be redirected to the store... | User has no customer | In a Django project, i have two apps; ecommerce and users. Ecommerce app has situation where logged in users are expected to be customers and they can add to cart. Non logged in users can as well add to cart. In the users app, new users are to register, logged in and be redirected to the store page(store.html).
The new... | [
"Yo must create the Customer with the User you are trying to access the store.\n"
] | [
0
] | [] | [] | [
"authentication",
"django",
"html",
"multiple_users",
"python"
] | stackoverflow_0070499995_authentication_django_html_multiple_users_python.txt |
Q:
WHY does multiprocessing not work properly in `__main__.py`
The following is the first example in "multiprociessing" page of Python doc.
from multiprocessing import Pool
def f(x):
return x*x
if __name__ == '__main__':
with Pool(5) as p:
print(p.map(f, [1, 2, 3]))
I have a project root with direc... | WHY does multiprocessing not work properly in `__main__.py` | The following is the first example in "multiprociessing" page of Python doc.
from multiprocessing import Pool
def f(x):
return x*x
if __name__ == '__main__':
with Pool(5) as p:
print(p.map(f, [1, 2, 3]))
I have a project root with directory:
foo
-- __main__.py
-- file.py
Copy paste the above example... | [
"Multiprocessing needs __file__ in order to work. Multiprocessing creates a new Python process that reads the contents of __file__, and it expects that that file contains what it needs to know in order to execute the command it has been given.\n"
] | [
0
] | [] | [] | [
"multiprocessing",
"python",
"python_3.x"
] | stackoverflow_0074341059_multiprocessing_python_python_3.x.txt |
Q:
Request in Flask from a Form in HTML is returning None, what did i do wrong?
i want to be able to get the the user name from a form and append it to a confirmation page but it keeps returning none
below is the html form
<form name="sentMessage" id="contactForm" action="{{ url_for('contact') }}" method="post" noval... | Request in Flask from a Form in HTML is returning None, what did i do wrong? | i want to be able to get the the user name from a form and append it to a confirmation page but it keeps returning none
below is the html form
<form name="sentMessage" id="contactForm" action="{{ url_for('contact') }}" method="post" novalidate>
<div class="control-group">
<div class="form-group floating-label-for... | [
"The template as defined, when rendered through the /contact endpoint, the following line (unrelated attributes replaced with ellipsis):\n<form ... action=\"{{ url_for('contact') }}\" method=\"post\" ...>\n\nRenders to\n<form ... action=\"/contact\" method=\"post\" ...>\n\nSubmitting the form will again hit the sam... | [
1
] | [] | [] | [
"css",
"flask",
"html",
"python"
] | stackoverflow_0074340998_css_flask_html_python.txt |
Q:
DatabaseError: DPI-1047: Cannot locate a 64-bit Oracle Client library (Running cx_Oracle in anaconda python)
I am trying to connect to an oracle database in a jupyter notebook environment using the cx_Oracle library. I've set the settings and configurations then tried to start the connection with cx_Oracle.connect... | DatabaseError: DPI-1047: Cannot locate a 64-bit Oracle Client library (Running cx_Oracle in anaconda python) | I am trying to connect to an oracle database in a jupyter notebook environment using the cx_Oracle library. I've set the settings and configurations then tried to start the connection with cx_Oracle.connect but am getting this error:
DatabaseError: DPI-1047: Cannot locate a 64-bit Oracle Client library
I've found solu... | [
"You may also change to python-oracledb, which Oracle client is not required.\npython -m pip install oracledb\n\n",
"You definitely need to install an Oracle client library for it to work. Your issue is just how to get cx_oracle in your conda env to be able to locate the drivers on your computer.\nPutting the dll... | [
1,
0
] | [] | [] | [
"cx_oracle",
"oracle",
"python"
] | stackoverflow_0072015723_cx_oracle_oracle_python.txt |
Q:
Pytorch newbie, non linear regression not converging
First im new to pytorh and DL, I want to create a simple non linear regression model, but apparently is not converging, i tried to change some hyperparams without sucess. This is the code, i guess im making wrong something obvius.
import torch
x1 =... | Pytorch newbie, non linear regression not converging | First im new to pytorh and DL, I want to create a simple non linear regression model, but apparently is not converging, i tried to change some hyperparams without sucess. This is the code, i guess im making wrong something obvius.
import torch
x1 = torch.arange(1,600,1, dtype=torch.float32).view(-1,1)
... | [
"Possible solutions:\n\ninput normalization\nbatch normalization\ndecrease learning rate\nchange MSELoss to L1Loss (more stable with large errors)\nchange optimizer, e.g. use Adam\netc\n\nAn example:\nimport torch\n\nx1 = torch.arange(1,600, 1, dtype=torch.float32).view(-1, 1)\ny1 = x1*x1\n\nmodel = torch.nn.Sequen... | [
1
] | [] | [] | [
"deep_learning",
"python",
"pytorch"
] | stackoverflow_0074338863_deep_learning_python_pytorch.txt |
Q:
Python: Stack bar chart, how can I stack by year from column?
Hi all am trying to create a stacked bar chart that shows every day of the Year (1 through to 365), with the stacks representing the Year.
My data looks like this:
I have put together the following which works for all Days/Years:
daychart = data.groupb... | Python: Stack bar chart, how can I stack by year from column? | Hi all am trying to create a stacked bar chart that shows every day of the Year (1 through to 365), with the stacks representing the Year.
My data looks like this:
I have put together the following which works for all Days/Years:
daychart = data.groupby(['Day'], as_index=False, sort=False).agg(Count=('Day','size'))
pl... | [
"Try query\nb2019 = data.query('Year == 2019').groupby('Day', as_index=False, sort=False).agg(Count=('Day','size'))\nb2020 = data.query('Year == 2020').groupby('Day', as_index=False, sort=False).agg(Count=('Day','size'))\n\n"
] | [
1
] | [] | [] | [
"bar_chart",
"matplotlib",
"python"
] | stackoverflow_0074340594_bar_chart_matplotlib_python.txt |
Q:
How to iterate over columns of pandas dataframe to run regression
I'm sure this is simple, but as a complete newbie to python, I'm having trouble figuring out how to iterate over variables in a pandas dataframe and run a regression with each.
Here's what I'm doing:
all_data = {}
for ticker in ['FIUIX', 'FSAIX', 'F... | How to iterate over columns of pandas dataframe to run regression | I'm sure this is simple, but as a complete newbie to python, I'm having trouble figuring out how to iterate over variables in a pandas dataframe and run a regression with each.
Here's what I'm doing:
all_data = {}
for ticker in ['FIUIX', 'FSAIX', 'FSAVX', 'FSTMX']:
all_data[ticker] = web.get_data_yahoo(ticker, '1/1... | [
"for column in df:\n print(df[column])\n\n",
"You can use iteritems():\nfor name, values in df.iteritems():\n print('{name}: {value}'.format(name=name, value=values[0]))\n\n",
"This answer is to iterate over selected columns as well as all columns in a DF.\ndf.columns gives a list containing all the colum... | [
525,
120,
54,
22,
17,
10,
7,
4,
0,
0
] | [
"assuming X-factor, y-label (multicolumn):\ncolumns = [c for c in _df.columns if c in ['col1', 'col2','col3']] #or '..c not in..'\n_df.set_index(columns, inplace=True)\nprint( _df.index)\n\nX, y = _df.iloc[:,:4].values, _df.index.values\n\n"
] | [
-1
] | [
"pandas",
"python",
"statsmodels"
] | stackoverflow_0028218698_pandas_python_statsmodels.txt |
Q:
how to divide a row with the previous one and that the values remain in a new column?
My problem is that I have time series, and I need to create a new column that gives me the natural logarithm of today's price divided by yesterday's price, and that these values are in a new column
#Accion1['Rentabilidad1'] = Acc... | how to divide a row with the previous one and that the values remain in a new column? | My problem is that I have time series, and I need to create a new column that gives me the natural logarithm of today's price divided by yesterday's price, and that these values are in a new column
#Accion1['Rentabilidad1'] = Accion1.apply(lambda row: np.log(Promedio), axis=1)
Accion1['Rentabilidad'] = np.log(Accion1['... | [
"I would grab all of the previous dates and save them to a separate list:\nfechas_anteriores = [x.strftime(\"%d-%m-%Y\") for x in Accion1[\"Fecha anterior\"]]\n\nThen I would create a new column called Promedio anterior using .loc, making reference to fechas_anteriores:\nAccion1[\"Promedio anterior\"] = [fecha[0] i... | [
0
] | [] | [] | [
"finance",
"numpy",
"pandas",
"python",
"scikit_learn"
] | stackoverflow_0074340629_finance_numpy_pandas_python_scikit_learn.txt |
Q:
The right way to round pandas.DataFrame?
I want round pandas.DataFrame.
Here is what i have tried so far:
import pandas as pd
data = pd.DataFrame([1.4,2.5,3.8,4.4,5.6],[6.2,7.6,8.8,9.1,0])
print(round(data))
But when i run this code, i get the following error:
Traceback (most recent call last):
File "C:\Users\*... | The right way to round pandas.DataFrame? | I want round pandas.DataFrame.
Here is what i have tried so far:
import pandas as pd
data = pd.DataFrame([1.4,2.5,3.8,4.4,5.6],[6.2,7.6,8.8,9.1,0])
print(round(data))
But when i run this code, i get the following error:
Traceback (most recent call last):
File "C:\Users\*****\Documents\*****\******\****.py", line 3, ... | [
"first, you may want to change the definition of your data frame, something like:\ndata = pd.DataFrame([[1.4,2.5,3.8,4.4,5.6],[6.2,7.6,8.8,9.1,0]]).T\n\nwhich results this:\n 0 1\n0 1.4 6.2\n1 2.5 7.6\n2 3.8 8.8\n3 4.4 9.1\n4 5.6 0.0\n\nor:\ndata = pd.DataFrame({'A':[1.4,2.5,3.8,4.4,5.6],'B':[6.2,7... | [
14,
6,
0
] | [] | [] | [
"pandas",
"python",
"rounding"
] | stackoverflow_0020455163_pandas_python_rounding.txt |
Q:
Pandas data frame grouping by loses the grouping function
I have a pandas dataframe (glob_df) which I am trying to group by by the lga_abbreviated_name field as below:
>>> glob_df.dtypes
lga_abbreviated_name object
counts int64
update_date_time_date object
dtype: object
>>> dg=glob_df.gro... | Pandas data frame grouping by loses the grouping function | I have a pandas dataframe (glob_df) which I am trying to group by by the lga_abbreviated_name field as below:
>>> glob_df.dtypes
lga_abbreviated_name object
counts int64
update_date_time_date object
dtype: object
>>> dg=glob_df.groupby('lga_abbreviated_name').aggregate({'counts':'sum'})
>>> dg... | [
"as_index = False\ndg=glob_df.groupby('lga_abbreviated_name', as_index=False).aggregate({'counts':'sum'})\n\n"
] | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074341117_pandas_python.txt |
Q:
VSCode Python error in importing modules from subdirectories
My project file structure is like this,
project/src/test/myscript.py
project/src/utils/file_utils.py
When I run myscript.py, which has from utils import file_utils, it gave me error:
ModuleNotFoundError: No module named 'utils'
Previously in Pycharm I... | VSCode Python error in importing modules from subdirectories | My project file structure is like this,
project/src/test/myscript.py
project/src/utils/file_utils.py
When I run myscript.py, which has from utils import file_utils, it gave me error:
ModuleNotFoundError: No module named 'utils'
Previously in Pycharm IDE I did not get this type of error (maybe due to _ init _.py), th... | [
"You could consider placing a .env file at the root of your project which adds your source directory to PYTHONPATH. i.e. something like\n>>> cat /project/.env\nPYTHONPATH=/project/src/\n>>>\n\nYour code will look a smidgen nicer without the explicit manipulation of sys.path.\nVSCode's usage of .env files is documen... | [
2,
0
] | [
"Unlike pycharm, vscode uses the workspace as the root directory to retrieve files. The first method you try is to write it in the launch.json file, which is applicable to debug rather than running it directly. You can use the following code to import:\nfrom src.utils import file_utils\n\n"
] | [
-1
] | [
"importerror",
"python",
"visual_studio_code"
] | stackoverflow_0074318121_importerror_python_visual_studio_code.txt |
Q:
python save image from url
I got a problem when I am using python to save an image from url either by urllib2 request or urllib.urlretrieve. That is the url of the image is valid. I could download it manually using the explorer. However, when I use python to download the image, the file cannot be opened. I use Mac... | python save image from url | I got a problem when I am using python to save an image from url either by urllib2 request or urllib.urlretrieve. That is the url of the image is valid. I could download it manually using the explorer. However, when I use python to download the image, the file cannot be opened. I use Mac OS preview to view the image. T... | [
"import requests\n\nimg_data = requests.get(image_url).content\nwith open('image_name.jpg', 'wb') as handler:\n handler.write(img_data)\n\n",
"A sample code that works for me on Windows:\nimport requests\n\nwith open('pic1.jpg', 'wb') as handle:\n response = requests.get(pic_url, stream=True)\n\n if not ... | [
174,
82,
29,
14,
5,
2,
1,
1,
1,
0
] | [] | [] | [
"download",
"image",
"python",
"urllib"
] | stackoverflow_0030229231_download_image_python_urllib.txt |
Q:
DRF filter/search return everything?
I'm currently doing self project inventory app and trying to implement filter and search.
what I've done
#views.py
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters
class ListInventories(generics.ListAPIView):
serializer_... | DRF filter/search return everything? | I'm currently doing self project inventory app and trying to implement filter and search.
what I've done
#views.py
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters
class ListInventories(generics.ListAPIView):
serializer_class = Inventory
filter_backends = [f... | [
"Cause of the error:\nclass ListInventories(generics.ListAPIView):\n\n serializer_class = Inventory\n \n # You are settings search filter here\n * filter_backends = [filters.SearchFilter]\n\n search_fields = ['name']\n \n # and overriding it here, that's why search is not working\n * filter_... | [
0,
0
] | [] | [] | [
"django",
"django_rest_framework",
"python"
] | stackoverflow_0074309079_django_django_rest_framework_python.txt |
Q:
Can I use method chaining to delete rows with a if-else condition?
Right now my df looks like this (I shorten it cause there are 20 rows).
import pandas as pd
df=pd.DataFrame({'Country': ["Uruguay", "Italy", "France"], 'Winner': ["Uruguay", "Italy", "France"]})
def f(row):
if row['Country'] in row['Winner']:... | Can I use method chaining to delete rows with a if-else condition? | Right now my df looks like this (I shorten it cause there are 20 rows).
import pandas as pd
df=pd.DataFrame({'Country': ["Uruguay", "Italy", "France"], 'Winner': ["Uruguay", "Italy", "France"]})
def f(row):
if row['Country'] in row['Winner']:
val = False
else:
val = True
return val
df["Aw... | [
"You need to remove the inplace argument.\ndf = df.drop(df[df[\"AwayTeam\"] == False].index).drop(\"AwayTeam\", axis=1)\n\nIf it's set to True, the drop method will do the operation inplace and return None, Which means that your method chain will evaluate like this,\ndf = None.drop(\"AwayTeam\", axis=1)\n\nWhen it'... | [
0
] | [] | [] | [
"dataframe",
"method_chaining",
"pandas",
"python"
] | stackoverflow_0074340960_dataframe_method_chaining_pandas_python.txt |
Q:
Panda's data frame filtering on rows that are empty
With Jupyter Notebook and Panda's I'm trying to filter 'NaN' values from a column in a dataframe.
I have uses the code you can see below.
empty_art = df.loc[df['Artikelnr.'] == 'NaN']
This does work when I am filtering for other values that are not empty.
For exa... | Panda's data frame filtering on rows that are empty | With Jupyter Notebook and Panda's I'm trying to filter 'NaN' values from a column in a dataframe.
I have uses the code you can see below.
empty_art = df.loc[df['Artikelnr.'] == 'NaN']
This does work when I am filtering for other values that are not empty.
For example leeg_art = df.loc[df['Artikelnr.'] == 'X99999'] work... | [
"df.loc[df['Artikelnr.'].isnull()]\n\n"
] | [
1
] | [] | [] | [
"dataframe",
"jupyter_notebook",
"pandas",
"python"
] | stackoverflow_0074341167_dataframe_jupyter_notebook_pandas_python.txt |
Q:
import "django.shortcuts" could not be resolved from sauce Pylance(reportMissingModuleSoucre)
[![import "django.shortcuts" could not be resolved from sauce Pylance(reportMissingModuleSoucre)
from django.shortcuts import render
# Create your views here.
def get_home(request):
return render(request,'home.html')... | import "django.shortcuts" could not be resolved from sauce Pylance(reportMissingModuleSoucre) | [![import "django.shortcuts" could not be resolved from sauce Pylance(reportMissingModuleSoucre)
from django.shortcuts import render
# Create your views here.
def get_home(request):
return render(request,'home.html')
i didnt try anything,i need some help
| [
"add the extra path virtual env - Django installed/lib/sitepackages to workspace of visual studio code in settings\nrefer this img - \n",
"You need to make sure you have selected the correct python interpreter (shortcuts \"Ctrl+shift+P\" and type \"Python: Select Interpreter\") which you have installed the packag... | [
0,
0
] | [] | [] | [
"django",
"python",
"visual_studio_code"
] | stackoverflow_0074318665_django_python_visual_studio_code.txt |
Q:
Both are almost same codes for House Robber III in leetcode but one is time limit exceed code whereas other is perfect solution to the question
The correct code is
class Solution:
def rob(self, root: Optional[TreeNode]) -> int:
def dfs(root):
if not root:
return [0,0]
... | Both are almost same codes for House Robber III in leetcode but one is time limit exceed code whereas other is perfect solution to the question | The correct code is
class Solution:
def rob(self, root: Optional[TreeNode]) -> int:
def dfs(root):
if not root:
return [0,0]
leftpair=dfs(root.left)
rightpair=dfs(root.right)
withroot=root.val+leftpair[1]+rightpair[1]
withoutroot=ma... | [
"The first version of dfs calls itself recursively twice, saving the results and reusing them. Here are the two recursive calls:\nleftpair=dfs(root.left)\nrightpair=dfs(root.right)\n\nThe second version of dfs calls itself recursively four times. Here are the four recursive calls, embedded in expressions:\nleft=r... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074341137_python.txt |
Q:
How do i make sure that when ever the user enter a number less than 0 or more than 300 it asks them to try again
How do i make sure that when ever the user enter a number less than 0 or more than 300 it asks them to try again. I have trouble with the code. My code works on the first score but the rest it keeps acc... | How do i make sure that when ever the user enter a number less than 0 or more than 300 it asks them to try again | How do i make sure that when ever the user enter a number less than 0 or more than 300 it asks them to try again. I have trouble with the code. My code works on the first score but the rest it keeps accepting values greater than 300 and less than 0. How would i be able to fix this issue without changing a big part of m... | [
"I think you can do something like this:\n\nI do not have all the same variables in this you have\n invalid = True\n while invalid:\n number = int(input(\"> \"))\n if number > 300 or number < 0:\n print(\"that is invalid input\")\n else:\n invalid = False\n\n\n\n",
"The issue ar... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074341112_python.txt |
Q:
Discord bot that gives a user role when I react with emoji
I've been working on a verification bot that gives members "Verified" role when I react on their pictures.
I found 1 main issue, the bot works fine but if anyone else reacted aswell the bot will simply keep spamming with message, is there a way to fix this... | Discord bot that gives a user role when I react with emoji | I've been working on a verification bot that gives members "Verified" role when I react on their pictures.
I found 1 main issue, the bot works fine but if anyone else reacted aswell the bot will simply keep spamming with message, is there a way to fix this point so that the first react only on the post will send verifi... | [
"Yes. Simply check if the user already has the verified role:\n@bot.event\nasync def on_raw_reaction_add(payload):\n if payload.channel_id == :\n guild_id = payload.guild_id\n guild = discord.utils.find(lambda g: g.id == guild_id, bot.guilds)\n\n if payload.emoji.name == '✅':\n ro... | [
0
] | [] | [] | [
"discord.py",
"python"
] | stackoverflow_0074212417_discord.py_python.txt |
Q:
Attribute Error: openai has no attribute Image
So I was getting my hands-on on the new DALL.E api for Python which has been made public. I was getting the Attribution Error as it was not detecting the Image model in Open ai after running the following code:
response = openai.Image.create(
prompt="a white siamese... | Attribute Error: openai has no attribute Image | So I was getting my hands-on on the new DALL.E api for Python which has been made public. I was getting the Attribution Error as it was not detecting the Image model in Open ai after running the following code:
response = openai.Image.create(
prompt="a white siamese cat",
n=1,
size="1024x1024"
)
image_url = respo... | [
"Had the same problem. I noticed my python is 3.7.0, which only supports up to openai=0.8... for openai 0.25.0, will need at least python>=3.7.1\n",
"I just found the solution. You have to upgrade your openai library with code:\npip install --upgrade openai\n\nRestart the kernel, and enjoy :)\n"
] | [
3,
2
] | [] | [] | [
"api",
"openai",
"python"
] | stackoverflow_0074313676_api_openai_python.txt |
Q:
Does DolphinDB have an equivalent method to Python join?
In Python, I can join all elements into a string separated by a string separator with method join().
>>> ','.join(["{}D".format(i) for i in range(1,6)])
'1D,2D,3D,4D,5D'
How can I implement the function equivalent to join in DolphinDB?
A:
You may try fun... | Does DolphinDB have an equivalent method to Python join? | In Python, I can join all elements into a string separated by a string separator with method join().
>>> ','.join(["{}D".format(i) for i in range(1,6)])
'1D,2D,3D,4D,5D'
How can I implement the function equivalent to join in DolphinDB?
| [
"You may try function concat to form a string. The equivalent function can be implemented with the following script:\nconcat(string(1..5) + \"D\", ',')\n\nThe output is\n1D,2D,3D,4D,5D\n\n"
] | [
4
] | [] | [] | [
"dolphindb",
"join",
"python"
] | stackoverflow_0074311173_dolphindb_join_python.txt |
Q:
how to split a string having more than one separator in python?
I have a pyspark dataframe that contains a column which has strings as shown below
qwe1
tre1.eyyu
cvbn.poiu.sdfg
- A value could be a single string (qwe1)
- A value could have one delimiter, i.e ".", and characters on both side of it.(tre1.eyyu)
- A ... | how to split a string having more than one separator in python? | I have a pyspark dataframe that contains a column which has strings as shown below
qwe1
tre1.eyyu
cvbn.poiu.sdfg
- A value could be a single string (qwe1)
- A value could have one delimiter, i.e ".", and characters on both side of it.(tre1.eyyu)
- A value could have two delimiters. (cvbn.poiu.sdfg)
code as below
p1 =... | [
"If you want to have a three list every time, please pre-define it.\nfor row in table:\n out = ['','', '']\n for index, word in enumerate(row.split('.', maxsplit=2)):\n out[index] = word\n print(out)\n\nOutput:\n['qwe1', '', '']\n['tre1', 'eyyu', '']\n['cvbn', 'poiu', 'sdfg']\n\n"
] | [
0
] | [] | [] | [
"pyspark",
"python",
"python_3.x"
] | stackoverflow_0074320317_pyspark_python_python_3.x.txt |
Q:
Shortest code to create an error that isn't a NameError or SyntaxError
In Python, many statements can cause errors, but I would like to know what are the simplest statements that can cause an Error except for NameError and SyntaxError and their subclasses such as IdentationError
Using the interactive Python shell,... | Shortest code to create an error that isn't a NameError or SyntaxError | In Python, many statements can cause errors, but I would like to know what are the simplest statements that can cause an Error except for NameError and SyntaxError and their subclasses such as IdentationError
Using the interactive Python shell, I have tried using single characters in statements but they are all NameErr... | [
"I think the shortest one would be a three-character ZeroDivisionError. Like this:\n1/0\n\nAlmost everything that isn't a NameError or SyntaxError is going to need some kind of operator, which will bump you up to three characters.\n",
"bitwise negation of a float raises TypeError in 3 characters\n>>> ~.0\nTraceba... | [
1,
1,
0,
0,
0
] | [] | [] | [
"interpreter",
"python"
] | stackoverflow_0074341209_interpreter_python.txt |
Q:
Asyncio running multiple asynconrous functions at once with uvicorn and fastapi
I'm having some problems with running my own async functions with uvicorn (fastapi)
My goal is to be able to run the queue manager function, as well as the uvicorn webapp. However, it seems that my start function blocks the uvicorn.run... | Asyncio running multiple asynconrous functions at once with uvicorn and fastapi | I'm having some problems with running my own async functions with uvicorn (fastapi)
My goal is to be able to run the queue manager function, as well as the uvicorn webapp. However, it seems that my start function blocks the uvicorn.run code from running.
async def queue_manager(self):
while True:
j... | [
"You could use startup event.\nasync def queue_manager(self):\n while True:\n job = await self.queue.get()\n print(job)\n await asyncio.sleep(2)\n\n\napp = FastAPI()\napp.include_router(server.router)\n\n@app.on_event('startup')\nasync def start():\n asyncio.create_task(qu... | [
2
] | [] | [] | [
"fastapi",
"python",
"python_asyncio",
"uvicorn"
] | stackoverflow_0074341178_fastapi_python_python_asyncio_uvicorn.txt |
Q:
pySerial PermissionError(13, 'Access denied', None, 5)
I wanted to create a manager for the frige and therefor I wanted to use a EAN Scanner to scan the items.
So far I wrote myself a EANScanner class in order to read the EANs from the serial port and everything was fine.
But now I wanted to continue on my desktop... | pySerial PermissionError(13, 'Access denied', None, 5) | I wanted to create a manager for the frige and therefor I wanted to use a EAN Scanner to scan the items.
So far I wrote myself a EANScanner class in order to read the EANs from the serial port and everything was fine.
But now I wanted to continue on my desktop and ran into strange problems (at least strange for me)
I a... | [
"Thats error means your COM port is already in use and getting data,\ntry to use ser.close() to close the connection\n",
"I had this same issue - I know this was asked over a year ago, but I was searching for answers today and couldn't find anything.\nHere is what I discovered - I had a system monitoring software... | [
1,
1,
1,
0
] | [] | [] | [
"pyserial",
"python"
] | stackoverflow_0059993883_pyserial_python.txt |
Q:
Find the words from the file whose first letter is capitalized
I need to write a script that finds all of the capitalized words (not words in all caps, just the initial letter) in a text file and presents them in alphabetical order.
I tried to use a regex like this:
re.findall(r'\b[A-Z][a-z]*\b', line)
but my fun... | Find the words from the file whose first letter is capitalized | I need to write a script that finds all of the capitalized words (not words in all caps, just the initial letter) in a text file and presents them in alphabetical order.
I tried to use a regex like this:
re.findall(r'\b[A-Z][a-z]*\b', line)
but my function returns this output:
Enter the file name: bzip2.txt
['A', 'All... | [
"You can do this within the regex itself, no need to filter the array. Just use + instead of *:\nre.findall(r'\\b[A-Z][a-z]+\\b', line)\n\nIn RegEx, * means to match zero or more times, while + means to match one or more times. Hence, your original code matched the lowercase letters zero times, so it was essentiall... | [
5,
0
] | [] | [] | [
"python",
"python_3.x",
"regex"
] | stackoverflow_0074341214_python_python_3.x_regex.txt |
Q:
Using VS Code Black Formatter extension to format multiple files at once
I have the Black Formatter extension configured to format the current file on save. I want to perform a one-time-only action where I format all my python files, as opposed to just the current file. I tried running the command (in the integrat... | Using VS Code Black Formatter extension to format multiple files at once | I have the Black Formatter extension configured to format the current file on save. I want to perform a one-time-only action where I format all my python files, as opposed to just the current file. I tried running the command (in the integrated terminal, with venv activated):
black {my_directory}
as described in the do... | [
"The problem with command not found may be that black is not installed in the currently selected interpreter, so you have to use pip install black to install.\nOf course, you can also switch to the interpreter installed with black to perform black formatting.\n"
] | [
0
] | [] | [] | [
"formatting",
"python",
"visual_studio_code"
] | stackoverflow_0074332778_formatting_python_visual_studio_code.txt |
Q:
I am getting this error: TypeError: '<' not supported between instances of 'str' and 'float'
I have this table that in which I am comparing list of articles (Article_body) with 4 baseline articles using cosine similarity:
Article_body
articleScores1
articleScores2
articleScores3
articleScores4
articleScores5
a**... | I am getting this error: TypeError: '<' not supported between instances of 'str' and 'float' | I have this table that in which I am comparing list of articles (Article_body) with 4 baseline articles using cosine similarity:
Article_body
articleScores1
articleScores2
articleScores3
articleScores4
articleScores5
a*****
0.6
0.2
0.7
0.9
0.2
a*****
0.3
0.8
0.1
0.5
0.1
I want to add a column that gives w... | [
"(df.iloc[:, 1:-1]\n .astype('float')\n .apply(\n lambda x: ('CosineSim' + x.idxmax()[-1]) if x.max() >= 0.5 else False \n , axis=1)\n)\n\noutput:\n0 CosineSim4\n1 CosineSim2\n2 False\n\nmake result to Most_similar_to column\n"
] | [
1
] | [] | [] | [
"apply",
"function",
"numpy",
"pandas",
"python"
] | stackoverflow_0074341287_apply_function_numpy_pandas_python.txt |
Q:
How to print data in Django views.py not in template?
I am new to Django and I know how to get the data from the database and send to the template. But i am in a situation where I need to print the data from the database in views.py file
order = Order.objects.get(user=request.user, ordered=False)
context['object']... | How to print data in Django views.py not in template? | I am new to Django and I know how to get the data from the database and send to the template. But i am in a situation where I need to print the data from the database in views.py file
order = Order.objects.get(user=request.user, ordered=False)
context['object']=order
return render(request,"Orderview.html",context)
thi... | [
"If you are asking how to print data to console then you can just use print(data) and this will print the data to the console. If you want to print context then:\norder = Order.objects.get(user=request.user, ordered=False)\ncontext['object']=order\nprint(context)\nreturn render(request,\"Orderview.html\",context)\n... | [
0,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0068995357_django_python.txt |
Q:
Shooting a bullet in pygame in the direction of mouse
I just cant figure out why my bullet is not working. I made a bullet class and here it is:
class Bullet:
def __init__(self):
self.x = player.x
self.y = player.y
self.height = 7
self.width = 2
self.bullet = pygame.Surf... | Shooting a bullet in pygame in the direction of mouse | I just cant figure out why my bullet is not working. I made a bullet class and here it is:
class Bullet:
def __init__(self):
self.x = player.x
self.y = player.y
self.height = 7
self.width = 2
self.bullet = pygame.Surface((self.width, self.height))
self.bullet.fill((25... | [
"First of all pygame.transform.rotate does not transform the object itself, but creates a new rotated surface and returns it.\nIf you want to fire a bullet in a certain direction, the direction is defined the moment the bullet is fired, but it does not change continuously.\nWhen the bullet is fired, set the startin... | [
13,
0
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0059977052_pygame_python.txt |
Q:
RuntimeError: mat1 and mat2 shapes cannot be multiplied (32x400 and 600x120)
I have the following CNN below and I am getting the following error RuntimeError: mat1 and mat2 shapes cannot be multiplied (32x400 and 600x120). Im using the CIFAR10 dataset which contains a total of 6,000 32x32 images with 10 labels. I... | RuntimeError: mat1 and mat2 shapes cannot be multiplied (32x400 and 600x120) | I have the following CNN below and I am getting the following error RuntimeError: mat1 and mat2 shapes cannot be multiplied (32x400 and 600x120). Im using the CIFAR10 dataset which contains a total of 6,000 32x32 images with 10 labels. If I understand correctly, the size input into x = F.relu(self.fc1(x)) should be 60... | [
"It's better to use \"same\" padding convolution 2d if downsampling is performed by average pooling.\nclass Network(nn.Module):\n def __init__(self):\n super(Network, self).__init__()\n self.conv1 = nn.Conv2d(3, 6, kernel_size=5, padding=2)\n self.pool = nn.MaxPool2d(2, 2) # downsample / 2\n... | [
0
] | [] | [] | [
"conv_neural_network",
"deep_learning",
"python",
"pytorch"
] | stackoverflow_0074341292_conv_neural_network_deep_learning_python_pytorch.txt |
Q:
how do I (filter and) save many ROIs taken from a larger picture individually to picture files?
I followed this discussion: How extract pictures from an big image in python
made mine, this is the output link https://imgur.com/a/GK8747f and .py script below
import cv2
image = cv2.imread('/home/joy/桌面/test_11_4/o... | how do I (filter and) save many ROIs taken from a larger picture individually to picture files? | I followed this discussion: How extract pictures from an big image in python
made mine, this is the output link https://imgur.com/a/GK8747f and .py script below
import cv2
image = cv2.imread('/home/joy/桌面/test_11_4/original.png', cv2.IMREAD_UNCHANGED)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
kernel = cv2.get... | [
"\nI did frame them up, then how to save each one/qr code\n\nIf you want to save the contents of each rectangle, there are two steps.\nWithin your for loop, the first step to make a copy of the image and crop it to the size of the rectangle.\nNow that you have that image extracted, the next step is to save it. You'... | [
0
] | [] | [] | [
"image_processing",
"opencv",
"python"
] | stackoverflow_0074341123_image_processing_opencv_python.txt |
Q:
Running codes on VS Code
I installed code run extension I cant write anything if I run the code with extension. On the other hand if I use shift+enter its going line by line and I dont think it should be like this
I wrote some codes, and I want to run my codes. For example I will write lionel then the surname part... | Running codes on VS Code |
I installed code run extension I cant write anything if I run the code with extension. On the other hand if I use shift+enter its going line by line and I dont think it should be like this
I wrote some codes, and I want to run my codes. For example I will write lionel then the surname part will come and I will write m... | [
"If the extension mentioned in your article is code-runner, you can add the following code to settings.json:\n\"code-runner.runInTerminal\": true,\nor you can check the option in the settings:\n\nYou can also use the \"Run python file\" which is provided by Python extension.\n\n"
] | [
0
] | [] | [] | [
"python",
"visual_studio_code"
] | stackoverflow_0074339289_python_visual_studio_code.txt |
Q:
Mapping Each Word In A String's Start and End Index To Dictionary
I'm trying to find the index range (start index and end index, spaces are omitted, and with indexing starting at 1 for human readability.) of each word in a string. What I thought was the best approach was doing a list of lists where each nested lis... | Mapping Each Word In A String's Start and End Index To Dictionary | I'm trying to find the index range (start index and end index, spaces are omitted, and with indexing starting at 1 for human readability.) of each word in a string. What I thought was the best approach was doing a list of lists where each nested list contains the word and a list of the start and end index. From a sampl... | [
"You can use re, with start and end attributes of match objects:\nimport re\nfrom collections import defaultdict\n\ntext = \"i have a list of lists that contain a word and there indices my method works except with repeated words like of or a or the or it\"\n\noutput = defaultdict(list)\nfor m in re.finditer(r\"\\S+... | [
1,
0
] | [] | [] | [
"dictionary",
"nested_lists",
"python"
] | stackoverflow_0074341368_dictionary_nested_lists_python.txt |
Q:
Don't know why the function is not returning the exact beverage type
def get_beverage_type(a_enabled: bool, b_enabled: bool) -> str:
"""
Returns the beverage type defined by the switches.
"""
if a_enabled == "y" == True and b_enabled == "n" == False:
return "Juice, Orange"
elif a_enable... | Don't know why the function is not returning the exact beverage type | def get_beverage_type(a_enabled: bool, b_enabled: bool) -> str:
"""
Returns the beverage type defined by the switches.
"""
if a_enabled == "y" == True and b_enabled == "n" == False:
return "Juice, Orange"
elif a_enabled == "n" == False and b_enabled == "y" == True:
return "Milk, 2%"
... | [
"You appear to believe that a_enabled == \"y\" == True checks if a_enabled is one of those values.\nThat is not what it does. It is equivalent to a_enabled == \"y\" and \"y\" == True which of course is always False.\nYou probably meant a_enabled == \"y\" or a_enabled == True, for which there is no shorthand. Howeve... | [
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074341390_python.txt |
Q:
Python how to replace values in a column in csv
I would like to change and replace some values under some conditions.
My csv looks like:
Date
0 2022-11-05
1 2022-11-06
2 2022-11-08
3 2022-11-09
I want the date +2 if it is Saturday and +1 if it is Sunday, and replace the value in the original csv.
df = pd.r... | Python how to replace values in a column in csv | I would like to change and replace some values under some conditions.
My csv looks like:
Date
0 2022-11-05
1 2022-11-06
2 2022-11-08
3 2022-11-09
I want the date +2 if it is Saturday and +1 if it is Sunday, and replace the value in the original csv.
df = pd.read_csv('Book1.csv')
date = df["Date"]
for d in date:... | [
"I made some slight changes and this appears to work. With the changes I made, I'm just updating the data frame as a multidimensional array.\ndf = pd.read_csv('Book1.csv')\ndate = df[\"Date\"]\nfor i in range(0, len(date)):\n d = date[i]\n date_object = datetime.strptime(d, '%Y-%m-%d').date()\n #print(date... | [
0,
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0074341251_csv_python.txt |
Q:
Conda's solving environment takes forever
I am using conda since one year, since several weeks, whenever I want to install a package using conda install -c anaconda <package_name>, for any package, it is just stuck at the Solving environment step.
I just want to install, for example, sympy or mpmath for Python...
... | Conda's solving environment takes forever | I am using conda since one year, since several weeks, whenever I want to install a package using conda install -c anaconda <package_name>, for any package, it is just stuck at the Solving environment step.
I just want to install, for example, sympy or mpmath for Python...
Is there some magic command to solve this probl... | [
"Use pip instead of conda.\nNowadays, Conda is pretty much broken because its native algorithm does not scale with the number of packages in real-world applications. Its developers are stubborn and reluctant to change and adapt, turning the toolkit more and more useless and hopeless.\nFYI, both pip and conda are Py... | [
1
] | [] | [] | [
"anaconda",
"environment",
"package",
"python"
] | stackoverflow_0072743734_anaconda_environment_package_python.txt |
Q:
ModuleNotFoundError: No module named 'PIL' ; But pillow is installed
I am importing Image, ImageTk using from PIL import Image, ImageTk
I get the error that the module doesnt exist, but when I try to install it, it says that the module is already installed.
I get this error:
from PIL import Image, ImageTk
Modu... | ModuleNotFoundError: No module named 'PIL' ; But pillow is installed | I am importing Image, ImageTk using from PIL import Image, ImageTk
I get the error that the module doesnt exist, but when I try to install it, it says that the module is already installed.
I get this error:
from PIL import Image, ImageTk
ModuleNotFoundError: No module named 'PIL'
When I try to import pillow using ... | [
"I hope this will help you:\n️ Before installing Pillow, uninstall PIL.\npip uninstall PIL\n️ in a virtual environment or using Python 2\npip install Pillow\n️ for python 3 (could also be pip3.10 depending on your version)\npip3 install Pillow\n️ if you get permissions error\nsudo pip3 install Pillow\npip install P... | [
0,
0
] | [] | [] | [
"python",
"python_imaging_library",
"visual_studio_code"
] | stackoverflow_0074319112_python_python_imaging_library_visual_studio_code.txt |
Q:
why do I get an error when writing sys.argv[1]
import sys
import pygame
import random
#command line
image = sys.argv[1]
#loading the image and importing
inputImage = pygame.image.load(image)
#getting the image's height and width
(width,height) = inputImage.get_size()
#creating the bigger windom of the image by... | why do I get an error when writing sys.argv[1] | import sys
import pygame
import random
#command line
image = sys.argv[1]
#loading the image and importing
inputImage = pygame.image.load(image)
#getting the image's height and width
(width,height) = inputImage.get_size()
#creating the bigger windom of the image by multiplying original size by 6
window = pygame.disp... | [
"This method does not catch any user errors (which is what you're experiencing).\n#command line\nimage = sys.argv[1]\n\nYou need to check a few things here:\n\nDoes the sys.argv list actually have a second element (at index [1]).\nTest the filename specified actually exists.\nUse a try, except block to catch any er... | [
1
] | [] | [] | [
"pygame",
"pygame_surface",
"python"
] | stackoverflow_0074329336_pygame_pygame_surface_python.txt |
Q:
Trouble finding a element on myanimelist.net using selenium package in python
I am having problems where nothing is coming up no matter what I do I have tried the class, the title, partial link text(they each have their own id to identify witch anime) and they all turn up blank or invalid.
The current webpage is h... | Trouble finding a element on myanimelist.net using selenium package in python |
I am having problems where nothing is coming up no matter what I do I have tried the class, the title, partial link text(they each have their own id to identify witch anime) and they all turn up blank or invalid.
The current webpage is https://myanimelist.net/anime.php?letter=N&show=400.
I am trying to get a script ... | [
"xpath is the best way to select elements in pages for beginners\nWhere more than one result column is sorted on top of a table (tbody) like on this page, I suggest you select the table first and proceed from the table to the inner layers.\nxpath path that selects the element of the href with each link:\n//tbody/tr... | [
0
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0074340489_python_selenium.txt |
Q:
How can I make applications opened by subprocess.Popen() stay open after my script exits?
I want to launch Excel using subprocess.Popen() but my script doesn't work as expected.
The following simple script doesn't work in the way I want it to work. It looks like Excel is terminated immediately when the script ends... | How can I make applications opened by subprocess.Popen() stay open after my script exits? | I want to launch Excel using subprocess.Popen() but my script doesn't work as expected.
The following simple script doesn't work in the way I want it to work. It looks like Excel is terminated immediately when the script ends. What do I need to do to keep it open?
import subprocess
subprocess.Popen(r'C:\Program Files (... | [
"you can use the following\nimport os\nos.system(\"start excel.exe\")\n\n",
"Thank you everyone for answering my question. I was able to solve it myself. The reason Excel terminates was because I ran the script from VS Code. If I run the script from Command Prompt, Excel stays open.\n"
] | [
0,
0
] | [
"import subprocess\nsubprocess.run(r'C:\\Program Files\\Microsoft Office\\root\\Office16\\EXCEL.EXE')\nStays Open Until Exit, Then you get this next line...\nCompletedProcess(args='C:\\Program Files\\Microsoft Office\\root\\Office16\\EXCEL.EXE', returncode=0)\nIf you want to do multiple, then multithreading is your... | [
-1
] | [
"python",
"windows"
] | stackoverflow_0074295296_python_windows.txt |
Q:
how to install opencv-python on linux with requirements.txt
I'm trying to deploy a python bot that use opencv on discloud but when I start the app it show the error:
#Traceback (most recent call last):
E File "/home/user_1028648117500924025/main.py", line 1, in <module>
import cv2
X File "/usr/local/lib/pyth... | how to install opencv-python on linux with requirements.txt | I'm trying to deploy a python bot that use opencv on discloud but when I start the app it show the error:
#Traceback (most recent call last):
E File "/home/user_1028648117500924025/main.py", line 1, in <module>
import cv2
X File "/usr/local/lib/python3.10/site-packages/cv2/__init__.py", line 181, in <module>
... | [
"Since your are trying to install this on a cloud provider's instance (discloud in this case), it might be missing some dependencies required by cv2\nHave a look at this ImportError: libGL.so.1: cannot open shared object file: No such file or directory\nFrom the top voted answer:\n\nAdd the following lines to your ... | [
0
] | [] | [] | [
"lib",
"opencv",
"python"
] | stackoverflow_0074338777_lib_opencv_python.txt |
Q:
How can I properly set utf-8 locale for Python in a docker container?
I am trying to run my python file in a docker container.
I am using NVIDIA container image for PyTorch, release 19.05, which provides Ubuntu 16.04 including Python 3.6 environment.
According to another similar question, I have added the environm... | How can I properly set utf-8 locale for Python in a docker container? | I am trying to run my python file in a docker container.
I am using NVIDIA container image for PyTorch, release 19.05, which provides Ubuntu 16.04 including Python 3.6 environment.
According to another similar question, I have added the environment parameter -e PYTHONIOENCODING=utf-8 when I ran the docker image:
nvidia... | [
"You should make your string a binary literal during creation with a b prefix\n>>> b\"(\\xef\\xbd\\xa1\\xef\\xbd\\xa5\\xcf\\x89\\xef\\xbd\\xa5\\xef\\xbd\\xa1)\\xef\\xbe\\x89\".decode(\"utf-8\")\n'(。・ω・。)ノ'\n\n"
] | [
0
] | [] | [] | [
"docker",
"linux",
"locale",
"python",
"utf_8"
] | stackoverflow_0074341551_docker_linux_locale_python_utf_8.txt |
Q:
Python 3.11.0: "No module named pip" on Spyder (5.4.0), but Terminal shows "ensurepip" as "Requirement already satisfied"
Hi. I installed Python 3.11.0 and Spyder IDE 5.4.0 a few days ago. It had been running smoothly. I tried entering "pip install pandas" (to install pandas through the console) but it says "no mo... | Python 3.11.0: "No module named pip" on Spyder (5.4.0), but Terminal shows "ensurepip" as "Requirement already satisfied" |
Hi. I installed Python 3.11.0 and Spyder IDE 5.4.0 a few days ago. It had been running smoothly. I tried entering "pip install pandas" (to install pandas through the console) but it says "no module named pip" (as shown in the picture).
I already ran "py -m ensurepip" through PowerShell but it says "Requirement already... | [
"Check the python installation used in your IDE vs the one used in Powershell.\nFrom your screenshot, it looks like the IDE comes with its own python and using that installation. Your powershell is probably using a different python installation.\nYou can update your IDE to use your system default so that the packag... | [
0
] | [] | [] | [
"pandas",
"pip",
"python"
] | stackoverflow_0074341276_pandas_pip_python.txt |
Q:
Find out which rows of one 2D numpy array are represented in another 2D numpy array
I have two arrays :
a = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12],
[13, 14, 15]]
b = [[1, 2, 3],
[4, 5, 6],
[13, 14, 15]]
And I want to find out which rows of first array are represented in seco... | Find out which rows of one 2D numpy array are represented in another 2D numpy array | I have two arrays :
a = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12],
[13, 14, 15]]
b = [[1, 2, 3],
[4, 5, 6],
[13, 14, 15]]
And I want to find out which rows of first array are represented in second array
desired_output = [1, 1, 0, 0, 1]
I have tried this code :
x = a == b[:, None]
... | [
"You can compare each row separately and then merge results using or. Here is sample code:\nnp.logical_or.reduce([(a == b[i]).all(axis=1) for i in range(b.shape[0])])\n\nResult:\narray([ True, True, False, False, True])\n\n",
"Here's a solution that is O(len(a)) + O(len(b)), rather than O(len(a) * len(b)):\nset... | [
0,
0,
0
] | [] | [] | [
"arrays",
"dask",
"numpy",
"python",
"vectorization"
] | stackoverflow_0074339256_arrays_dask_numpy_python_vectorization.txt |
Q:
Compute pandas dataframe row difference for each group with incrementing period till preset value
With a dataframe
df = pd.DataFrame([['a', 3], ['a', 5], ['a', 2], ['a', 6], ['a', 7], ['a', 1], ['a', 9], ['b', 7], ['b', 8], ['b', 11], ['b', 9], ['b', 10], ['b', 6]], columns = ['k', 'v'])
I want to compute the row... | Compute pandas dataframe row difference for each group with incrementing period till preset value | With a dataframe
df = pd.DataFrame([['a', 3], ['a', 5], ['a', 2], ['a', 6], ['a', 7], ['a', 1], ['a', 9], ['b', 7], ['b', 8], ['b', 11], ['b', 9], ['b', 10], ['b', 6]], columns = ['k', 'v'])
I want to compute the row difference on column v for each group of column k with a period of 3. While for the first few rows in ... | [
"Using .groupby() and .rolling() you can achieve what you want:\n>>> grouped = (df.\n groupby('k')['v'].\n rolling(window=4, min_periods=1).\n apply(lambda x: x.iloc[-1] - x.iloc[0]).\n reset_index().\n rename(columns={'v': 'diff'}).drop('level_1... | [
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074341607_pandas_python.txt |
Q:
Difference between dict and set (python)
So, I know that this,
a = {} # dict
constructs an empty dictionary. Now, I also picked up that this,
b = {1, 2, 3} # set
creates a set. This can easily be verified, as,
>>>print(type(a))
<class 'dict'>
>>>print(type(b))
<class 'set'>
While I understand what it does, I... | Difference between dict and set (python) | So, I know that this,
a = {} # dict
constructs an empty dictionary. Now, I also picked up that this,
b = {1, 2, 3} # set
creates a set. This can easily be verified, as,
>>>print(type(a))
<class 'dict'>
>>>print(type(b))
<class 'set'>
While I understand what it does, I fail to see why we use 'set notation' for emp... | [
"There were no set literals in Python 2, historically curly braces were only used for dictionaries. Sets could be produced from lists (or any iterables):\nset([1, 2, 3])\nset([i for i in range(1, 3)])\n\nPython 3 introduced set literals and comprehensions (see PEP-3100) which allowed us to avoid intermediate lists:... | [
69,
24,
17,
0
] | [] | [] | [
"dictionary",
"python",
"set"
] | stackoverflow_0034370599_dictionary_python_set.txt |
Q:
how to extract (x, y) coordinate value from a grid python
I have a grid 7x3
how to extract (x, y) coordinate value that contain "1"?
grid = np.array([
[0,0,0,0,0,0,0],
[0,0,1,0,1,0,1],
[0,0,1,0,1,0,1]])
A:
You can pass your array to numpy.argwhere which will find non-zero values:
grid = np.array([
[0,0,0,0,0... | how to extract (x, y) coordinate value from a grid python | I have a grid 7x3
how to extract (x, y) coordinate value that contain "1"?
grid = np.array([
[0,0,0,0,0,0,0],
[0,0,1,0,1,0,1],
[0,0,1,0,1,0,1]])
| [
"You can pass your array to numpy.argwhere which will find non-zero values:\ngrid = np.array([\n [0,0,0,0,0,0,0],\n [0,0,1,0,1,0,1],\n [0,0,1,0,1,0,1]\n])\n\nnp.argwhere(grid)\n\nreturning\narray([[1, 2],\n [1, 4],\n [1, 6],\n [2, 2],\n [2, 4],\n [2, 6]])\n\nIf you need specif... | [
2
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0074341776_arrays_numpy_python.txt |
Q:
Python Pygame Music While Loop
I have a Rpi 3 with:
Magnetic Reed switch (pin 18)
Oil Diffuser Ch1 relay hat
Disco Ball Ch2 relay hat
I am trying to trigger the diffuser, and disco ball with the reed switch to start diffusing good smells while the disco ball spins and lights up.
The diffuser and ball are working p... | Python Pygame Music While Loop | I have a Rpi 3 with:
Magnetic Reed switch (pin 18)
Oil Diffuser Ch1 relay hat
Disco Ball Ch2 relay hat
I am trying to trigger the diffuser, and disco ball with the reed switch to start diffusing good smells while the disco ball spins and lights up.
The diffuser and ball are working perfectly, however when I play the mp... | [
"pygame.mixer.music.play() instructs the mixer to begin playing the audio. So what you're experiencing seems to match exactly what one would expect. Everytime .play() is called, it starts again.\nA nice way to do this is to use a threaded function to monitor the GPIO I/Os, and then send messages to the PyGame eve... | [
1
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0074318025_pygame_python.txt |
Q:
How would I chunk up a list to write to text file due to running out of memory issue
import itertools, hashlib, pandas as pd,time, re
chars = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']
numbers_list = list(range(0,25))
rows = []
removechars1 = ["(",")","'",","," "]
removechars2 = [","," ","-"... | How would I chunk up a list to write to text file due to running out of memory issue | import itertools, hashlib, pandas as pd,time, re
chars = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']
numbers_list = list(range(0,25))
rows = []
removechars1 = ["(",")","'",","," "]
removechars2 = [","," ","-"]
pattern1 = '[' + ''.join(removechars1) + ']'
pattern2 = '[' + ''.join(removechars2) +... | [
"Don't store your combinations in a list only to then iterate again through that list. Write each \"row\" directly as your iterate through the combinations generator:\nimport itertools, hashlib, time, re\nchars = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']\nnumbers_list = list(range(0,25))\n# ... | [
2
] | [] | [] | [
"list",
"loops",
"python",
"python_3.x",
"python_itertools"
] | stackoverflow_0074341829_list_loops_python_python_3.x_python_itertools.txt |
Q:
Django how to pass clicked on link text to a URL on another HTML page showing static images?
I have table of tickers on one HTML page, and four charts displayed on another HTML page. These charts come from my static/images folder full of hundreds of images named by each ETF's benchmark index ticker. If I click the... | Django how to pass clicked on link text to a URL on another HTML page showing static images? | I have table of tickers on one HTML page, and four charts displayed on another HTML page. These charts come from my static/images folder full of hundreds of images named by each ETF's benchmark index ticker. If I click the ETF ticker "PSCD" in the first row of the table, how can it be linked to another HTML page named ... | [
"Modify the path for the charts page (to one that accepts a parameter) and pass in the ticker to this path. You can use that to filter content.\nIn your urls.py modify the path to charts:\nfrom django.urls import path\nfrom . import views\nfrom .views import ChartView\n\napp_name = 'forecast'\nurlpatterns = [\n ... | [
3,
0
] | [] | [] | [
"django",
"html",
"javascript",
"python"
] | stackoverflow_0074284715_django_html_javascript_python.txt |
Q:
Having issues with displaying data from a json file in a embed
I have been trying to show the data from my json file inside of a embed. However, I can't seem to find a way to display it and needed some help finding out how.
Here is the json file data:
{
"Slims Mod Bot": {
"Felix\u2122": 2,
"Dus... | Having issues with displaying data from a json file in a embed | I have been trying to show the data from my json file inside of a embed. However, I can't seem to find a way to display it and needed some help finding out how.
Here is the json file data:
{
"Slims Mod Bot": {
"Felix\u2122": 2,
"DustinFoes": 16,
"Slim Beatbox": 26,
},
In other words, I d... | [
"For anyone who is having the same problem my friend and his team found a answer:\n@bot.command()\nasync def leaderboard(ctx):\n with open('messages.json') as file:\n data = json.load(file)\n for key, value in data[\"Slims Mod Bot\"].items():\n embed = discord.Embed(\n title=\"Leadboard... | [
0
] | [] | [] | [
"database",
"discord.py",
"json",
"pycord",
"python"
] | stackoverflow_0074329681_database_discord.py_json_pycord_python.txt |
Q:
Why am I getting Time Limit Exceeded error on O(n) time complexity code?
The question, https://leetcode.com/problems/first-missing-positive/, asks:
Given an unsorted integer array nums, return the smallest missing positive integer.
You must implement an algorithm that runs in O(n) time and uses constant extra spac... | Why am I getting Time Limit Exceeded error on O(n) time complexity code? | The question, https://leetcode.com/problems/first-missing-positive/, asks:
Given an unsorted integer array nums, return the smallest missing positive integer.
You must implement an algorithm that runs in O(n) time and uses constant extra space.
Example 1:
Input: nums = [1,2,0]
Output: 3
Example 2:
Input: nums = [3,4,-... | [
"As the comments described, sorted() doesn't take linear time. sorted() also creates a new list, so your solution also violates the O(1) memory constraint.\nHere's a linear-time, constant-space solution. The problem asks for two things (for simplicity, let n = len(nums)):\n\na data structure that can in O(1) time, ... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0070571699_python.txt |
Q:
In Plotly (python), how to disconnect a lines when no values?
In Plotly (Python), I would like to disconnect a line when there is no value.
df = pd.DataFrame(range(2,12), index=pd.date_range(start='2010-01-01', freq='d', periods=10), columns=['A'])
idx = [1,2, 4,5, 7,8]
fig = go.Figure()
line = go.Scatter(x=df.in... | In Plotly (python), how to disconnect a lines when no values? | In Plotly (Python), I would like to disconnect a line when there is no value.
df = pd.DataFrame(range(2,12), index=pd.date_range(start='2010-01-01', freq='d', periods=10), columns=['A'])
idx = [1,2, 4,5, 7,8]
fig = go.Figure()
line = go.Scatter(x=df.index[idx], y=df['A'][idx])
fig.add_trace(line)
fig.show()
In this e... | [
"You could try adding in a column, keeping the desired values for A and adding a null value for segments you don't want plotted.\nimport plotly.graph_objects as go\nimport pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame(range(2,12), index=pd.date_range(start='2010-01-01', freq='d', periods=10), columns=['A'])... | [
1
] | [] | [] | [
"plotly",
"python"
] | stackoverflow_0074336607_plotly_python.txt |
Q:
How to test the sum of 2 elements in a list for each pair of elements
I am trying to analyse if a pair of elements in a list equal to a certain number n. Let's say I have n=5 and my list is ['1', '2', '3', '4', '5','6']. Here, we can see that 4+1=5 and 3+2=5. I want to display ONLY this : Elements 4 and 1 =5
How d... | How to test the sum of 2 elements in a list for each pair of elements | I am trying to analyse if a pair of elements in a list equal to a certain number n. Let's say I have n=5 and my list is ['1', '2', '3', '4', '5','6']. Here, we can see that 4+1=5 and 3+2=5. I want to display ONLY this : Elements 4 and 1 =5
How do I make a loop that tests all pairs of number (so a group of 2 numbers) ? ... | [
"Is this you asking?\ninput=['1', '2', '3', '4', '5','6']\nn=5\nfor i in input:\n for j in input:\n if int(i)+int(j)==n:\n print(i,\"+\",j,\"=\",n)\n\noutput\n1 + 4 = 5\n2 + 3 = 5\n3 + 2 = 5\n4 + 1 = 5\n\n"
] | [
0
] | [] | [] | [
"for_loop",
"list",
"loops",
"python"
] | stackoverflow_0074341850_for_loop_list_loops_python.txt |
Q:
Simplifying line length with pre-commit, flake8, black, isort, pylint, etc
When using multiple tools that either check or format python files, is there a way to set line length once for all?
Currently I have:
.flake8 file:
max-line-length = 120
.isort.cfg file:
line-length = 120
.black file:
line-length = 120
.... | Simplifying line length with pre-commit, flake8, black, isort, pylint, etc | When using multiple tools that either check or format python files, is there a way to set line length once for all?
Currently I have:
.flake8 file:
max-line-length = 120
.isort.cfg file:
line-length = 120
.black file:
line-length = 120
.pylintrc file:
max-line-length = 120
| [
"If you use Poetry, it's possible to configure all the above in the pyproject.toml file as a workaround.\nFor example, my project looks like this:\n[tool.black]\nline-length = 130\ntarget-version = ['py310']\ninclude = '\\.pyi?$'\nexclude = '''\n/(\n \\.git\n| \\.hg\n| \\.mypy_cache\n| \\.tox\n| \\.venv\n| _buil... | [
0
] | [] | [] | [
"flake8",
"isort",
"pre_commit",
"pylintrc",
"python"
] | stackoverflow_0071773712_flake8_isort_pre_commit_pylintrc_python.txt |
Q:
Graph disconnected: cannot obtain value for tensor Tensor("input_20:0", shape=(?, 25, 2), dtype=float32) at layer "input_20"
I try to combine two CNNs with Keras. Here is the code:
import keras
from keras import Model
from keras.layers.core import Dense, Activation
from keras.layers import Conv2D, Conv1D, MaxPooli... | Graph disconnected: cannot obtain value for tensor Tensor("input_20:0", shape=(?, 25, 2), dtype=float32) at layer "input_20" | I try to combine two CNNs with Keras. Here is the code:
import keras
from keras import Model
from keras.layers.core import Dense, Activation
from keras.layers import Conv2D, Conv1D, MaxPooling2D, Reshape, Concatenate, Dropout , MaxPooling1D, Flatten
from keras.layers import Dense, Input, LeakyReLU
from keras.utils.vis_... | [
"The problem is that you defined your model with inputs=[input_p, input_sp], but you are not actually using [input_p, input_sp] as input layers when you build the model, you are using [model_p_in, model_sp_in] instead. See the updated code below.\nfrom keras import Model\nfrom keras.layers import Conv1D, Concatenat... | [
0
] | [] | [] | [
"conv_neural_network",
"deep_learning",
"keras",
"python",
"tensorflow"
] | stackoverflow_0074341317_conv_neural_network_deep_learning_keras_python_tensorflow.txt |
Q:
A python function to shift the positions of a vowel by 2 places?
r task is to shift the vowels by two positions contained in the string, where vowels are
the symbols a e i o u (and their capitalised versions A E I O U), If the input is "a cat", the output is "i cit"
vowels = ["a", "e", "i", "o", "u"]
vowel=['a','e... | A python function to shift the positions of a vowel by 2 places? | r task is to shift the vowels by two positions contained in the string, where vowels are
the symbols a e i o u (and their capitalised versions A E I O U), If the input is "a cat", the output is "i cit"
vowels = ["a", "e", "i", "o", "u"]
vowel=['a','e','i','o','u']
mapper = dict(zip(vowels, vowels[1:] + [vowels[0]]))
m... | [
"You need a function count_repetition which tells you how many consecutive vowels there are starting at any position. This is also the number of vowels in vowels array that you should skip. The new vowel can be found using vowels[(steps+i+1)%size] where size is the length of vowels array and i is the index of the o... | [
0
] | [] | [] | [
"arrays",
"dictionary",
"list",
"python",
"python_3.x"
] | stackoverflow_0074324473_arrays_dictionary_list_python_python_3.x.txt |
Q:
Get mac address with telnet in Python
I am trying to get mac addresses from stb. When I run "ifconfig eth0 | grep HWaddr | cut -c39-55" on the command line, I get the right mac addresses.
for ip in ip_address:
tel_con = telnetlib.Telnet(ip, port_number, time_delay)
tel_con.read_until("login: ")
tel_co... | Get mac address with telnet in Python | I am trying to get mac addresses from stb. When I run "ifconfig eth0 | grep HWaddr | cut -c39-55" on the command line, I get the right mac addresses.
for ip in ip_address:
tel_con = telnetlib.Telnet(ip, port_number, time_delay)
tel_con.read_until("login: ")
tel_con.write(user_name + "\r\n")
tel_con.rea... | [
"after:\ntel_con.write(\"ifconfig eth0 | grep HWaddr | cut -c39-55\\r\\n\")\n\nyou need to read output again. try this:\nfor ip in ip_address:\n\n tel_con = telnetlib.Telnet(ip, port_number, time_delay)\n tel_con.read_until(\"login: \")\n tel_con.write(user_name + \"\\r\\n\")\n tel_con.read_until(\"-sh-... | [
0
] | [] | [] | [
"mac_address",
"python",
"python_2.7",
"telnet"
] | stackoverflow_0041806372_mac_address_python_python_2.7_telnet.txt |
Q:
`__set_name__` hook manually added to `functools.wraps()` descriptor instance never called
I'm trying to add a __set_name__ hook to the descriptor produced by functools.wraps inside a decorator, but it is never called and I don't see any error messages:
import functools
def wrap(fn):
"""Decorator."""
@fu... | `__set_name__` hook manually added to `functools.wraps()` descriptor instance never called | I'm trying to add a __set_name__ hook to the descriptor produced by functools.wraps inside a decorator, but it is never called and I don't see any error messages:
import functools
def wrap(fn):
"""Decorator."""
@functools.wraps(fn)
def w(*args, **kwargs):
return fn(*args, **kwargs)
# This ne... | [
"Whenever Python looks for magic methods, it looks on the type of the object, not the instance. What you've done is take a function object (the return value of functools.wrap, in this case) and assign something on its __dict__. But for efficiency (and correctness, in some cases), special methods like __set_name__ b... | [
1
] | [] | [] | [
"decorator",
"metaclass",
"python",
"python_decorators",
"python_descriptors"
] | stackoverflow_0074341990_decorator_metaclass_python_python_decorators_python_descriptors.txt |
Q:
Keras LSTM masking multidimensional array
My data is sequential 3D array that have different length, something like this (this is just an example data, not my real data):
data1 = [
[
[-1,2,3],
[1,0,-3],
[1,-2,0]
],
[
[1,-2,3],
[1,... | Keras LSTM masking multidimensional array | My data is sequential 3D array that have different length, something like this (this is just an example data, not my real data):
data1 = [
[
[-1,2,3],
[1,0,-3],
[1,-2,0]
],
[
[1,-2,3],
[1,0,-3],
[-1,2,0]
]
... | [
"From the masking layer documentation, your data should be structured in the format samples x timesteps x features. You can of course extend the concept of timesteps to whatever form of sequential information you're using.\nYou would assign your masking value like below.\ndata[SHORT_DATA_INDEX, MISSING_SEQUENCE_IN... | [
0
] | [] | [] | [
"keras",
"lstm",
"masking",
"python",
"tensorflow"
] | stackoverflow_0074291966_keras_lstm_masking_python_tensorflow.txt |
Q:
Sleep function seems to be skipping some of my code
Beginner-ish to python and my sleep function in the function pet_dog is not working properly. I want heart2 to appear when u pet the dog, then sleep for a second, and then it hides. However, instead no heart appears, it just waits a second then adds 1 to the scor... | Sleep function seems to be skipping some of my code | Beginner-ish to python and my sleep function in the function pet_dog is not working properly. I want heart2 to appear when u pet the dog, then sleep for a second, and then it hides. However, instead no heart appears, it just waits a second then adds 1 to the score. I think the sleep function is not pausing before the h... | [
"When you set wn.tracer(0) to 0, you have to manually update the screen using wn.update(). So adding it like this should work:\nif character.xcor() > 13 and character.xcor() < 31 and character.ycor() > -10 and character.ycor() < 10:\n heart2.showturtle()\n wn.update()\n sleep(1)\n heart2.hideturtle()\n ... | [
1,
0
] | [] | [] | [
"python",
"python_turtle"
] | stackoverflow_0074333086_python_python_turtle.txt |
Q:
How can I filter only strings in a list that only contain certain characters in Python?
For this project I am working on, I have a list of strings of equal length (so the length may vary), and I only want the strings whose substrings can be found in a string that I have specified.
Will elaborate further, but the f... | How can I filter only strings in a list that only contain certain characters in Python? | For this project I am working on, I have a list of strings of equal length (so the length may vary), and I only want the strings whose substrings can be found in a string that I have specified.
Will elaborate further, but the following is the expected result.
# list of strings
["aa", "ct", "ab", "ac", "bd", "ra", "db",... | [
"Everything looks very good, but we need only stop checking when we find characters we wish to exclude. Otherwise, we must continue to check the sequence.\nlist_of_strings = [\"aa\", \"ct\", \"ab\", \"ac\", \"bd\", \"ra\", \"db\", \"pq\", \"cb\"]\n\ndef isValidString(seq):\n for substring in seq:\n if sub... | [
1,
0,
0,
0,
0
] | [] | [] | [
"boolean",
"list",
"python",
"string",
"substring"
] | stackoverflow_0074341905_boolean_list_python_string_substring.txt |
Q:
Days in dataframe arent in order. How do I have it set to be the right order by the week?
The days are shown in different order of appearance. How do I have it so that they are correct?
# calculate the mode of week-day of members
mode_week_day_member = bike_data[bike_data['member_casual'] == 'member']
mode_week_... | Days in dataframe arent in order. How do I have it set to be the right order by the week? | The days are shown in different order of appearance. How do I have it so that they are correct?
# calculate the mode of week-day of members
mode_week_day_member = bike_data[bike_data['member_casual'] == 'member']
mode_week_day_member = mode_week_day_member['day_name'].mode()
mode_week_day_member
The output comes out... | [
"Taking reference from pandas categorical data documentation, you can reorder the categorical type:\ndf = pd.DataFrame(data=[\"Wed\", \"Sun\", \"Tue\", \"Thu\"], columns=[\"week_day\"])\ndf[\"week_day\"] = df[\"week_day\"].astype(\"category\")\n\n[Out]:\n week_day\n0 Wed\n1 Sun\n2 Tue\n3 Thu\n\... | [
1
] | [] | [] | [
"data_analysis",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074341380_data_analysis_dataframe_pandas_python.txt |
Q:
Modify global module variable externally
I have a plotting module imported by other scripts/jupyter notebooks which has a global variable denoting font size on the axis labels. This variable is used as default for a function setting axis labels:
FONT_SIZE=14
def pltlabel(title='', x='', y='', size=FONT_SIZE):
... | Modify global module variable externally | I have a plotting module imported by other scripts/jupyter notebooks which has a global variable denoting font size on the axis labels. This variable is used as default for a function setting axis labels:
FONT_SIZE=14
def pltlabel(title='', x='', y='', size=FONT_SIZE):
""" this function is used by other functions ... | [
"The problem is that default function argument values are only evaluated once when the function is defined, not each time it is called. So the right-hand side of size=FONT_SIZE is only evaluated once, and that is used as the default value for size for any future function calls.\nYou should use FONT_SIZE as the def... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074342002_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.