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: How to get list of columns containing specific values corresponding to a index as a new column in pandas dataframe? I have a pandas dataframe df which looks as follows: A B C D E F G H I J Values A NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN B NaN NaN NaN NaN...
How to get list of columns containing specific values corresponding to a index as a new column in pandas dataframe?
I have a pandas dataframe df which looks as follows: A B C D E F G H I J Values A NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN B NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN C yes NaN NaN NaN NaN NaN NaN NaN NaN NaN D NaN yes NaN NaN NaN NaN NaN NaN NaN NaN E NaN ...
[ "Dot product of non-NaNness and the columns (suffixed \", \") is a way of doing this:\nIn [242]: df.notna().dot(df.columns + \", \").str[:-2]\nOut[242]:\nA\nB\nC A\nD B\nE B, C\nF\nG D\nH\nI A\nJ\ndtype: object\n\nWhat's happening is that, df.notna() is a True/False dataframe; then we tak...
[ 4, 3 ]
[]
[]
[ "dataframe", "loops", "pandas", "python", "python_3.x" ]
stackoverflow_0074619638_dataframe_loops_pandas_python_python_3.x.txt
Q: SWIG: Passing a list as a vector pointer to a constructor Trying to use swig to pass a python list as input for c++ class with a (one of many) constructor taking a std::vector<double> * as input. Changing the C++ implementation of the codebase is not possible. <EDIT> : What I am looking for is a way to "automatica...
SWIG: Passing a list as a vector pointer to a constructor
Trying to use swig to pass a python list as input for c++ class with a (one of many) constructor taking a std::vector<double> * as input. Changing the C++ implementation of the codebase is not possible. <EDIT> : What I am looking for is a way to "automatically" process a python list to a vector<double> * or say for exa...
[ "The Python list passed into the non-default constructor gets converted to a temporary SWIG proxy of a vector<double>* and that pointer is saved by the constructor into SampleClass's m_v member, but the pointer no longer exists when the constructor returns. If you create a persistent doublevector and make sure it ...
[ 0 ]
[]
[]
[ "c++", "python", "swig" ]
stackoverflow_0074616783_c++_python_swig.txt
Q: How can I join two dataframes in pandas that have different no of rows and different columns? I am trying to build a pandas DataFrame by merging 2 DataFrames consisting of different number of rows. I have attached my code below. Im trying to join these 2 dataframes together but I'm getting an error stating: KeyErr...
How can I join two dataframes in pandas that have different no of rows and different columns?
I am trying to build a pandas DataFrame by merging 2 DataFrames consisting of different number of rows. I have attached my code below. Im trying to join these 2 dataframes together but I'm getting an error stating: KeyError: 'Number of Mutations' #!/usr/bin/env python import pandas as pd df1= pd.DataFrame({"Mutations...
[ "I don't know why you want to combine these df's in the first place, since the rows aren't connected at all. But if you just want to align them next to each other, you want to use pd.concat\nout = pd.concat([df1, df2], axis=1)\nprint(out)\n\n Mutations Number of Mutations Number of Bases\n0 A>T ...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074619081_dataframe_pandas_python.txt
Q: Trouble waiting for changes to complete that are triggered by Python Playwright `select_option` I'm trying to scrape a site that reports internet service availability by address. Addresses can be selected from a list created for a specific postcode. After an address is selected, a table is updated with the availab...
Trouble waiting for changes to complete that are triggered by Python Playwright `select_option`
I'm trying to scrape a site that reports internet service availability by address. Addresses can be selected from a list created for a specific postcode. After an address is selected, a table is updated with the availability of various services. My problem is that I cannot work out how to spot that the table has been u...
[ "Based on @ggorlen's suggestion, I spotted that the select_option triggered a request, which I was able to trigger on, and validate, thus:\n with page.expect_response(lambda response: response.url) as response_info:\n assert loc[0] in response_info.value.url, f\"wrong location {response_info.value...
[ 0 ]
[]
[]
[ "playwright", "playwright_python", "python" ]
stackoverflow_0074618690_playwright_playwright_python_python.txt
Q: How do you type-hint class prototypes that don't otherwise exist? I have legacy code with inheriting dataclasses: @dataclass class Base: a: int @dataclass class Derived1(Base): b: int @dataclass class Derived2(Base): b: int I want to use Python type hints so that methods know when they're getting so...
How do you type-hint class prototypes that don't otherwise exist?
I have legacy code with inheriting dataclasses: @dataclass class Base: a: int @dataclass class Derived1(Base): b: int @dataclass class Derived2(Base): b: int I want to use Python type hints so that methods know when they're getting something with a b attribute. However, I cannot import actual Derived1 o...
[ "Use typing.Protocol:\nfrom typing import Protocol\n\n\nclass SupportsB(Protocol):\n b: int\n\n" ]
[ 0 ]
[]
[]
[ "python", "python_typing" ]
stackoverflow_0074619783_python_python_typing.txt
Q: How to label edges and avoid the edge overlapping in MultiDiGraph/DiGraph? (Networkx) Here is my code now G = nx.from_pandas_edgelist(data, source='grad', target='to', edge_attr='count', create_using=nx.DiGraph()) weight = nx.get_edge_attributes(G, 'c...
How to label edges and avoid the edge overlapping in MultiDiGraph/DiGraph? (Networkx)
Here is my code now G = nx.from_pandas_edgelist(data, source='grad', target='to', edge_attr='count', create_using=nx.DiGraph()) weight = nx.get_edge_attributes(G, 'count') pos = nx.shell_layout(G, scale=1) nx.draw_networkx_nodes(G, pos, node_size=300, node...
[ "Here's a solution to issues 1 and 2. In my version of networkx, self-loops are displayed.\nimport pandas as pd\nimport networkx as nx\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nd = {'grad': {0: 'CUHK', 1: 'CUHK', 2: 'CUHK', 3: 'CUHK', 4: 'CUHK', 5: 'CUHK', 6: 'CUHK', 7: 'CUHK', 8: 'CityU', 9: 'CityU',...
[ 1 ]
[]
[]
[ "networkx", "python" ]
stackoverflow_0074618675_networkx_python.txt
Q: Extracting data from JSON log I am a beginner when it comes to programming. I'm trying to extract elements from a JSON log file, but I get an error and I don't know how to deal with it. import json with open("/Users/milosz/Desktop/logi.json") as f: data = json.load(f) print(type(data['Objects'])) print(data) ...
Extracting data from JSON log
I am a beginner when it comes to programming. I'm trying to extract elements from a JSON log file, but I get an error and I don't know how to deal with it. import json with open("/Users/milosz/Desktop/logi.json") as f: data = json.load(f) print(type(data['Objects'])) print(data) for object in data ['Objects']: ...
[ "Following up on the guidance from @accdias, here is a code snippet that closes the gaps in your JSON snippet and demonstrates how to access the Objects section:\nimport json\n\njson_string = \"\"\"\n{\n \"_id\": \"635bd4bfc594743ce9b1a5a3\",\n \"dateStart\": \"2022-10-28T13:09:28.609Z\",\n \"dateFinish\":...
[ 0 ]
[]
[]
[ "json", "python" ]
stackoverflow_0074619451_json_python.txt
Q: how to predict my own image using cnn in keras after training on MNIST dataset I have made a convolutional neural network to predict handwritten digits using MNIST dataset but now I am stuck at predicting my own image as input to cnn,I have saved weights after training cnn and want to use that to predict my own im...
how to predict my own image using cnn in keras after training on MNIST dataset
I have made a convolutional neural network to predict handwritten digits using MNIST dataset but now I am stuck at predicting my own image as input to cnn,I have saved weights after training cnn and want to use that to predict my own image (NOTE : care is taken that my input image is 28x28) code: new_mnist.py : ap = ar...
[ "Try:\npr = model.predict_classes(im.reshape((1, 1, 28, 28)))\n\nHere : first dimension comes from examples (you need to specify it even if you have only one example), second comes from channels (as it seems that you use Theano backend) and rest are spatial dimensions.\n", "It should be noted that the images must...
[ 6, 0 ]
[]
[]
[ "conv_neural_network", "keras", "machine_learning", "neural_network", "python" ]
stackoverflow_0043076259_conv_neural_network_keras_machine_learning_neural_network_python.txt
Q: How to use my own Meta class together with SQLAlchemy-Model as a parent class I recently started to use Flask as my back-end framework. However, recently I encountered a problem and I could not figure out how to solve it. As a last resort I wanted to try my change here. If you could help me with it, I would be gra...
How to use my own Meta class together with SQLAlchemy-Model as a parent class
I recently started to use Flask as my back-end framework. However, recently I encountered a problem and I could not figure out how to solve it. As a last resort I wanted to try my change here. If you could help me with it, I would be grateful. So, I have a class that inherits from SQLAlchemy's db.Model: from flask_sqla...
[ "Finally I managed to solve my problem. In case anyone else encounters the same issue, I am posting a solution here.\nThis is a snipped that is taken from SQLAlchemy's website:\n\nThe model metaclass is responsible for setting up the SQLAlchemy internals when defining model subclasses. Flask-SQLAlchemy adds some ex...
[ 3, 0, 0 ]
[]
[]
[ "metaclass", "python", "sqlalchemy", "types" ]
stackoverflow_0055925297_metaclass_python_sqlalchemy_types.txt
Q: get() function in Tkinter always returns 0 i want to get the contents of an entry box and when i use the .get() function it always return 0 doesnt matter what i write in the box window1 = Tk() window1.geometry("500x720+750+0") entry1 = IntVar() e1 = tk.Entry(window1, width=8,fg="darkblue", textvariable=entry1, fon...
get() function in Tkinter always returns 0
i want to get the contents of an entry box and when i use the .get() function it always return 0 doesnt matter what i write in the box window1 = Tk() window1.geometry("500x720+750+0") entry1 = IntVar() e1 = tk.Entry(window1, width=8,fg="darkblue", textvariable=entry1, font=('secular one', 13)).place(x=20, y=60) num_of_...
[ "You need to call get() inside the get_value() function\nUPDATE - I misread the code previously - this should work now.\nFYI:\n\nYou don't need an IntVar to store the value of the Entry, you can just call get() directly and do away with setting the textvariable parameter\nYou should make a habit of declaring your w...
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074619917_python_tkinter.txt
Q: Cannot send message in a loop using whatsapp automation (selenium) I am using this code to automate WhatsApp message sending, But the loop applied to send a message number of times is not working properly. It just sends a message once and stops. Kindly help! Following is the code: from selenium import webdriver fr...
Cannot send message in a loop using whatsapp automation (selenium)
I am using this code to automate WhatsApp message sending, But the loop applied to send a message number of times is not working properly. It just sends a message once and stops. Kindly help! Following is the code: from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webd...
[ "Try locating the message_box inside the loop.\nAlso, you have to improve your locators.\nAnd it should be element_to_be_clickable expected condition there, not just presence_of_element_located.\nSo, please try this code:\nmessage_box_path='//footer//p'\nfor x in range(5):\n message_box=wait.until(EC.element_to_...
[ 0 ]
[]
[]
[ "automation", "python", "selenium", "selenium_webdriver", "whatsapp" ]
stackoverflow_0074619781_automation_python_selenium_selenium_webdriver_whatsapp.txt
Q: Getting final weights and biases values from neural network MLPClassifier From the documentation https://scikit-learn.org/stable/modules/generated/sklearn.neural_network.MLPClassifier.html it is not clear whether the attributes coefs_ and intercepts_ are the initial ones (before the neural network is estimated) or...
Getting final weights and biases values from neural network MLPClassifier
From the documentation https://scikit-learn.org/stable/modules/generated/sklearn.neural_network.MLPClassifier.html it is not clear whether the attributes coefs_ and intercepts_ are the initial ones (before the neural network is estimated) or the final ones (after the neural network is estimated). In case they are the f...
[ "The attributes coefs_ and intercepts_ are the final ones. Indeed, by design\n\nAttributes that have been estimated from the data must always have a name ending with trailing underscore.\n\nThe starting values of such parameters are not exposed via a public attribute or method; instead, they are exploiting the _ini...
[ 1 ]
[]
[]
[ "python", "scikit_learn" ]
stackoverflow_0074618826_python_scikit_learn.txt
Q: How to assertRaises in unittest an exception caught in try except block? In my production function: def myfunction(): try: do_stuff() (...) raise MyException("...") except MyException as exception: do_clean_up(exception) My test fails, because the exception is caught in the...
How to assertRaises in unittest an exception caught in try except block?
In my production function: def myfunction(): try: do_stuff() (...) raise MyException("...") except MyException as exception: do_clean_up(exception) My test fails, because the exception is caught in the try/except block def test_raise(self): with self.assertRaises(MyException)...
[ "This is because you caught the exception MyException direct in myFunction().\nComment out out the try-except clause and try again, test should pass.\nassertRaises is used for uncaught errors. You can also re-raise in except block.\n", "The exception is handled internally, so there is no external evidence that th...
[ 1, 0 ]
[]
[]
[ "exception", "python", "python_unittest", "unit_testing" ]
stackoverflow_0074605367_exception_python_python_unittest_unit_testing.txt
Q: Create index on nested element JSONField for Postgres in Django I have a Django model in my python project with a meta class detailing it's indexes. I'm curious if there's a way to create the index using the nested path of the json object. In this case we know the structure of our json and I wanted to stick with a...
Create index on nested element JSONField for Postgres in Django
I have a Django model in my python project with a meta class detailing it's indexes. I'm curious if there's a way to create the index using the nested path of the json object. In this case we know the structure of our json and I wanted to stick with a BTree or Hash index on the specific element. If I were simply runnin...
[ "Django 3.2 introduced native support for these indexes.\nThe question as asked presently doesn't seem to have the definition of the JSONField, but assuming it is something like\nfrom django.db import models\n\nclass Facilitators(models.Model):\n foster_data = models.JSONField()\n\nTo index a particular key, you...
[ 0 ]
[]
[]
[ "django", "postgresql", "python" ]
stackoverflow_0071974662_django_postgresql_python.txt
Q: Need help printing result of __str__ function in Python I'm working on a problem with classes, but I'm stuck on defining the __str__ function so that returns the capitalized version of whatever text within the class. Currently I have an excruciatingly difficult code that works in PyCharm but not in my class's auto...
Need help printing result of __str__ function in Python
I'm working on a problem with classes, but I'm stuck on defining the __str__ function so that returns the capitalized version of whatever text within the class. Currently I have an excruciatingly difficult code that works in PyCharm but not in my class's automatic checking system. Can I get some advice on how to fix th...
[ "__str__ canonically doesn't accept any arguments.\nSince you're subclassing str, you probably mean\nclass X(str):\n def __str__(self):\n return self.capitalize()\n\nb = X('hello')\nprint(b.__str__()) \n# or print(str(b))\n# or print(b)\n\ni.e. to override the __str__ magic method in a way that uses the ...
[ 4 ]
[]
[]
[ "class", "oop", "python" ]
stackoverflow_0074619971_class_oop_python.txt
Q: Member Avatar doesn't appear in the welcome embed I am trying to make my bot send a welcome message when someone joins a specific server. Code: if member.guild.id == 928443083660607549: new = nextcord.utils.get(member.guild.roles, name="new") channel = bot.get_channel(996767690091925584) em...
Member Avatar doesn't appear in the welcome embed
I am trying to make my bot send a welcome message when someone joins a specific server. Code: if member.guild.id == 928443083660607549: new = nextcord.utils.get(member.guild.roles, name="new") channel = bot.get_channel(996767690091925584) embed = nextcord.Embed(title="welcome to ikari!", descrip...
[ "Discord.py v2 changed the variables. Meaning that .avatar_url is now .avatar.url. .icon_url is now .icon.url. Hence meaning that member.display_avatar.url is what you're looking for.\nThis also means that stuff like .avatar_with_size(...) for example have now been changed to .avatar.with_size(...). Just for future...
[ 1, 0 ]
[]
[]
[ "discord", "nextcord", "python" ]
stackoverflow_0074587092_discord_nextcord_python.txt
Q: multiply 2 columns until get a desired value Greeting everyone, I have this table (Without the Res_Problem): ID Problem X Impact Prob Res_Problem ID1 12 IDC1 1 2 (12-2)=10 ID1 12 IDC2 2 2 (10-4)=6 STOP ID1 12 IDC3 1 0 NO LOOP ID1 12 IDC4 1 0 NO LOOP ID2 10 IDB1 1 2 New Loop (10-2)=8 ID2 10 IDB1 1 2 (8-2) = ...
multiply 2 columns until get a desired value
Greeting everyone, I have this table (Without the Res_Problem): ID Problem X Impact Prob Res_Problem ID1 12 IDC1 1 2 (12-2)=10 ID1 12 IDC2 2 2 (10-4)=6 STOP ID1 12 IDC3 1 0 NO LOOP ID1 12 IDC4 1 0 NO LOOP ID2 10 IDB1 1 2 New Loop (10-2)=8 ID2 10 IDB1 1 2 (8-2) = 6 STOP I want to do a loop that mul...
[ "Here is one option:\ns = (df['Problem']\n .sub(df['Impact'].mul(df['Prob'])\n .groupby(df['ID']).cumsum()\n )\n)\n\nm = s.le(6).groupby(df['ID']).shift(fill_value=False)\n\ndf['Res_Problem'] = s.mask(m)\n\noutput:\n ID Problem X Impact Prob Res_Problem\n0 ID1 12 IDC1 1 2 ...
[ 5 ]
[]
[]
[ "dataframe", "numpy", "pandas", "python", "while_loop" ]
stackoverflow_0074619855_dataframe_numpy_pandas_python_while_loop.txt
Q: How to Add another level of column to an existing multi-level column I have a data frame that looks like this: x A B 0 0 1 1 2 3 2 4 5 3 6 7 4 8 9 When I want to add another level to the multi-level columns using the following code x.columns = pd.MultiIndex.from_product([['D'], x.columns]) it...
How to Add another level of column to an existing multi-level column
I have a data frame that looks like this: x A B 0 0 1 1 2 3 2 4 5 3 6 7 4 8 9 When I want to add another level to the multi-level columns using the following code x.columns = pd.MultiIndex.from_product([['D'], x.columns]) it gives me the following error Traceback (most recent call last): File "C...
[ "You need to do this:\n x.columns = pd.MultiIndex.from_product([['D'], *x.columns.levels])\n\nwhere x.columns.levels gives you a Frozenlist of columns that form the MultiIndex.\nAnd then you have to unpack the list using * in order to pass list of lists to from_product.\n", "You can denote a multi-level column wi...
[ 3, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074619620_dataframe_pandas_python.txt
Q: python error : missing 1 required positional argument: 'self' I am really new(beginner) in Python and I am trying to implement an optimization problem using the pyomo library, in colab notebook. The goal is to implement in pyomo the elastic net problem https://en.wikipedia.org/wiki/Elastic_net_regularization and t...
python error : missing 1 required positional argument: 'self'
I am really new(beginner) in Python and I am trying to implement an optimization problem using the pyomo library, in colab notebook. The goal is to implement in pyomo the elastic net problem https://en.wikipedia.org/wiki/Elastic_net_regularization and then run it for λ=1 with a=1. I have written the following implement...
[ "The comment above is correct. The source of your problems is that you used this:\nmodel = pyo.ConcreteModel\n\ninstead of this:\nmodel = pyo.ConcreteModel()\n\nTo explain what happens when you do this... You have unwittingly created an \"alias\" for the function ConcreteModel, which is obviously not what you int...
[ 1 ]
[]
[]
[ "pyomo", "python" ]
stackoverflow_0074617125_pyomo_python.txt
Q: String formatting in Python version earlier than 2.6 When I run the following code in Python 2.5.2: for x in range(1, 11): print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x) I get: Traceback (most recent call last): File "<pyshell#9>", line 2, in <module> print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*...
String formatting in Python version earlier than 2.6
When I run the following code in Python 2.5.2: for x in range(1, 11): print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x) I get: Traceback (most recent call last): File "<pyshell#9>", line 2, in <module> print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x) AttributeError: 'str' object has no attribute 'format' ...
[ "The str.format method was introduced in Python 3.0, and backported to Python 2.6 and later.\n", "Your example code seems to be written for Python 2.6 or later, where the str.format method was introduced.\nFor Python versions below 2.6, use the % operator to interpolate a sequence of values into a format string:\...
[ 48, 38, 8, 7, 7 ]
[ "Use this:\nprint \"test some char {} and also number {}\".format('a', 123)\n\nresult:\n\ntest some char a and also number 123\n\n" ]
[ -1 ]
[ "format", "python" ]
stackoverflow_0000792721_format_python.txt
Q: Running python interpreter in shell from a make file I want to call a python interpreter in a shell, from an android make file. Initially I tried this: $(shell python -c "import sys;print('hello')") The result is an error: Android.mk:150: *** missing separator. Stop. I suspect this is caused by ndk-build misint...
Running python interpreter in shell from a make file
I want to call a python interpreter in a shell, from an android make file. Initially I tried this: $(shell python -c "import sys;print('hello')") The result is an error: Android.mk:150: *** missing separator. Stop. I suspect this is caused by ndk-build misinterpreting nested quotes. I couldn't find an alternative th...
[ "To use the $() in Makefiles, you have to declare a variable like this HELLO = $(shell python -c \"import sys;print('hello')\"), and now HELLO has the value of \"hello\"\nIf you want to print something on the screen, just use echo or printf in the target's script\n" ]
[ 1 ]
[]
[]
[ "android_ndk", "makefile", "ndk_build", "python" ]
stackoverflow_0074619600_android_ndk_makefile_ndk_build_python.txt
Q: How do I return an image in fastAPI? Using the python module fastAPI, I can't figure out how to return an image. In flask I would do something like this: @app.route("/vector_image", methods=["POST"]) def image_endpoint(): # img = ... # Create the image here return Response(img, mimetype="image/png") what'...
How do I return an image in fastAPI?
Using the python module fastAPI, I can't figure out how to return an image. In flask I would do something like this: @app.route("/vector_image", methods=["POST"]) def image_endpoint(): # img = ... # Create the image here return Response(img, mimetype="image/png") what's the corresponding call in this module?
[ "If you already have the bytes of the image in memory\nReturn a fastapi.responses.Response with your custom content and media_type.\nYou'll also need to muck with the endpoint decorator to get FastAPI to put the correct media type in the OpenAPI specification.\n@app.get(\n \"/image\",\n\n # Set what the media...
[ 67, 66, 37, 34, 17, 13, 4, 3, 1, 0 ]
[]
[]
[ "api", "fastapi", "python" ]
stackoverflow_0055873174_api_fastapi_python.txt
Q: Google Cloud Pub/Sub error "Closed subscriber cannot be used as context manager" when trying to unsubscribe I'm getting the following error when trying to unsubscribe from a topic in Google Pub/Sub. self = <google.cloud.pubsub_v1.SubscriberClient object at 0x000002069A31D820> def __enter__(self) -> "Client": ...
Google Cloud Pub/Sub error "Closed subscriber cannot be used as context manager" when trying to unsubscribe
I'm getting the following error when trying to unsubscribe from a topic in Google Pub/Sub. self = <google.cloud.pubsub_v1.SubscriberClient object at 0x000002069A31D820> def __enter__(self) -> "Client": if self._closed: > raise RuntimeError("Closed subscriber cannot be used as context manager.") E...
[ "Well, Google's own documentation states that the code I was using would automatically close the subscription because of the with block. For some reason I kept overlooking that comment in the code.\nThis resolved my issue:\n def unsubscribe(self, subscription_id):\n subscriber = self.subscriber\n\n ...
[ 0 ]
[]
[]
[ "google_cloud_pubsub", "python" ]
stackoverflow_0074212699_google_cloud_pubsub_python.txt
Q: How edit a discord message using the message's id or link using discord.py I have discord messaged that was send a few weeks ago by my bot and now I want to update that message but I don't want to delete the message I want to edit it. I though the only way to find that message is using the message's id or link but...
How edit a discord message using the message's id or link using discord.py
I have discord messaged that was send a few weeks ago by my bot and now I want to update that message but I don't want to delete the message I want to edit it. I though the only way to find that message is using the message's id or link but I don't know how I can do that.
[ "Once you have the ID of the message you want to edit, just go:\nawait msg.edit(content=\"Edit\")\n\nObviously, edit content to what you want. Also remember, you can only edit messages you have sent, so make sure the bot has sent that message.\n" ]
[ 0 ]
[]
[]
[ "discord", "python" ]
stackoverflow_0074580195_discord_python.txt
Q: Convert html to json in Python I am trying to convert some html files to json. From the beginning: I downloaded a kind of old dataset called SarcasmAmazonReviewsCorpus. It has several txt files, all with comments, reactions, name of product and so on, as it follows in the image: I was able to pick up each txt fil...
Convert html to json in Python
I am trying to convert some html files to json. From the beginning: I downloaded a kind of old dataset called SarcasmAmazonReviewsCorpus. It has several txt files, all with comments, reactions, name of product and so on, as it follows in the image: I was able to pick up each txt file and using os module I created a li...
[ "You might have to change soup.find in dictionary to get the data you want.\nimport json\n\ndictionary = {\n \"title\": soup.find(\"title\"),\n \"date\": soup.find(\"date\")\n}\n\njson_object = json.dumps(dictionary, indent=4)\n\nwith open(\"saveFile.json\", \"w\") as outfile:\n outfile.write(json_object)\...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074619838_python.txt
Q: Python - rearranging dataframe data I wanna rearrange my dataframe from the left one to the right table, like I show you in the next picture: df = pd.DataFrame({ "Unnamed:0": ["Entity","","Var1","Var2","Var3","Var4"], "Unnamed:1": ["A","X","0.45","0.14","0.16","0.28"], "Unnamed:2": ["A","Y","0.66","0.55","0.39","...
Python - rearranging dataframe data
I wanna rearrange my dataframe from the left one to the right table, like I show you in the next picture: df = pd.DataFrame({ "Unnamed:0": ["Entity","","Var1","Var2","Var3","Var4"], "Unnamed:1": ["A","X","0.45","0.14","0.16","0.28"], "Unnamed:2": ["A","Y","0.66","0.55","0.39","0.49"], "Unnamed:3": ["A","Z","0.3","0.24...
[ "As your dataframe is not clean (the 2 first rows are a multiindex column name), you can first create the inner dataframe before melting it :\nnew_df = pd.DataFrame(df.iloc[2:,1:]).set_index(df.iloc[2:,0])\nnew_df.columns = pd.MultiIndex.from_frame(df.iloc[:2,1:].T)\nnew_df.melt(ignore_index=False).reset_index()\n\...
[ 0 ]
[]
[]
[ "database", "dataframe", "pandas", "pandas_melt", "python" ]
stackoverflow_0074619534_database_dataframe_pandas_pandas_melt_python.txt
Q: how to use beautiful soup to get all text "except" a specific class I'm trying to use soup.get_text to get some text out of a webpage, but I want to exclude a specific class. I tried to use a = soup.find_all(class_ = "something") and b=[i.get_text() for i in a], but that allows me to choose one class, and doesn't ...
how to use beautiful soup to get all text "except" a specific class
I'm trying to use soup.get_text to get some text out of a webpage, but I want to exclude a specific class. I tried to use a = soup.find_all(class_ = "something") and b=[i.get_text() for i in a], but that allows me to choose one class, and doesn't allow me to exclude one specific class. I also tried: a = soup.select('sp...
[ "If you want to get all classes but one for example, you can loop through all element and choose the ones you keep:\nfor p in soup.find_all(\"p\", \"review_comment\"):\n if p.find(class_=\"something-archived\"):\n continue\n # p is now a wanted p\n\nsource: Excluding unwanted results of findAll using B...
[ 1 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0074620106_beautifulsoup_python.txt
Q: How can I sort 2d array includes only string characters in Python? There is an array as below; x=np.array([ ['0', '0'], ['1', '1'], ['7', '10'], ['8', '11'], [',', '2'], ['4', '3'], ['.', '4'], ['2', '5'], ['5',...
How can I sort 2d array includes only string characters in Python?
There is an array as below; x=np.array([ ['0', '0'], ['1', '1'], ['7', '10'], ['8', '11'], [',', '2'], ['4', '3'], ['.', '4'], ['2', '5'], ['5', '6'], ['er014', '7'], ['ww', '8'], ...
[ "np.take(x, x[:, 1].astype(int).argsort(), 0)\nYou may just cast the values for sorting. The overall result of you np.take() will remain as strings.\narray([['0', '0'],\n ['1', '1'],\n [',', '2'],\n ['4', '3'],\n ['.', '4'],\n ['2', '5'],\n ['5', '6'],\n ['er014', '7'],\n ['ww', '8'],\n ['*', '9']...
[ 1 ]
[]
[]
[ "np.argsort", "numpy", "python" ]
stackoverflow_0074620197_np.argsort_numpy_python.txt
Q: Query unique values inside django forloop I have a query where I should avoid double entry of the same question. In fact, I would like to get only unique values but, I am using the distinct() django function which isn't working. I have these models: class QuestionTopic(models.Model): name = models.CharField(ma...
Query unique values inside django forloop
I have a query where I should avoid double entry of the same question. In fact, I would like to get only unique values but, I am using the distinct() django function which isn't working. I have these models: class QuestionTopic(models.Model): name = models.CharField(max_length=255) question_subject = models.For...
[ "Just make questions_list a set:\nquestions_list = set()\n\nSets don't allow a value more than once.\n", "You can work with a single query with:\nsubject = QuestionSubject.objects.get(id=request.POST.get('subject'))\nquestion_topics = QuestionTopic.objects.filter(question_subject=subject)\nquestions_list = [\n ...
[ 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074606914_django_python.txt
Q: How to get the a href link from under the div class? using beautiful soup I am trying to scrape the href attribute from links from a page, but I end up with [] as the output The HTML code is My desired output is: https://www.pigiame.co.ke/listings/nissan-latio-2016-36000-kms-5300124 A: You can try: import re imp...
How to get the a href link from under the div class? using beautiful soup
I am trying to scrape the href attribute from links from a page, but I end up with [] as the output The HTML code is My desired output is: https://www.pigiame.co.ke/listings/nissan-latio-2016-36000-kms-5300124
[ "You can try:\nimport re\nimport requests\nimport urllib.parse\nfrom bs4 import BeautifulSoup\n\nurl = \"https://www.pigiame.co.ke/cars\"\n\nheaders = {\n \"User-Agent\": \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:107.0) Gecko/20100101 Firefox/107.0\",\n}\n\nsoup = BeautifulSoup(requests.get(url, headers=heade...
[ 0 ]
[]
[]
[ "beautifulsoup", "css_selectors", "html", "python", "web_scraping" ]
stackoverflow_0074620047_beautifulsoup_css_selectors_html_python_web_scraping.txt
Q: Try to extract paragraph using beautiful soup from selenium import webdriver import time from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from webdriver_manager.chrome import ChromeDriverManager from bs4 import BeautifulSoup from selenium.webdriver.support import ex...
Try to extract paragraph using beautiful soup
from selenium import webdriver import time from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from webdriver_manager.chrome import ChromeDriverManager from bs4 import BeautifulSoup from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.chr...
[ "\nActually, detailed paragraph is visualized in the html dom and click on thereviews just go down to the page and the jab can be done by scrolling button too.The subject matter is that clicking on reviews will not work rather will create exception.\n\nThe big problem is to select the virtual games paragraph html n...
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074610162_beautifulsoup_python_web_scraping.txt
Q: Python, most compact&efficeint way of checking if an item is any of the lists (which are inside dictionaries)? I have a dictionary with lists (with strings inside) and I need I need to check if a string appears anywhere among those lists. Here is an example classes = { "class_A" : ["Mike","Alice","Peter"], "cl...
Python, most compact&efficeint way of checking if an item is any of the lists (which are inside dictionaries)?
I have a dictionary with lists (with strings inside) and I need I need to check if a string appears anywhere among those lists. Here is an example classes = { "class_A" : ["Mike","Alice","Peter"], "class_B" : ["Sam","Robert","Anna"], "class_C" : ["Tom","Nick","Jack"] } students=["Alice","Frodo","Jack"] for stude...
[ "If a generator expression is acceptable with regards to your requirements, then:\ndef check(student, classes):\n return any(student in value for value in classes.values())\n\nAnd to get a boolean for each student, you could create this function:\ndef checkall(students, classes):\n return [any(student in value fo...
[ 3, 0, 0, 0, 0, 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0074620209_dictionary_list_python.txt
Q: how to run a function in python for a specified time interval I want to run a function for only n number of seconds after which the function shouldn't run anymore while in the background other functions should continue running. I've tried using the time.time() function with the while loop but other functions in th...
how to run a function in python for a specified time interval
I want to run a function for only n number of seconds after which the function shouldn't run anymore while in the background other functions should continue running. I've tried using the time.time() function with the while loop but other functions in the background doesn't run and I want it such a way that even other f...
[ "use threading and the timeout parameter for join https://docs.python.org/3/library/threading.html#threading.Thread.start\nfrom threading import Thread\nimport time\ndef A():\n while True:\n time.sleep(2)\ndef B():\n while True:\n time.sleep(1)\ndef C():\n while True:\n time.sleep(1)\n\nt_a = Thread(tar...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074620402_python.txt
Q: Conda environments only working with base version Python I have started to learn how to work with creating new virtual environments. However whenever I try to launch a Jupyter Notebook I find that going through the dropdown menu and selecting the kernel name results in Kernel starting, please wait... followed by...
Conda environments only working with base version Python
I have started to learn how to work with creating new virtual environments. However whenever I try to launch a Jupyter Notebook I find that going through the dropdown menu and selecting the kernel name results in Kernel starting, please wait... followed by connection failed. Very simply my approach is: conda create -...
[ "This ended up being very straight forward. While I feel a bit silly I didn't click at first I learnt a fair bit about virtual environments in the process!\nAll that was necessary was to simply run the following once I had activated the environment (in Anaconda prompt)\njupyter notebook\n\nThe problem was that I wa...
[ 0, 0 ]
[]
[]
[ "anaconda", "conda", "jupyter_notebook", "python" ]
stackoverflow_0068076724_anaconda_conda_jupyter_notebook_python.txt
Q: Django models relation The idea is that there are two models: Group and Player. My objective is that there are different Groups and each group has players. Each player can belong to one or more groups. Inside a group, each player has some points accumulated, but the same player can have different points accumulate...
Django models relation
The idea is that there are two models: Group and Player. My objective is that there are different Groups and each group has players. Each player can belong to one or more groups. Inside a group, each player has some points accumulated, but the same player can have different points accumulated in another group. class Pl...
[ "You can tell Django to use a custom model for the many to many relationship using through parameter in that field, this way:\n\nclass Player(models.Model):\n username = models.CharField(max_length = 200)\n won_games = models.IntegerField(default=0)\n\n\nclass Group(models.Model):\n id = models.CharField(m...
[ 0, 0 ]
[]
[]
[ "django", "django_models", "django_rest_framework", "python" ]
stackoverflow_0074620380_django_django_models_django_rest_framework_python.txt
Q: Python - automatically apply Excel filters to .csv files/method to convert hh:mm:ss time string to integer? I have a ton of VOIP analytics to process, all in .csv format. All calls are formatted as rows, and I need to isolate rows with cells that match the strings "Answered" and "Terminating", and with call durati...
Python - automatically apply Excel filters to .csv files/method to convert hh:mm:ss time string to integer?
I have a ton of VOIP analytics to process, all in .csv format. All calls are formatted as rows, and I need to isolate rows with cells that match the strings "Answered" and "Terminating", and with call duration <= 00:00:30. I've been combing through Python libraries to find one that can quickly and easily apply the nece...
[ "Using Miller at command line to filter a CSV and capture all rows with time <= 00:00:30.\ncat time_select.csv\nid,time_val\n1,00:00:01\n2,00:00:02\n3,00:00:03\n4,00:00:04\n5,00:00:05\n6,00:00:06\n7,00:00:07\n8,00:00:08\n9,00:00:09\n10,00:00:10\n...\n50,00:00:50\n51,00:00:51\n52,00:00:52\n53,00:00:53\n54,00:00:54\n...
[ 0 ]
[]
[]
[ "csv", "excel", "python", "python_3.x" ]
stackoverflow_0074605396_csv_excel_python_python_3.x.txt
Q: Pyserial write data to serial port It´s my first time working with pyserial. I made an simple gui with pysimplegui and now I´d like to write the data from the sliders to the serial monitor. How can I do it? import PySimpleGUI as sg import serial font = ("Courier New", 11) sg.theme("DarkBlue3") sg.set_options(font...
Pyserial write data to serial port
It´s my first time working with pyserial. I made an simple gui with pysimplegui and now I´d like to write the data from the sliders to the serial monitor. How can I do it? import PySimpleGUI as sg import serial font = ("Courier New", 11) sg.theme("DarkBlue3") sg.set_options(font=font) ser = serial.Serial("COM6") ser....
[ "There are 2 issues with the code here:\n\nVariable data has a type of tuple, not a number.\nEach member of the tuple is a float as the TypeError indicates.\n\nYou will need to pass one value at a time to ser.write. And you will need to cast the float returned by the slider widget to an integer. Something like the ...
[ 0 ]
[]
[]
[ "pyserial", "pysimplegui", "python", "python_3.x" ]
stackoverflow_0074619830_pyserial_pysimplegui_python_python_3.x.txt
Q: Chain assignment in Python for list I am trying to understand chain assignment in Python. If I run x = x[1] = [1, 2], I get an infinite list [1, [...]]. But if I run x = x[1:] = [1, 2], I will get a normal list [1, 1, 2]. How does it work in the background to make these two different results? A: First, understan...
Chain assignment in Python for list
I am trying to understand chain assignment in Python. If I run x = x[1] = [1, 2], I get an infinite list [1, [...]]. But if I run x = x[1:] = [1, 2], I will get a normal list [1, 1, 2]. How does it work in the background to make these two different results?
[ "First, understand that in a chained assignment, the right-most expression is evaluated to an object. A reference to that object is then assigned to each target in sequence, from left to right. x = y = z is effectively the same as\nt = z # A new temporary variable \"t\" to hold the result of evaluating z\nx = t\ny ...
[ 3, 0, 0 ]
[]
[]
[ "infinite_loop", "python", "variable_assignment" ]
stackoverflow_0074620364_infinite_loop_python_variable_assignment.txt
Q: How to separate the data_time colum by days from a dataframe I have a dataframe and I need to find the most acess hour from the day. I think i need to do some for loops to store the values and after find the most acess hour. My code until now is: df['date_time'] = pd.to_datetime(df['date_time']) This me return: 0...
How to separate the data_time colum by days from a dataframe
I have a dataframe and I need to find the most acess hour from the day. I think i need to do some for loops to store the values and after find the most acess hour. My code until now is: df['date_time'] = pd.to_datetime(df['date_time']) This me return: 0 2022-11-24 19:18:37 1 2022-11-25 00:45:35 2 2022-11-2...
[ "I would suggest to group by day and take mode on hours:\ndf['date_time'] = pd.to_datetime(df['date_time'])\ndf['date'] = df['date_time'].dt.day\ndf['hour'] = df['date_time'].dt.hour\ndf_groupped = df.groupby(df['date'])['hour'].agg(pd.Series.mode)\n\n", "You can use pandas.DataFrame.groupby with .dt accessors.\n...
[ 1, 1 ]
[]
[]
[ "dataframe", "datetime", "pandas", "python" ]
stackoverflow_0074620285_dataframe_datetime_pandas_python.txt
Q: nested dictionary from nested lister as follow (python) Been struggling with this issue, so I hope I get some help taken the following lister: Buildings = ['nr1','nr2','n3'] offices = [1,3,2] area=[23,[67,77,94],[78,79]] price=[45,[43,89,56],[54,53]] employees=[56,[45,54,78],[56,89]] I would like to create follow...
nested dictionary from nested lister as follow (python)
Been struggling with this issue, so I hope I get some help taken the following lister: Buildings = ['nr1','nr2','n3'] offices = [1,3,2] area=[23,[67,77,94],[78,79]] price=[45,[43,89,56],[54,53]] employees=[56,[45,54,78],[56,89]] I would like to create following dictionary { {'build nr1': { 'office 1': ...
[ "Maybe this is the code you are looking for:\nimport json\n\n\nBuildings = ['nr1','nr2','nr3']\noffices = [1,3,2]\narea=[23,[67,77,94],[78,79]]\nprice=[45,[43,89,56],[54,53]]\nemployees=[56,[45,54,78],[56,89]]\n\nmyDict = dict()\n\nfor building, office in zip(Buildings, offices):\n myDict[f\"Build {building}\"] ...
[ 0 ]
[]
[]
[ "dictionary", "nested_lists", "python" ]
stackoverflow_0074620205_dictionary_nested_lists_python.txt
Q: python pymssql returns list comma separated, how to change the separator to i.e pipe? I checked pymssql documents for parameters but I couldn't find what I was looking for. Basically when I execute the cursor with my SQL query, I always receive the list as comma separated. I'd like to change comma to another separ...
python pymssql returns list comma separated, how to change the separator to i.e pipe?
I checked pymssql documents for parameters but I couldn't find what I was looking for. Basically when I execute the cursor with my SQL query, I always receive the list as comma separated. I'd like to change comma to another separator since some name fields contains comma. Is there a way to do that? This is what I have:...
[ "I'm making an assumption based on your comment about the need for a non-comma separator to avoid conflicts with the commas in your fields that you would be okay with something like this:\nrows = [('Name,1', '20221110'), ('Name2', '20221115')]\nfor r in rows:\n print(\"|\".join(r))\n\nOutput:\nName,1|20221110\nN...
[ 0 ]
[]
[]
[ "pymssql", "python" ]
stackoverflow_0074620520_pymssql_python.txt
Q: How to concatenate 2 dict in Python with concat I have 2 dict objects with the same key but different elements.I would like to merge them into one dict. First, I used append and it works but append is deprecated so that I prefer to use concat. here is the code : data1 = {'a':1, 'b':2} data2 = {'a':3, 'b':4} list...
How to concatenate 2 dict in Python with concat
I have 2 dict objects with the same key but different elements.I would like to merge them into one dict. First, I used append and it works but append is deprecated so that I prefer to use concat. here is the code : data1 = {'a':1, 'b':2} data2 = {'a':3, 'b':4} list = [data1, data2] df = pd.DataFrame() for x in range...
[ "The following code works but may not be very efficient:\ndata1 = {'a':1, 'b':2}\ndata2 = {'a':3, 'b':4}\n\nlist = [data1, data2]\ndf = pd.concat([pd.DataFrame(list[i], index=[i]) for i in range(len(list))])\n\nprint(df)\n\n", "Here is a proposition using pandas.concat with pandas.DataFrame.unstack :\nlist_of_dic...
[ 0, 0 ]
[]
[]
[ "concatenation", "dataframe", "pandas", "python", "python_3.x" ]
stackoverflow_0074620471_concatenation_dataframe_pandas_python_python_3.x.txt
Q: script that checks if another script has an error, then kills and restarts screen and script I have a matlab scipt on a cluster that pings an API, but after a couple hours (2-4h), the script will have an unexpected error which we believe comes from pinging the API too many times. I want to create a script (not sur...
script that checks if another script has an error, then kills and restarts screen and script
I have a matlab scipt on a cluster that pings an API, but after a couple hours (2-4h), the script will have an unexpected error which we believe comes from pinging the API too many times. I want to create a script (not sure if it should be a .sh or .py) that essentially monitors the matlab script and once it reads that...
[]
[]
[ "Try saving it all as a text by doing\ndef text():\n#your code here\nwhile True: text()\n\nwhat that does is repeats your code even when it stops or breaks.\nalso you could try doing an if function: if it breaks, start again\nthanks!\n" ]
[ -1 ]
[ "crash", "matlab", "python", "shell", "try_catch" ]
stackoverflow_0074620521_crash_matlab_python_shell_try_catch.txt
Q: Unable to install Twine I am running on a Raspberry PI OS uname -a Linux gus 5.10.103-v7l+ #1529 SMP Tue Mar 8 12:24:00 GMT 2022 armv7l GNU/Linux I have built my (Python) wheel. I am attempting to publish to testPyPI. I cannot install Twine - because the cryptography module keeps failing. From my Googling, it'...
Unable to install Twine
I am running on a Raspberry PI OS uname -a Linux gus 5.10.103-v7l+ #1529 SMP Tue Mar 8 12:24:00 GMT 2022 armv7l GNU/Linux I have built my (Python) wheel. I am attempting to publish to testPyPI. I cannot install Twine - because the cryptography module keeps failing. From my Googling, it's failing because it's packag...
[ "Well...there was no wheel i could find so i finally got the build working. It took about a day.\n" ]
[ 0 ]
[]
[]
[ "cryptography", "linux", "python", "raspberry_pi", "twine" ]
stackoverflow_0074606027_cryptography_linux_python_raspberry_pi_twine.txt
Q: Python Pandas - Can you use .loc and ignore indexes? I am trying to replace a string found in a column with file1_backup_df.loc[file1_backup_df['CustName'].str.contains('bbb', case=False), 'CustomerName'] = 'Big Boy Booty' Now the above works on a single dataframe (file1_backup_df). But I am combining dataframes ...
Python Pandas - Can you use .loc and ignore indexes?
I am trying to replace a string found in a column with file1_backup_df.loc[file1_backup_df['CustName'].str.contains('bbb', case=False), 'CustomerName'] = 'Big Boy Booty' Now the above works on a single dataframe (file1_backup_df). But I am combining dataframes like this; frames = [add_backup_name(), file1_backup_df] f...
[ "It seems that the column CustomerName holds some NaN values, so you need to set na=False in pandas.Series.str.contains :\nTry this :\nfinal_df.loc[final_df['CustName'].str.contains('bbb', case=False, na=False), 'CustomerName'] = 'Big Boy Booty'\n\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074620527_pandas_python.txt
Q: base.html only showing the context data in the home page I have a ListView for my homepage that displays extra data using the get_context_data method. It works, but only in the url of the HomeView, the homepage, not in other templates after I extend the base.html file. Everything else in base appears, the only thi...
base.html only showing the context data in the home page
I have a ListView for my homepage that displays extra data using the get_context_data method. It works, but only in the url of the HomeView, the homepage, not in other templates after I extend the base.html file. Everything else in base appears, the only thing that doesn't is the context data. HomeView class HomeView(L...
[ "\nDoes this mean that I have to add a get_context_data method to every single view I have?\n\nNo, you don't have to do that. HomeView.get_context_data(...) is specific to the home page.\nIn your example, it looks like you want to show the news in all pages (all pages that use the base.html template). In that case,...
[ 0 ]
[]
[]
[ "django", "django_templates", "django_views", "python" ]
stackoverflow_0074620511_django_django_templates_django_views_python.txt
Q: How to count integers within a tuple? So I have a list of tuples which looks like: [(1, 60), (1, 93), (1, 104), (1, 145), (1, 159), (4, 20), (4, 30), (4, 103), (8, 8), (9, 35), (9, 172), (9, 191), (10, 33), (10, 164), (10, 185)] However, the numbers on the left side of the tuple should all be unique...
How to count integers within a tuple?
So I have a list of tuples which looks like: [(1, 60), (1, 93), (1, 104), (1, 145), (1, 159), (4, 20), (4, 30), (4, 103), (8, 8), (9, 35), (9, 172), (9, 191), (10, 33), (10, 164), (10, 185)] However, the numbers on the left side of the tuple should all be unique. So I would like to have something like th...
[ "Each tuple in your list has two elements. Let's call the first one a \"key\".\nWe're going to create an empty list to fill with the tuples we want.\nLet's also create a set (already_added) containing the keys we have already added. For each tuple, we need to check if the \"key\" exists in already_added, and only a...
[ 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074620494_python.txt
Q: How do I create a "package.json" file? Git clone repository is missing a package.json file Am new to coding, I have cloned this GitHub repository https://github.com/TribeZOAGit/zoa_ussd it happens to be missing the package.json file, so how do I create a package.json file for the already existing project. I can't ...
How do I create a "package.json" file? Git clone repository is missing a package.json file
Am new to coding, I have cloned this GitHub repository https://github.com/TribeZOAGit/zoa_ussd it happens to be missing the package.json file, so how do I create a package.json file for the already existing project. I can't tell which dependencies. npm init command creates the package.json file but with no dependencies...
[ "This is a Python repository, not JavaScript...\nrequirements.txt is pip's version of npm's package.json\nSee what is PIP\nSee here for information on installing the necessary packages using pip.\nOr this Stack answer\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074574819_django_python.txt
Q: How do I redirect to the created page after I submitted the form Django I'm trying to redirect to the created page after I've filled out and submitted a form. I have gotten it to work on the update form but not the create form. How do i do this? Here's what I have so far. Let me know if you need more details and ...
How do I redirect to the created page after I submitted the form Django
I'm trying to redirect to the created page after I've filled out and submitted a form. I have gotten it to work on the update form but not the create form. How do i do this? Here's what I have so far. Let me know if you need more details and code views.py @login_required(login_url='login') def createRoom(request): ...
[ "While you have created a new Room object, you haven't assigned it to room.\nTry\nroom = Room.objects.create(\n\n", "Your create room function should look like this\n@login_required(login_url='login')\ndef createRoom(request):\n form = RoomForm()\n topics = Topic.objects.all()\n if request.method == 'POS...
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074619663_django_python.txt
Q: What is ceil("1d") with reference to timedeltas in Python I have a function I have come across: def sub_kpi1_rule(sub_comp_appr_date, date_report_run, greater_of_date_sub_sub_ll): if pd.isnull(sub_comp_appr_date) and not alive_for_six_days(date_report_run, greater_of_date_sub_sub_ll): return "N...
What is ceil("1d") with reference to timedeltas in Python
I have a function I have come across: def sub_kpi1_rule(sub_comp_appr_date, date_report_run, greater_of_date_sub_sub_ll): if pd.isnull(sub_comp_appr_date) and not alive_for_six_days(date_report_run, greater_of_date_sub_sub_ll): return "NA" elif (sub_comp_appr_date - greater_of_date_sub_sub_l...
[ "You get an error, because you're using .ceil() on datetime.timedelta class in your example. You need the pandas class for this. (pandas._libs.tslibs.timedeltas.Timedelta)\ndelta = pd.Timedelta(4, \"d\")\nNow, what does this .ceil(\"1d\") do?\nIf you have a delta with hours and minutes you want ceil it to days valu...
[ 0 ]
[]
[]
[ "pandas", "python", "timedelta" ]
stackoverflow_0074620497_pandas_python_timedelta.txt
Q: How to do PGP in Python (generate keys, encrypt/decrypt) I'm making a program in Python to be distributed to windows users via an installer. The program needs to be able to download a file every day encrypted with the user's public key and then decrypt it. So I need to find a Python library that will let me genera...
How to do PGP in Python (generate keys, encrypt/decrypt)
I'm making a program in Python to be distributed to windows users via an installer. The program needs to be able to download a file every day encrypted with the user's public key and then decrypt it. So I need to find a Python library that will let me generate public and private PGP keys, and also decrypt files encrypt...
[ "You don't need PyCrypto or PyMe, fine though those packages may be - you will have all kinds of problems building under Windows. Instead, why not avoid the rabbit-holes and do what I did? Use gnupg 1.4.9. You don't need to do a full installation on end-user machines - just gpg.exe and iconv.dll from the distributi...
[ 41, 35, 7, 3, 3, 3, 1, 0 ]
[]
[]
[ "encryption", "gnupg", "pgp", "public_key_encryption", "python" ]
stackoverflow_0001020320_encryption_gnupg_pgp_public_key_encryption_python.txt
Q: Near identical code producing different results. TIME modual I am using TIME for the first time and wanted to make a basic timer. I ran this code completely on its own: import time start = int(time.time()) answered = "No" while int(time.time()) - 2 < start: if input("What's 1 + 1?") == 2: print("Correct") ...
Near identical code producing different results. TIME modual
I am using TIME for the first time and wanted to make a basic timer. I ran this code completely on its own: import time start = int(time.time()) answered = "No" while int(time.time()) - 2 < start: if input("What's 1 + 1?") == 2: print("Correct") else: print("Incorrect") This code's execution gives you 2 ...
[ "As pointed out by @jasonharper you changed your logic in the second example and in the process misused time in your while statement. Keeping your second example's logic in line with your first example's logic (assuming that is your goal) you would want to do something like this:\nstart = int(time.time())\nhits = ...
[ 0 ]
[]
[]
[ "python", "replit", "time" ]
stackoverflow_0074620650_python_replit_time.txt
Q: how to compare if 2 columns in pandas dataframe are equal then update the rest of the dataframe I have 2 pandas dataframes and trying to compare if 2 of their columns are equal then update the rest of the dataframe if not append the new data so concat or something like that . i tried this amongst other stuff if d...
how to compare if 2 columns in pandas dataframe are equal then update the rest of the dataframe
I have 2 pandas dataframes and trying to compare if 2 of their columns are equal then update the rest of the dataframe if not append the new data so concat or something like that . i tried this amongst other stuff if demand_history[['Pyramid Key','FCST_YR_PRD']] == azlog_3[['Pyramid Key','FCST_YR_PRD']]: demand_histor...
[ "demand_hist_sku_date = demand_history['Pyramid Key'] + demand_history['FCST_YR_PRD']\nazlog_3_sku_date = azlog_3['Pyramid Key']+ azlog_3['FCST_YR_PRD']\ndemand_history.loc[demand_hist_sku_date.isin(azlog_3_sku_date), 'DMD_ACTL_QTY' ] = azlog_3['DMD_ACTL_QTY']\n" ]
[ 0 ]
[]
[]
[ "dataframe", "merge", "pandas", "python" ]
stackoverflow_0074620034_dataframe_merge_pandas_python.txt
Q: Project 3D points to 2D points in python I'm trying to project 3D body keypoints to 2D keypoints, My 3D points are: points = np.array([[-7.55801499e-02, -3.69511306e-01, -2.63576955e-01], [ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00], [ 3.08661222e-01, -2.93346141e-02, 3.72593999e-02], [ 5.96781611...
Project 3D points to 2D points in python
I'm trying to project 3D body keypoints to 2D keypoints, My 3D points are: points = np.array([[-7.55801499e-02, -3.69511306e-01, -2.63576955e-01], [ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00], [ 3.08661222e-01, -2.93346141e-02, 3.72593999e-02], [ 5.96781611e-01, -2.82074720e-01, 4.71359938e-01], [ ...
[ "Here's a way to do this from \"scratch\". I have the following import statements:\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom numpy import sin,cos,pi\nfrom scipy.linalg import norm\n\nAfter your 3d plotting code, I added the following:\nazim = ax.azim*pi/180\nelev = ax.elev*pi/180\nelev *= 1.2 ...
[ 3 ]
[]
[]
[ "computer_vision", "numpy", "opencv", "pose_estimation", "python" ]
stackoverflow_0074620278_computer_vision_numpy_opencv_pose_estimation_python.txt
Q: Plotly Figure. How to get the number of rows and cols? I create a Plotly Figure instance this way: fig = go.Figure() fig = make_subplots(rows=3, cols=1, shared_xaxes=True, row_width=[0.3, 0.3, 0.4]) Lets assume that now I do not know how many rows and cols the Figure instance has. How can I obtain these values? F...
Plotly Figure. How to get the number of rows and cols?
I create a Plotly Figure instance this way: fig = go.Figure() fig = make_subplots(rows=3, cols=1, shared_xaxes=True, row_width=[0.3, 0.3, 0.4]) Lets assume that now I do not know how many rows and cols the Figure instance has. How can I obtain these values? For example, I expect something like this: rows = fig.get_row...
[ "I had the same use case come up! I was happy to find you can do this:\nrows, cols = fig._get_subplot_rows_columns()\n\n" ]
[ 0 ]
[]
[]
[ "plotly", "python" ]
stackoverflow_0073829894_plotly_python.txt
Q: Matplotlib figures not generating in GitHub CodeSpaces I just started using Codespaces. In my python file I have this code: import matplotlib.pyplot as plt import pandas as pd print("Hello") titanic_data = pd.read_csv("https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv") titanic_data ...
Matplotlib figures not generating in GitHub CodeSpaces
I just started using Codespaces. In my python file I have this code: import matplotlib.pyplot as plt import pandas as pd print("Hello") titanic_data = pd.read_csv("https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv") titanic_data = titanic_data[titanic_data['Age'].notnull()] titanic_data['...
[ "Based on the experimentation I have done thus far, plotting these diagrams as one would do in a local dev environment is not (yet?) possible.\nFor this specific case, the next best solution was to create a new GitHub Codespace from this repo: https://github.com/education/codespaces-teaching-template-py\n\nOnce the...
[ 1 ]
[]
[]
[ "codespaces", "python" ]
stackoverflow_0074415793_codespaces_python.txt
Q: Generating a UDP message in python with a header and payload in python3 I am new to Networking and trying to implement a network calculator using python3 where the client's responsibility is to send operands and operators and the server will calculate the result and send it back to the client. Communication is thr...
Generating a UDP message in python with a header and payload in python3
I am new to Networking and trying to implement a network calculator using python3 where the client's responsibility is to send operands and operators and the server will calculate the result and send it back to the client. Communication is through UDP messages and I am working on client side. Each message is comprised ...
[ "I will only do a portion of your homework.\nI hope it will help you to find energy to work on missing parts.\nimport struct\nimport socket\n\nCPROTO_ECODE_REQUEST, CPROTO_ECODE_SUCCESS, CPROTO_ECODE_FAIL = (0,1,2)\n\nver = 1 # version of protocol\nmid = 0 # initial value\ncid = 99 # client Id (arbitrary)\n\nsock...
[ 1 ]
[]
[]
[ "networking", "python", "python_3.x", "sockets", "udp" ]
stackoverflow_0074606143_networking_python_python_3.x_sockets_udp.txt
Q: i want to return two values, but only print one in python function, def f(value): value = ~~~ a = ~~~~ return value, a print(f(value)) I want to return value and a so the program out of the function also can memorize value and a, but want to show only a. is there any method to process this? I canno...
i want to return two values, but only print one
in python function, def f(value): value = ~~~ a = ~~~~ return value, a print(f(value)) I want to return value and a so the program out of the function also can memorize value and a, but want to show only a. is there any method to process this? I cannot use global, because the error says that 'value is p...
[ "You should assign value and a to variables outside of the function. Since you are returning a tuple you should assign it like x,y=f(value). Then print(y) to just show a.\n", "As Karl Knechtel mentioned your requirements are inconsistent but the nearest you can get is:\ndef f(value):\n global other_value\n\n ...
[ 1, 0, 0 ]
[ "https://stackoverflow.com/a/45972642/9184997\ndef test():\n r1 = 1\n r2 = 2\n r3 = 3\n return r1, r2, r3\n\nx,y,z = test()\nprint x\nprint y\nprint z\n\n\n> test.py \n1\n2\n3\n\n" ]
[ -1 ]
[ "global", "python", "return" ]
stackoverflow_0064735161_global_python_return.txt
Q: Is there a way to use loop iteration variables in an area outside the loop? I want this code to refer to a list with a loop variable inside instead of using the initialised value: i = 1 list = [i,i+1,i+2] for i in range(3): print(list[0]) I expected the output to be: 0 1 2 The output was: 1 1 1 I have tried i...
Is there a way to use loop iteration variables in an area outside the loop?
I want this code to refer to a list with a loop variable inside instead of using the initialised value: i = 1 list = [i,i+1,i+2] for i in range(3): print(list[0]) I expected the output to be: 0 1 2 The output was: 1 1 1 I have tried i = None instead, but an error was (of course) raised. I have tried using a placeh...
[ "In each iteration of your loop you access the same element at index 0.\nTo get to each individual element of your list by index you have set it to i:\nx = 1\nlst = [x,x+1,x+2]\nfor i in range(3):\n print(lst[i])\n\nI changed list to lst as the former is a reserved keyword and shouldn't be used as variable name.\n...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074620782_python.txt
Q: 1669. Merge In Between Linked Lists - Leetcode - failing test I am working on the LeetCode problem 1669. Merge In Between Linked Lists: You are given two linked lists: list1 and list2 of sizes n and m respectively. Remove list1's nodes from the ath node to the bth node, and put list2 in their place. The blue edge...
1669. Merge In Between Linked Lists - Leetcode - failing test
I am working on the LeetCode problem 1669. Merge In Between Linked Lists: You are given two linked lists: list1 and list2 of sizes n and m respectively. Remove list1's nodes from the ath node to the bth node, and put list2 in their place. The blue edges and nodes in the following figure indicate the result: Build the...
[ "Some of the issues:\n\nslow != a is a condition that is always False because slow is a ListNode object, and a is an int. The same problem occurs with fast != b.\nslowslow.val != a-1 is wrong, as there is nothing in the question that requires to look at the values in the list. a is an index, not a value.\nYour code...
[ 0 ]
[]
[]
[ "linked_list", "python", "python_3.x", "singly_linked_list" ]
stackoverflow_0074620648_linked_list_python_python_3.x_singly_linked_list.txt
Q: How can I calculate the time lag between two similar time series? I'm trying to compute/visualize the time lag between 2 time series (I want to know the time lag between the humidity progression of outside and inside a room). Each data point of my series was taken hourly. Plotting the 2 series together, I can clea...
How can I calculate the time lag between two similar time series?
I'm trying to compute/visualize the time lag between 2 time series (I want to know the time lag between the humidity progression of outside and inside a room). Each data point of my series was taken hourly. Plotting the 2 series together, I can clearly see a shift between them: Sorry for hiding the axis Here are a part...
[ "With the given data, you can use the numpy and matplotlib modules to achieve the desired result.\nso, you can do something like this:\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n\nx = np.array(inside_humidity)\ny = np.array(outside_humidity)\n\nfig = plt.figure()\n\n# fit a curve of your choice\na...
[ 0 ]
[]
[]
[ "cross_correlation", "numpy", "python", "scipy", "time_series" ]
stackoverflow_0074620148_cross_correlation_numpy_python_scipy_time_series.txt
Q: Azure Cognitive Services / Speech-to-text: Transcribe compressed PCMU (mu-law) wav files Using Azure Speech Service, I'm trying to transcribe a bunch a wav files (compressed in the PCMU aka mu-law format). I came up with the following code based on the articles referenced below. The code works fine sometimes with ...
Azure Cognitive Services / Speech-to-text: Transcribe compressed PCMU (mu-law) wav files
Using Azure Speech Service, I'm trying to transcribe a bunch a wav files (compressed in the PCMU aka mu-law format). I came up with the following code based on the articles referenced below. The code works fine sometimes with few files, but I keep getting Segmentation fault errors while looping a bigger list of files (...
[ "I tried to work on a similar dataset, and I didn’t get any segmentation fault. Check with the subscription and deployment pattern with pricing tier. Implemented the same with the custom speech to text translator and it worked in the segmentation also.\n\nCheck with the pricing tier which is creating segmentation f...
[ 0, 0 ]
[]
[]
[ "azure_cognitive_services", "python", "speech_recognition", "speech_to_text", "wav" ]
stackoverflow_0074197867_azure_cognitive_services_python_speech_recognition_speech_to_text_wav.txt
Q: Create new dataframe from the highest values in a column I have the following dataframe df: topic num 0 a01 1 1 a01 1 2 a01 2 3 a02 1 4 a02 3 5 a02 2 6 a02 3 7 a03 2 8 a03 1 And I need to create a new dataframe newdf, where each row corresponds to the to...
Create new dataframe from the highest values in a column
I have the following dataframe df: topic num 0 a01 1 1 a01 1 2 a01 2 3 a02 1 4 a02 3 5 a02 2 6 a02 3 7 a03 2 8 a03 1 And I need to create a new dataframe newdf, where each row corresponds to the topic and the maximum number for each topic, like the following:...
[ "See Get the row(s) which have the max value in groups using groupby\nExample:\nnew_df = df.groupby(['topic'], sort=False)['num'].max()\n\n", "You can use GroupBy.max with numeric_only=True:\nnewdf= df.groupby(\"topic\", as_index=False).max(numeric_only=True)\n\nOutput:\nprint(newdf)\n\n topic num\n0 a01 2...
[ 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074620828_dataframe_pandas_python.txt
Q: subprocess.check_output with grep command fails when grep finds no matches I'm trying to search a text file and retrieve lines containing a specific set of words. This is the code I'm using: tyrs = subprocess.check_output('grep "^A" %s | grep TYR' % pocket_location, shell = True).split('\n') This works fine when ...
subprocess.check_output with grep command fails when grep finds no matches
I'm trying to search a text file and retrieve lines containing a specific set of words. This is the code I'm using: tyrs = subprocess.check_output('grep "^A" %s | grep TYR' % pocket_location, shell = True).split('\n') This works fine when the file contains at least one line that grep identifies. But when grep doesn't ...
[ "\nI just want subprocess.check_output to return an empty string if grep doesn't find anything.\n\nWell, too bad. grep considers no matches to be failure, and the whole point of the check in check_output is to check for failure, so you're explicitly asking to do things this way. Here are the relevant docs:\n\nIf th...
[ 14, 6, 0 ]
[]
[]
[ "grep", "python", "subprocess" ]
stackoverflow_0020983498_grep_python_subprocess.txt
Q: smallest number of sublists with maximum length m and tolerance k I need to create a program that takes a sorted list of integers, x, and outputs the smallest number sublists with the following properties: length <= m smallest item in sublist + 2k >= largest item in sublist it is important to note I don't actual...
smallest number of sublists with maximum length m and tolerance k
I need to create a program that takes a sorted list of integers, x, and outputs the smallest number sublists with the following properties: length <= m smallest item in sublist + 2k >= largest item in sublist it is important to note I don't actually need to find the sublists themselves just the how many of them I've ...
[ "Use combinations to find the ordered combinations of a list.\nfrom itertools import combinations\n\ndef split(lst, t, m):\n n = len(lst)\n counter = 0\n for i in range(1, m+1):\n for c in combinations(x, r=i):\n if min(c) + t >= max(c):\n counter += 1\n return counter\n...
[ 0 ]
[]
[]
[ "list", "python", "recursion" ]
stackoverflow_0074618948_list_python_recursion.txt
Q: Are chunks returned by 'np.array_split()' ordered by descending sizes? In numpy.array_split using an integer, when the number of parts isn't a divisor of the size on the axis considered, some parts may be smaller or larger, e.g. import numpy as np [chunk.shape[0] for chunk in np.array_split(np.arange(12), 5)] ret...
Are chunks returned by 'np.array_split()' ordered by descending sizes?
In numpy.array_split using an integer, when the number of parts isn't a divisor of the size on the axis considered, some parts may be smaller or larger, e.g. import numpy as np [chunk.shape[0] for chunk in np.array_split(np.arange(12), 5)] returns chunk sizes: [3, 3, 2, 2, 2] While the documentation doesn't mention it...
[ "numpy.array_split docs says\n\nFor an array of length l that should be split into n sections, it\nreturns l % n sub-arrays of size l//n + 1 and the rest of size l//n.\n\nAs l and n are fixed in each run, we can conclude that for every element in returned array next one will be no longer than current.\nEdit: when i...
[ 1, 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0065793051_numpy_python.txt
Q: Trying to check if tuple item is nan I have the below for loop and am try to check first if the tuple(row) item in position 10 is Nan i=0 for row in df.iterrows(): if row[1][10] != None: names = row[1][10].split(',') for name in names: df2.loc[i,:] = row[1][:] i=i+1 ...
Trying to check if tuple item is nan
I have the below for loop and am try to check first if the tuple(row) item in position 10 is Nan i=0 for row in df.iterrows(): if row[1][10] != None: names = row[1][10].split(',') for name in names: df2.loc[i,:] = row[1][:] i=i+1 else: i=i+1 I thought I could use...
[ "Can use pd.isnull(row[1][10]) instead of if row[1][10] != None.\nExample:\ni=0\nfor row in df.iterrows():\n if pd.isnull(row[1][10]):\n df2.loc[i,:] = row[1][:]\n i=i+1\n else:\n names = row[1][10].split(',')\n for name in names:\n df2.loc[i,:] = row[1][:]\n ...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074620897_pandas_python.txt
Q: myRange function giving output of None. Why is this? I am to create a function called myRange that behaves like range. This is for class and the instructions tell me to use Python's help for range but I am not understanding it at all. I am a complete greenhorn with Python. Please do not provide modules or methods....
myRange function giving output of None. Why is this?
I am to create a function called myRange that behaves like range. This is for class and the instructions tell me to use Python's help for range but I am not understanding it at all. I am a complete greenhorn with Python. Please do not provide modules or methods. def myRange(stop,start=None,step=None): outputList = ...
[ "# define a function called 'myRange' which takes 3 arguments,\n# stop, start and step, where start and step default to None\ndef myRange(stop,start=None,step=None):\n\n # set the value of outputList to an empty list\n outputList = []\n\n # if stop is 0, do this block of code below\n if stop == 0:\n ...
[ 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074620952_list_python.txt
Q: Polars - How to create dynamic rolling window for calculations Consider the following dataframe of sensor readings laid out along a straight line: Location Start (KM) Location End (KM) Readings 1 1.1 7 1.1 1.23 null 1.23 1.3 8 1.3 1.34 null 1.34 1.4 null 1.4 1.5 5 1.5 1.65 6 I am trying to create a rollin...
Polars - How to create dynamic rolling window for calculations
Consider the following dataframe of sensor readings laid out along a straight line: Location Start (KM) Location End (KM) Readings 1 1.1 7 1.1 1.23 null 1.23 1.3 8 1.3 1.34 null 1.34 1.4 null 1.4 1.5 5 1.5 1.65 6 I am trying to create a rolling 150m lookahead window to calculate the percentage o...
[ "I may not understand what you need, but let's see if we can get the ball rolling.\nLet's start by using groupby_rolling and see if this gets us close to what is needed.\nFirst, let's convert the floats (kilometers) to integers (meters). That allows us to specify our period as an integer: 150i. We'll then calcula...
[ 2 ]
[]
[]
[ "python", "python_polars" ]
stackoverflow_0074615958_python_python_polars.txt
Q: Rearrange/mix column pandas i have table like this: ID Type I/P Value ID1 Primary I 8 ID2 Primary I 3 ID3 Secondary P 6 ID4 Secondary I 2 ID5 Primary P 3 ID6 Primary I 4 I re order it this way: ID Type I/P Value ID1 Primary I 8 ID6 Primary I 4 ID2 Primary I 3 ID5 Primary P 3 ID3 Secondary P 6 ID4 Se...
Rearrange/mix column pandas
i have table like this: ID Type I/P Value ID1 Primary I 8 ID2 Primary I 3 ID3 Secondary P 6 ID4 Secondary I 2 ID5 Primary P 3 ID6 Primary I 4 I re order it this way: ID Type I/P Value ID1 Primary I 8 ID6 Primary I 4 ID2 Primary I 3 ID5 Primary P 3 ID3 Secondary P 6 ID4 Secondary ...
[ "here is one way to do it\nNote: your starting DF has two 'P' in the DF, the expected output has three 'P'. seems to be a typo\n\n# create a temp seq based on type and i/p\n# count for 'I' and 'P' both starts from 0\n# sort the result with type and seq\n\n\nout=df.assign(seq=df.groupby(['Type','I/P']).cumcount()).s...
[ 2 ]
[]
[]
[ "dataframe", "multiple_columns", "pandas", "python", "sorting" ]
stackoverflow_0074620994_dataframe_multiple_columns_pandas_python_sorting.txt
Q: I am so so tired of backtracking issues with pip. How can I figure out exactly which package is causing the problem? I've got a repo with a bunch of different requirements.txt for a few different cloud functions. I separate the install/test for each with a loop in my bitbucket-pipelines.yml: for d in `find . -type...
I am so so tired of backtracking issues with pip. How can I figure out exactly which package is causing the problem?
I've got a repo with a bunch of different requirements.txt for a few different cloud functions. I separate the install/test for each with a loop in my bitbucket-pipelines.yml: for d in `find . -type d -maxdepth 1 -mindepth 1`; do if [ -f "$d/requirements.txt" ]; then echo "====="$d"=====" python3 -m pip insta...
[ "As it seems your question has been answered in another Question\nA bit of an explanation:\nFirst we assume we work with python-version-2.5 (because I chose so - you have to replace 2.5 by your python-version)\n\nFirst there was/is the command to avoid multiple requests:\nex.g. $ python-2.5 -m pip install myfoopack...
[ 0 ]
[]
[]
[ "pip", "python" ]
stackoverflow_0074620601_pip_python.txt
Q: Django / Python: Sorting QuerySet by field on first instance of foreignkey relation I have the following 2 models, a Lesson model, that can have multiple start / end dates - each with their own Date model. class Lesson(models.Model): name = models.Charfield() (...) class Date(models.Model): meeting = ...
Django / Python: Sorting QuerySet by field on first instance of foreignkey relation
I have the following 2 models, a Lesson model, that can have multiple start / end dates - each with their own Date model. class Lesson(models.Model): name = models.Charfield() (...) class Date(models.Model): meeting = models.ForeignKey( Lesson, verbose_name="dates", on_delete=model...
[ "I'm assuming you need a min?\nSomething like (untested):\nMeeting.objects.annotate(first_date=Min('dates__start_date')).order_by('first_date')\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_queryset", "python" ]
stackoverflow_0074621051_django_django_queryset_python.txt
Q: Adding user input to an array I've just started learning python. I'm doing this for a school project. I cannot use a list for storing the passengers ages, I need to do a 2d array and I'm just lost. How do I add the values of "age" into an array? I've gott it working with a list, but that won't be enough. I've trie...
Adding user input to an array
I've just started learning python. I'm doing this for a school project. I cannot use a list for storing the passengers ages, I need to do a 2d array and I'm just lost. How do I add the values of "age" into an array? I've gott it working with a list, but that won't be enough. I've tried messing around with numpy but I m...
[ "So when you work with numpy arrays they have indexes, like lists. But since they're multi-dimensional you have to call more than one axis.\nIf you replace line passenger_ages.np.append(age) with passenger_ages[pass_no][x] = age then you can get this working. In this case pass_no will increment each time you add a ...
[ 0 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0074620780_arrays_numpy_python.txt
Q: Speedup extracting data form larger xml files using python Hello I am not strong python user , but need to extract the xml file values. I am using for loop to get attribute values from 'xml.dom.minidom.document' Both the xyz or temp uses for loop , since the file has half million values it takes time. I tried usin...
Speedup extracting data form larger xml files using python
Hello I am not strong python user , but need to extract the xml file values. I am using for loop to get attribute values from 'xml.dom.minidom.document' Both the xyz or temp uses for loop , since the file has half million values it takes time. I tried using lxml, but it had error: module 'lxml' has no attribute 'parse'...
[ "I recommend iterparse() for large xml files:\nimport timeit\nimport os, psutil\nimport datetime\n\nimport pandas as pd\nimport xml.etree.ElementTree as ET\n\nclass parse_xml:\n def __init__(self, path):\n self.xml = os.path.split(path)[1]\n print(self.xml)\n \n columns = [\"Pos_x\", ...
[ 0 ]
[]
[]
[ "anaconda", "lxml", "python", "xml" ]
stackoverflow_0074321833_anaconda_lxml_python_xml.txt
Q: Exasol_Error: I keep getting Exasol connection error timed out I am trying to connect to my Exasol SaaS database, I tried via these tools(TALEND, DBVISUALIZER, POWERBI) and via python but I cannot connect and I keep getting the same error. I saw another post on Exasol community https://community.exasol.com/t5/disc...
Exasol_Error: I keep getting Exasol connection error timed out
I am trying to connect to my Exasol SaaS database, I tried via these tools(TALEND, DBVISUALIZER, POWERBI) and via python but I cannot connect and I keep getting the same error. I saw another post on Exasol community https://community.exasol.com/t5/discussion-forum/exaconnectionfailederror/m-p/8049#M1855 of this type of...
[ "The error means that the client is not able to reach the host for some reason. Try the following:\n\nMake sure the database is still online (they auto-shutdown after 2 hours if there is no activity by default)\nCheck that the IP Address of the host you are connecting with is added to the allow list in the SaaS UI....
[ 0, 0 ]
[]
[]
[ "database_connection", "dbvisualizer", "exasol", "python", "talend" ]
stackoverflow_0074430573_database_connection_dbvisualizer_exasol_python_talend.txt
Q: Tensorflow clone_model with subclass model Is there a way to clone a subclass-based model in Tensorflow? For example, if I have the following model: class MySequentialModel(tf.keras.Model): def __init__(self, name=None, **kwargs): super().__init__(**kwargs) self.dense_1 = FlexibleDense(out_features=3) ...
Tensorflow clone_model with subclass model
Is there a way to clone a subclass-based model in Tensorflow? For example, if I have the following model: class MySequentialModel(tf.keras.Model): def __init__(self, name=None, **kwargs): super().__init__(**kwargs) self.dense_1 = FlexibleDense(out_features=3) self.dense_2 = FlexibleDense(out_features=2) ...
[ "This is not possible, but the issue is tracked on the Keras repository here.\n" ]
[ 0 ]
[]
[]
[ "keras", "python", "tensorflow" ]
stackoverflow_0066068938_keras_python_tensorflow.txt
Q: How to Trigger an On-Demand Scheduled Query Using a Cloud Function? What I basically want to happen is my on demand scheduled query will run when a new file lands in my google cloud storage bucket. This query will load the CSV file into a temporary table, perform some transformation/cleaning and then append to a t...
How to Trigger an On-Demand Scheduled Query Using a Cloud Function?
What I basically want to happen is my on demand scheduled query will run when a new file lands in my google cloud storage bucket. This query will load the CSV file into a temporary table, perform some transformation/cleaning and then append to a table. Just to try and get the first part running, my on demand scheduled ...
[ "It seems to me that it's not really a scheduled query you want at all. You don't want one to run at regular intervals, you want to run a query in response to a certain event.\nNow, you've rigged up a cloud function to execute some code whenever a new file is added to a bucket. What this cloud function needs is the...
[ 1 ]
[]
[]
[ "google_bigquery", "google_cloud_functions", "google_cloud_platform", "google_cloud_storage", "python" ]
stackoverflow_0074620163_google_bigquery_google_cloud_functions_google_cloud_platform_google_cloud_storage_python.txt
Q: Pandas: how to group rows with consecutively repeating values in columns? I have a data frame df ` df=pd.DataFrame([['1001',34.3],['1009',34.3],['1003',776],['1015',18.95],['1023',18.95],['1007',18.95],['1009',18.95],['1037',321.2],['1001',344.2],['1016',3.2],['1017',3.2],['1027',344.2]],columns=['id','amount']) ...
Pandas: how to group rows with consecutively repeating values in columns?
I have a data frame df ` df=pd.DataFrame([['1001',34.3],['1009',34.3],['1003',776],['1015',18.95],['1023',18.95],['1007',18.95],['1009',18.95],['1037',321.2],['1001',344.2],['1016',3.2],['1017',3.2],['1027',344.2]],columns=['id','amount']) id amount 0 1001 34.30 1 1009 34.30 2 1003 776...
[ "here is one way to do it\n\n# take a difference b/w the amount of two consecutive rows and then\n# choose rows where the difference is not zero\n\nout= df[df['amount'].diff().ne(0) ]\n\nout\n\n\nid amount\n0 1001 34.30\n2 1003 776.00\n3 1015 18.95\n7 1037 321.20\n8 1001 344.20\n9 1016 ...
[ 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074621127_pandas_python.txt
Q: Contain in a list the values that appear in an array in a given percentage I have an array called "data" which contains the following information. [['amazon', 'phone', 'serious', 'mind', 'blown', 'serious', 'enjoy', 'use', 'applic', 'full', 'blown', 'websit', 'allow', 'quick', 'track', ...
Contain in a list the values that appear in an array in a given percentage
I have an array called "data" which contains the following information. [['amazon', 'phone', 'serious', 'mind', 'blown', 'serious', 'enjoy', 'use', 'applic', 'full', 'blown', 'websit', 'allow', 'quick', 'track', 'packag', 'descript', 'say'], ['would', 'say', 'app', 'real', 'th...
[ "let's see, we can remove the nesting using itertool.chain.from_iterable, but we also need the total length, which we can compute by making another generator to avoid looping twice, and we need to count the repetitions, which is done by a counter.\nfrom collections import Counter\nfrom itertools import chain\n\ntot...
[ 0, 0 ]
[]
[]
[ "arrays", "python" ]
stackoverflow_0074620854_arrays_python.txt
Q: How can I dump YAML 1.1 booleans (y, n, T, F, etc) as quoted strings with ruamel.yaml Already read https://stackoverflow.com/a/61252180/1676006 and it doesn't seem to have solved my problem. Using ruamel.yaml: yaml = YAML(typ="safe") yaml.version = (1, 1) yaml.default_flow_style = None yaml.dump(st...
How can I dump YAML 1.1 booleans (y, n, T, F, etc) as quoted strings with ruamel.yaml
Already read https://stackoverflow.com/a/61252180/1676006 and it doesn't seem to have solved my problem. Using ruamel.yaml: yaml = YAML(typ="safe") yaml.version = (1, 1) yaml.default_flow_style = None yaml.dump(stuff, sys.stdout) With a python dict stuff containing: { "key": "Y" } outputs %YAML 1....
[ "If your Python dict really consists of a single key value pair, mapping of a string to a string, as you indicate, ruamel.yaml will not dump the output you display\nwith or without typ='safe')\nimport sys\nimport ruamel.yaml\n\ndata = {\n \"key\": \"Y\"\n}\nyaml = ruamel.yaml.YAML(typ='safe')\nyaml.version = (1,...
[ 2 ]
[]
[]
[ "python", "ruamel.yaml" ]
stackoverflow_0074620398_python_ruamel.yaml.txt
Q: S3 Python - Multipart upload to s3 with presigned part urls I'm unsuccessfully trying to do a multipart upload with pre-signed part URLs. This is the procedure I follow (1-3 is on the server-side, 4 is on the client-side): Instantiate boto client. import boto3 from botocore.client import Config s3 = boto3.clien...
S3 Python - Multipart upload to s3 with presigned part urls
I'm unsuccessfully trying to do a multipart upload with pre-signed part URLs. This is the procedure I follow (1-3 is on the server-side, 4 is on the client-side): Instantiate boto client. import boto3 from botocore.client import Config s3 = boto3.client( "s3", region_name=aws.default_region, aws_access_k...
[ "Did you try pre-signed POST instead? Here is the AWS Python reference for it: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/s3-presigned-post.html\nThis will potentially workaround proxy limitations from client perspective, if any:\n\nAs a last resort, you can always try good old REST API, although I ...
[ 1, 1, 1, 0 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "boto3", "python" ]
stackoverflow_0057929414_amazon_s3_amazon_web_services_boto3_python.txt
Q: How do I make a function triggered by pressing right click? I'm working on a game involving turtle for a school project and I want to end it when the player right clicks on anything but I've been researching for ages and I can't find how to key bind a right click and every module i import but turtle won't work. I ...
How do I make a function triggered by pressing right click?
I'm working on a game involving turtle for a school project and I want to end it when the player right clicks on anything but I've been researching for ages and I can't find how to key bind a right click and every module i import but turtle won't work. I tried importing pyautogui, pydirectimput, tkinter and many more t...
[ "I don't know turtle much, but I think this should work:\ndef bar():\n # do stuff here\n\n# Test this with either a 2 or a 3, idk which one it is\nturtle.onscreenclick(bar, 2, True) \n\nIt will bind the right click event to this bar function.\nTell me if it does not work!\nEdit: I had used the wrong method sorry...
[ 0 ]
[]
[]
[ "keyboard_events", "python", "python_3.x", "right_click" ]
stackoverflow_0074620773_keyboard_events_python_python_3.x_right_click.txt
Q: python AttributeError: '_tkinter.tkapp' object has no attribute 'balance_label' I can't seem to figure out why I can't update the label text. But after a day... I figured I'd ask for help self.balance_label['text'] = "Text updated" gives me: AttributeError: '_tkinter.tkapp' object has no attribute 'balance_label' ...
python AttributeError: '_tkinter.tkapp' object has no attribute 'balance_label'
I can't seem to figure out why I can't update the label text. But after a day... I figured I'd ask for help self.balance_label['text'] = "Text updated" gives me: AttributeError: '_tkinter.tkapp' object has no attribute 'balance_label' I'm using 2 separate script. file 1 import sys import tkinter as tk import tkinter.tt...
[ "Finally found the solution...\ndef get_balance(*args):\n\n print('trade_helper_support.get_balance')\n _w1.balance_label['text'] = \"Text updated\"\n\n" ]
[ 0 ]
[]
[]
[ "attributes", "python" ]
stackoverflow_0074620906_attributes_python.txt
Q: Wondering the best way to implement a score function to my anagrams game using OOP in Python I am trying to implement an anagram game in python. It currently gives the player 7 tiles from a "Scrabble Bag". I want to add some type of scoring function but I am struggling on Should I implement a score function in on...
Wondering the best way to implement a score function to my anagrams game using OOP in Python
I am trying to implement an anagram game in python. It currently gives the player 7 tiles from a "Scrabble Bag". I want to add some type of scoring function but I am struggling on Should I implement a score function in one of the classes? or in a def score() function under main... and If i make a function under main ...
[ "I assume that the score you want to compute is the current value of the tiles in a particular Player's hand. You mention the need to access an instance of Bag. I don't see where this is necessary or desirable. Once you have built up a Player with a hand, you only need to work with that instance of Player.\nThe ...
[ 0 ]
[]
[]
[ "oop", "python", "python_class" ]
stackoverflow_0074621098_oop_python_python_class.txt
Q: How to subtract values in a list I am writing a function that works as follows it receives list of numbers e.g [0.5,-0.5,1] then it returns a list with this in each index[(-0.5-0.5) + (1-0.5)]. In other words, it adds the difference between the current value and the other values. So the output should be [-0.5,2.5,...
How to subtract values in a list
I am writing a function that works as follows it receives list of numbers e.g [0.5,-0.5,1] then it returns a list with this in each index[(-0.5-0.5) + (1-0.5)]. In other words, it adds the difference between the current value and the other values. So the output should be [-0.5,2.5,-2] def Calculate(initial_values,b): ...
[ "This seems to do the trick:\ndef Calculate(arr):\n res = []\n for i, val in enumerate(arr):\n total = -val * (len(arr) - 1) + sum(arr[0:i]) + sum(arr[i+1:])\n res.append(total)\n return res\n\nWe iterate through each element and calculate the sum of differences like you described. Since the ...
[ 1, 0, 0 ]
[]
[]
[ "arrays", "list", "numpy", "python" ]
stackoverflow_0074620852_arrays_list_numpy_python.txt
Q: Py_Initialize undefined error in Xcode while integrating Python in iOS project I am trying to integrate Python in iOS app. Here is the contentview file import SwiftUI import Python import PythonKit struct ContentView: View { @State private var showingSheet = false var body: some View { ...
Py_Initialize undefined error in Xcode while integrating Python in iOS project
I am trying to integrate Python in iOS app. Here is the contentview file import SwiftUI import Python import PythonKit struct ContentView: View { @State private var showingSheet = false var body: some View { var name = "" Button("Run Python") { showingSheet...
[ "I believe your problem is with this part \"Python/Resources\".\nYou need the python-stdlib to appear in Build Phase's Copy Bundle Resources. And then do this:\nimport Python\n\nguard let stdLibPath = Bundle.main.path(forResource: \"python-stdlib\", ofType: nil) else { return }\nguard let libDynloadPath = Bundle.ma...
[ 0 ]
[]
[]
[ "ios", "python", "swift", "xcode" ]
stackoverflow_0074427573_ios_python_swift_xcode.txt
Q: How to create a Data Frame in Python from a for loop? I am trying to merge the results of X with the results of the predicted Y with the help of for loop. How can the result be saved to a DataFrame. predictions = [] for i in range(100): predictions.append([X_unseen[i], y_pred_unseen[i]]) print(predictions) df...
How to create a Data Frame in Python from a for loop?
I am trying to merge the results of X with the results of the predicted Y with the help of for loop. How can the result be saved to a DataFrame. predictions = [] for i in range(100): predictions.append([X_unseen[i], y_pred_unseen[i]]) print(predictions) df = pd.Series(predictions) This is the output I get. I am n...
[ "You created a pd.Series which is basically a single column. If you want multiple columns, you need a whole dataframe.\nSo instead, do pd.DataFrame(predictions)\n" ]
[ 0 ]
[]
[]
[ "dataframe", "prediction", "python" ]
stackoverflow_0074620700_dataframe_prediction_python.txt
Q: how to rename random number from file name to sequent number? Hi i'm trying to rename my files in a directory from (2015_001.txt,2015_005.txt,2015_009.txt..etc) to (2015_001.txt,2015_002.txt,2015_003.tx..etc). I'm new to python, can anyone help me? I tried using loop but all file will not in series anymore this is...
how to rename random number from file name to sequent number?
Hi i'm trying to rename my files in a directory from (2015_001.txt,2015_005.txt,2015_009.txt..etc) to (2015_001.txt,2015_002.txt,2015_003.tx..etc). I'm new to python, can anyone help me? I tried using loop but all file will not in series anymore this is the code I tried so far import re import os _src = "C:/ZTD/pwv2015...
[ "You probably have an easier time with the glob module for finding files and f-strings for renaming. Also, for the sake of teaching modern python, I'm using the pathlib and its glob method. Try this:\nimport os\nimport pathlib\n\nsrc = pathlib.Path(\"C:/ZTD/pwv2015\")\npattern = \"2015_[0-9][0-9][0-9].txt\"\ninpath...
[ 3 ]
[]
[]
[ "directory", "file_rename", "python" ]
stackoverflow_0074621197_directory_file_rename_python.txt
Q: Image not showing in Canvas tkinter I have a code where I'm using the create_image() method of Canvas, I want to use tags to bind the respective methods but when I run the code the image doesn't show up on the canvas. I made a simple code example to show what I mean: from tkinter import * class CanvasM(Canvas): ...
Image not showing in Canvas tkinter
I have a code where I'm using the create_image() method of Canvas, I want to use tags to bind the respective methods but when I run the code the image doesn't show up on the canvas. I made a simple code example to show what I mean: from tkinter import * class CanvasM(Canvas): width = 600 height = 400 def...
[ "There are two issues in create_an_image():\n\nimg is a local variable, so it will be garbage collected after exiting the function. So use an instance variable self.img instead.\nyou need to use file option of PhotoImage() to specify the filename of the image\n\n def create_an_image(self, file, x, y):\n #...
[ 1 ]
[]
[]
[ "python", "tags", "tkinter", "tkinter_canvas" ]
stackoverflow_0074621243_python_tags_tkinter_tkinter_canvas.txt
Q: Correlation Matrix with Lists or Can not create DataFrame with Arrays It's about a data project. I have a problem with types of variables and I guess I am missing something that I can not see. I am beginner at this topic any help would be appreciated. I have 8 normalised arrays and I want to put them into a datafr...
Correlation Matrix with Lists or Can not create DataFrame with Arrays
It's about a data project. I have a problem with types of variables and I guess I am missing something that I can not see. I am beginner at this topic any help would be appreciated. I have 8 normalised arrays and I want to put them into a dataframe so I can create a correlation matrix. But I have this error. > ValueE...
[ "After I applied .flatten() all my values converted to 0\nHere it is the output\n" ]
[ 0 ]
[]
[]
[ "arrays", "data_science", "dataframe", "finance", "python" ]
stackoverflow_0074621189_arrays_data_science_dataframe_finance_python.txt
Q: Speed of Turtle not changing with simple Frogger style code import time import turtle from turtle import Screen, Turtle from player import Player from car_manager import CarManager from scoreboard import Scoreboard screen = Screen() screen.setup(width=600, height=600) screen.tracer(0) player = Player() car_manag...
Speed of Turtle not changing with simple Frogger style code
import time import turtle from turtle import Screen, Turtle from player import Player from car_manager import CarManager from scoreboard import Scoreboard screen = Screen() screen.setup(width=600, height=600) screen.tracer(0) player = Player() car_manager = CarManager() scoreboard = Scoreboard() screen.listen() scre...
[ "\nI set the go_up movement speed to 0 (\"fastest\"), however if I input\nany value here, or type out the \"fastest\", \"slowest\"... whichever\nvalue... the turtle still moves at the same rate no matter any value I\ninput into the go_up function\n\nOnce you invoke tracer(0), the turtles' speed() method is a no-op....
[ 2 ]
[]
[]
[ "python", "python_turtle", "turtle_graphics" ]
stackoverflow_0074619350_python_python_turtle_turtle_graphics.txt
Q: Pandas Similar Function to COUNTIFS Sample Data Please see Sample Data image. I'm trying to replicate the COUNTIFS functionality within Python / Pandas but I'm having troubles finding the correct solution. =COUNTIFS(B:B,"BD*",A:A,A2,C:C,">"&C2) B is the Type column, A is the Reference column, and C is the Doc Con...
Pandas Similar Function to COUNTIFS
Sample Data Please see Sample Data image. I'm trying to replicate the COUNTIFS functionality within Python / Pandas but I'm having troubles finding the correct solution. =COUNTIFS(B:B,"BD*",A:A,A2,C:C,">"&C2) B is the Type column, A is the Reference column, and C is the Doc Condition column. So the count is only grea...
[ "You should include your input data as text. Screenshots are really hard to work with.\nYou can use numpy broadcasting. However, this will have an n^2 computational complexity since you are comparing every row against every other row:\nreference, type_, doc_condition = df.to_numpy().T\nmatch = (\n (type_[:, None...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074620537_pandas_python.txt
Q: 8.3.3: Hourly temperature reporting Write a loop to print all elements in hourly_temperature. Separate elements with a -> surrounded by spaces. Sample output for the given program with input: 90 92 94 95' 90 -> 92 -> 94 -> 95 Note: 95 is followed by a space, then a newline. This is the assignment Here is my code ...
8.3.3: Hourly temperature reporting
Write a loop to print all elements in hourly_temperature. Separate elements with a -> surrounded by spaces. Sample output for the given program with input: 90 92 94 95' 90 -> 92 -> 94 -> 95 Note: 95 is followed by a space, then a newline. This is the assignment Here is my code so far: user_input = input() hourly_tempe...
[ "you could use the built-in join() method for strings:\nlst_str = \" -> \".join(user_input.split()) + \" \\n\"\n\n", "This is the code I used. The output is without the '->' and any extra space at the end:\nuser_input = input()\nhourly_temperature = user_input.split()\n\n\nfor temp in hourly_temperature:\n lst_s...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074046719_python.txt
Q: Plot elements in a column of a dataframe on the same graph sharing the same x-axis in datetime format I have a dataframe: Element Date Q 0 A 24/10/2021 17:16 400 1 B 24/10/2021 18:59 210 2 A 26/10/2021 18:42 325 3 A 26/10/2021 19:44 589 4 B 2...
Plot elements in a column of a dataframe on the same graph sharing the same x-axis in datetime format
I have a dataframe: Element Date Q 0 A 24/10/2021 17:16 400 1 B 24/10/2021 18:59 210 2 A 26/10/2021 18:42 325 3 A 26/10/2021 19:44 589 4 B 29/10/2021 14:23 251 5 A 01/11/2021 9:12 578 6 B 02/11/2021 21:30 321 7 A ...
[ "Your first attrempt would have wored had you converted the Date column to Timestamp. A scatter plot requires that both values on x- and y-axis to be numerical. When you supply strings on the x-axis, they are treated as positions [0, 1, 2, 3,...] with tick marks equal to the supplied values.\nfor df in [dfA, dfB]:\...
[ 0 ]
[]
[]
[ "datetime", "pandas", "plot", "python", "x_axis" ]
stackoverflow_0074621393_datetime_pandas_plot_python_x_axis.txt
Q: Can't add a record to a database without "sqlite3.OperationalError: near "(": syntax error" I made a 'dummy' version for my program consisting of just the first four fields but once I added the rest, this error keeps appearing. Anyone else I've seen with this issue was due to something else that doesn't apply to m...
Can't add a record to a database without "sqlite3.OperationalError: near "(": syntax error"
I made a 'dummy' version for my program consisting of just the first four fields but once I added the rest, this error keeps appearing. Anyone else I've seen with this issue was due to something else that doesn't apply to mine. I feel like it's something small that I've missed, if anyone could help me figure this out i...
[ "you should need to use comma(,) after employeeName TEXT.\nCorrect code-\nconnection = sqlite3.connect(\"TempDatabase.db\")\n cursor = connection.cursor()\n\n sqlCommand = \"\n CREATE TABLE IF NOT EXISTS OrderTb1N1\n (\n OrderID INTEGER NOT NULL,\n dateOrdered D...
[ 0 ]
[]
[]
[ "database", "python", "sqlite", "syntax", "syntax_error" ]
stackoverflow_0074621399_database_python_sqlite_syntax_syntax_error.txt
Q: Python : Pygame error : AttributeError: module 'pygame.image' has no attribute 'rotate' when trying to rotate image of an in game character import pygame import os WIDTH, HEIGHT = 900, 500 WIN = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("First Game!") WHITE = (255, 255, 255) FPS = 60 SP...
Python : Pygame error : AttributeError: module 'pygame.image' has no attribute 'rotate' when trying to rotate image of an in game character
import pygame import os WIDTH, HEIGHT = 900, 500 WIN = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("First Game!") WHITE = (255, 255, 255) FPS = 60 SPACESHIP_WIDTH, SPACESHIP_HEIGHT = 55, 40 YELLOW_SPACESHIP_IMAGE = pygame.image.load( os.path.join('Assets', 'spaceship_yellow.png')) YELLOW...
[ "pygame.image.rotate does not actualy exists.\nTo rotate an image, you have to do the same as to scale :\npygame.transform.rotate(surface, angle)\n\nIn your case, that would be:\nYELLOW_SPACESHIP = pygame.transform.rotate(pygame.transform.scale(YELLOW_SPACESHIP_IMAGE, (SPACESHIP_WIDTH, SPACESHIP_HEIGHT)), 90) \n\n...
[ 2, 2 ]
[]
[]
[ "attributeerror", "pygame", "python" ]
stackoverflow_0074621267_attributeerror_pygame_python.txt
Q: Python Loop question: calling models based on variables I have a basic python loop question. Problem Statement: I have a master list of variables in list 'X', a variable 't' (which is present in master list) and another variable 'y' (which is also present in master list). I want to run a ML model inside the loop a...
Python Loop question: calling models based on variables
I have a basic python loop question. Problem Statement: I have a master list of variables in list 'X', a variable 't' (which is present in master list) and another variable 'y' (which is also present in master list). I want to run a ML model inside the loop and each time I want to remove the variable 't' and 'y' from m...
[ "have you tried to use a list? something like... seen_numbers = set()\nI know this isn't exactly what you're asking but I use lists to find duplicates or find things I want to exclude. maybe this will help...\nthis = line[92:102] + line[114:123]\nif this not in seen_numbers:\n seen_numbers.add(this)\n\nand you s...
[ 0 ]
[]
[]
[ "for_loop", "loops", "pandas", "python" ]
stackoverflow_0074621403_for_loop_loops_pandas_python.txt
Q: Partitions per month from the bigquery CLI in python I'm trying to use partitions per month from the bigquery CLI in python, but the only thing I get is the error in the image table = bigquery.Table(table_ref, schema=schema) table.time_partitioning = bigquery.TimePartitioning( type_=bigquery.T...
Partitions per month from the bigquery CLI in python
I'm trying to use partitions per month from the bigquery CLI in python, but the only thing I get is the error in the image table = bigquery.Table(table_ref, schema=schema) table.time_partitioning = bigquery.TimePartitioning( type_=bigquery.TimePartitioningType.MONTH, field='fiel...
[ "I tested it and it works well with MONTH partition :\ndef create_table_time_partitioning_month(self):\n from google.cloud import bigquery\n client = bigquery.Client()\n project = client.project\n dataset_ref = bigquery.DatasetReference(project, 'my_dataset')\n\n table_ref = dataset_ref.table(\"my_pa...
[ 0 ]
[]
[]
[ "gcloud", "google_bigquery", "python" ]
stackoverflow_0074619174_gcloud_google_bigquery_python.txt
Q: Python3.10.6 can't pip install things: error: subprocess-exited-with-error Using Python 3.10.6 on new Ubuntu VPS. Can't pip install dotenv, bs4 etc. pip 22.3.1 version used. Why is this error showing, how do I fix this? I looked at other questions, but couldn't solve my problem. I tried having a lower pip version,...
Python3.10.6 can't pip install things: error: subprocess-exited-with-error
Using Python 3.10.6 on new Ubuntu VPS. Can't pip install dotenv, bs4 etc. pip 22.3.1 version used. Why is this error showing, how do I fix this? I looked at other questions, but couldn't solve my problem. I tried having a lower pip version, didn't work. I even reinstalled python3.10. Thanks. (below error log - some emi...
[ "First update setuptools, as per https://stackoverflow.com/a/58754136/5666087\npip install -U setuptools\n\nThen use the correct package for dotenv, which is python-dotenv.\npip install python-dotenv\n\n" ]
[ 1 ]
[]
[]
[ "pip", "python", "python_3.x" ]
stackoverflow_0074621173_pip_python_python_3.x.txt
Q: Create a new columns in dataframe equaling differenciated series I want to create a new column diff aqualing the differenciation of a series in a nother column. The following is my dataframe: df=pd.DataFrame({ 'series_1' : [10.1, 15.3, 16, 12, 14.5, 11.8, 2.3, 7.7,5,10], 'series_2' : [9.6,10.4, 11.2, 3.3, ...
Create a new columns in dataframe equaling differenciated series
I want to create a new column diff aqualing the differenciation of a series in a nother column. The following is my dataframe: df=pd.DataFrame({ 'series_1' : [10.1, 15.3, 16, 12, 14.5, 11.8, 2.3, 7.7,5,10], 'series_2' : [9.6,10.4, 11.2, 3.3, 6, 4, 1.94, 15.44, 6.17, 8.16] }) It has the following display: serie...
[ "here is one way to do it, using diff\n\n# create a new col by taking difference b/w consecutive rows of DF using diff\ndf['diff_2']=df['series_2'].diff()\ndf\n\n series_1 series_2 diff_2\n0 10.1 9.60 NaN\n1 15.3 10.40 0.80\n2 16.0 11.20 0.80\n3 12.0 3.30 -7.90\n4 14.5 6....
[ 2, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074621360_dataframe_pandas_python.txt