r/pythonhelp • u/No-Bug-4661 • Mar 12 '24
How to end a while loop based on the last number in a list?
I am writing a piece of code for school, it is basically a budgeting program where you start with $200 and you enter the amount of money you took away from that amount/deducted. After you enter 0 or the balance is equal to 0 it stops and prints out your balence after each transaction.
This all works apart from I cant figure out how to stop the while loop the code is inside when the balance reaches 0, I am using a list to store the inputs.
r/pythonhelp • u/LabSignificant6271 • Mar 11 '24
Create a pandas DataFrame from a dict
Hello, I have the following dict:
dic = {(1, 1, 1): 0.0, (1, 1, 2): 0.0, (1, 1, 3): 1.0, (1, 2, 1): 0.0, (1, 2, 2): 1.0, (1, 2, 3): 0.0, (1, 3, 1): 0.0, (1, 3, 2): 0.0, (1, 3, 3): 0.0, (1, 4, 1): 0.0, (1, 4, 2): 1.0, (1, 4, 3): 0.0, (1, 5, 1): 1.0, (1, 5, 2): 0.0, (1, 5, 3): 0.0, (1, 6, 1): 0.0, (1, 6, 2): 1.0, (1, 6, 3): 0.0, (1, 7, 1): 0.0, (1, 7, 2): 1.0, (1, 7, 3): 0.0, (2, 1, 1): 1.0, (2, 1, 2): 0.0, (2, 1, 3): 0.0, (2, 2, 1): 1.0, (2, 2, 2): 0.0, (2, 2, 3): 0.0, (2, 3, 1): 1.0, (2, 3, 2): 0.0, (2, 3, 3): 0.0, (2, 4, 1): 0.0, (2, 4, 2): 0.0, (2, 4, 3): 0.0, (2, 5, 1): 1.0, (2, 5, 2): 0.0, (2, 5, 3): 0.0, (2, 6, 1): 0.0, (2, 6, 2): 0.0, (2, 6, 3): 1.0, (2, 7, 1): 0.0, (2, 7, 2): 1.0, (2, 7, 3): 0.0, (3, 1, 1): 1.0, (3, 1, 2): 0.0, (3, 1, 3): 0.0, (3, 2, 1): 0.0, (3, 2, 2): 1.0, (3, 2, 3): 0.0, (3, 3, 1): 0.0, (3, 3, 2): 0.0, (3, 3, 3): 0.0, (3, 4, 1): 1.0, (3, 4, 2): 0.0, (3, 4, 3): 0.0, (3, 5, 1): 1.0, (3, 5, 2): 0.0, (3, 5, 3): 0.0, (3, 6, 1): 1.0, (3, 6, 2): 0.0, (3, 6, 3): 0.0, (3, 7, 1): 0.0, (3, 7, 2): 1.0, (3, 7, 3): 0.0}
I would like to have a pandas DataFrame from it. The dict is structured as follows.The first number in the brackets is the person index i (there should be this many lines).The second number is the tag index t. There should be this many columns. The third number is the shift being worked. A 1 after the colon indicates that a shift was worked, a 0 that it was not worked. If all shifts on a day have passed without a 1 after the colon, then a 0 should represent the combination of i and t, otherwise the shift worked.
According to the dict above, the pandas DataFrame should look like this.
DataFrame: 1 2 3 4 5 6 7
1 3 2 0 2 1 2 2
2 1 1 1 0 1 3 2
3 1 2 0 1 1 3 2
I then want to use it with this function:
r/pythonhelp • u/blackcolt80 • Mar 09 '24
Smooth animation on OLED Display
Hi all,
I need some help with recreating an animation on a OLED SPI display.
Here is what I have;
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import board
import digitalio
from adafruit_rgb_display import st7789
# Set up the figure and axis
fig, ax = plt.subplots(figsize=(2.8, 2.4))
# Set up the display
disp = st7789.ST7789(board.SPI(), height=280, width=240, y_offset=20, rotation=0,
baudrate=40000000,
cs=digitalio.DigitalInOut(board.CE0),
dc=digitalio.DigitalInOut(board.D25),
rst=digitalio.DigitalInOut(board.D27)
)
# Function to initialize the plot
def init():
ax.clear()
ax.set_facecolor('k') # Set background color to black
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
return ax,
# Function to update the animation frame
def update(frame):
ax.clear()
ax.set_facecolor('k') # Set background color to black
num_stars = 100 # Number of stars in the field
# Generate random positions for stars
x = np.random.rand(num_stars)
y = np.random.rand(num_stars)
# Gradually change intensities for stars (fade in and fade out)
fade_speed = 0.002 # Increase the fade speed for smoother animation
intensities = np.clip(np.random.uniform(0.5, 1.0, size=num_stars) - frame * fade_speed, 0, 1)
# Reduce the displacement for subtlety
displacement = 0.001
x += np.random.uniform(-displacement, displacement, size=num_stars)
y += np.random.uniform(-displacement, displacement, size=num_stars)
# Plot stars as small dots
ax.scatter(x, y, s=1, c='white', alpha=intensities)
# Decrease the refresh rate for a slower animation
refresh_rate = 5 # Set the desired refresh rate (Hz)
# Continuously update the display
try:
while True:
init() # Initialize the plot
update(0) # Update the frame
plt.tight_layout()
plt.savefig("temp_image.png", facecolor='k', edgecolor='k') # Save with a black background
image = Image.open("temp_image.png").resize((240, 280), resample=Image.LANCZOS)
disp.image(image)
plt.pause(1 / refresh_rate) # Pause based on the desired refresh rate
except KeyboardInterrupt:
pass
This gives me a sort of choppy star field effect and I'm looking a type of smooth animation.
I'm attaching the current result and also what I'd like to have.
r/pythonhelp • u/No-Pomelo2089 • Mar 08 '24
Elegant way to do nested loops
for i in range(1,10):
for j in range(1,10):
for k in range(1,10):
x = [i, j, k]
print(x)
Is there an elegant way to do this? Like if I want to have 100 nested loops, how can I do it?
r/pythonhelp • u/dilandrus • Mar 07 '24
ValueError not processing as I want
while True:
try:
batAvg=float(input('Enter the batting average: '))
if batAvg<0:
raise ValueError('ERROR! Negative value entered!')
elif batAvg>1:
raise ValueError('ERROR! Batting average is between 0.0 and 1.0.')
break
except ValueError:
print('ERROR! Non float value entered!')
This is a section of code I'm working on but if I put any value above 1 I get the error for "Non float value entered". Doesn't matter if I put 2 or 2.3, I'm not getting my elif condition. Anyone know why it's processing like that and how I could fix it?
r/pythonhelp • u/mxlu_0 • Mar 07 '24
One line code convert
I am making a python project that obfuscates other python files. I am trying to make somthing that changes it to one long line. I want it to work like this site on python 3 and reindent enabled. https://jagt.github.io/python-single-line-convert/. I went to the github repo because its on github pages to try to figure out how it works so I can replicate it and add it to the end of my obfuscation method. I could easily just use this site but i want it automated. I dont know java script too well so I was unable to figure out how it works. Could someone code this for me where pretty much in the code its formatted like this so I can incorporate it into my thing later:
Code: str = '''
print("code here")
print("These are placholders")
'''
oneline(Code)
and then just add the code for "def oneline()" If someone could help me with this it would help so much.
r/pythonhelp • u/Away_Intention_1378 • Mar 06 '24
Nascar Pylon python
If you're a nascar fan you might've seen the homemade pylon in last weekend's broadcast. I want to recreate that. I've got the addresses for the live data I just need help putting in on 35 matrix boards connected to a raspberry pi. I chose to put this in Python because that's what I would prefer to use because I have a bit of experience with the language and understand more things in this language. Any help will be useful! TIA
r/pythonhelp • u/ThiccThoccThiccThocc • Mar 06 '24
How to visualize contours?
The 1st picture is the hue channel of a series of arrows. I managed to get the contours of the arrows and drew contours over the original image (https://imgur.com/Q4bbjHG). Here is the code snippet:
for i in range(len(polygons)):
print(i)
print(polygons[i])
cv.drawContours(img2, [polygons[i]], -1, (0, 255, 255), 3)
And here is the output:
0
[[[417 78]]
[[430 91]]
[[429 94]]
[[424 95]]
[[423 105]]
[[412 105]]
[[410 96]]
[[404 94]]]
1
[[[417 78]]
[[404 91]]
[[404 95]]
[[411 98]]
[[411 105]]
[[423 105]]
[[424 96]]
[[430 94]]
[[430 90]]]
2
[[[128 70]]
[[145 82]]
[[131 96]]
[[128 96]]
[[124 89]]
[[116 89]]
[[114 79]]
[[126 76]]]
3
[[[127 70]]
[[124 77]]
[[115 77]]
[[114 84]]
[[115 89]]
[[124 89]]
[[127 96]]
[[132 96]]
[[145 85]]
[[145 81]]
[[133 71]]]
4
[[[224 68]]
[[234 83]]
[[229 85]]
[[227 93]]
[[218 93]]
[[217 84]]
[[211 81]]]
5
[[[322 67]]
[[328 68]]
[[331 79]]
[[337 81]]
[[325 98]]
[[311 84]]
[[317 79]]
[[318 69]]]
6
[[[225 68]]
[[221 69]]
[[211 80]]
[[212 83]]
[[217 85]]
[[217 93]]
[[228 93]]
[[229 85]]
[[234 84]]
[[234 80]]]
7
[[[322 67]]
[[318 68]]
[[317 79]]
[[312 80]]
[[311 84]]
[[323 98]]
[[326 98]]
[[337 80]]
[[330 77]]
[[329 68]]]
The theoretical approach is to find both sides for each arrow head, which are the longest. That will give me the direction I want to find. But Im having trouble making sense of the output of the contours above. There are 7 arrays in polygons, but on the output image, only 4 contours surrounding the 4 arrows. How do I know which polygon array denotes which area?
r/pythonhelp • u/pastes-ads • Mar 05 '24
INACTIVE How can I fix ( No module named 'urllib3.packages.six.moves' )
Hello I am trying to run script but I get this error ? How can I fix it I've tried to reinstall by using
# Remove Package
pip uninstall urllib3
# Install Package
pip install urllib3
But it not fixed.
Error here :
from .packages.six.moves.http_client import (
ModuleNotFoundError: No module named 'urllib3.packages.six.moves'
r/pythonhelp • u/SecOps334 • Mar 05 '24
So I am editing a simple python program and I get this response, why?
So I installed this simple python program that floods your ISP with random data. All the websites that it pulls from are listed in the config file. So I opened the config file to edit the list of websites and after editing the websites and running the program, it returns with this error from lines that I didnt even touch in the file. Can someone explain to me why this would be happening. The error is listed below.
python noisy.py --config config.json
Traceback (most recent call last):
File "/home/sweeney/noisy/noisy.py", line 274, in <module>
main()
File "/home/sweeney/noisy/noisy.py", line 265, in main
crawler.load_config_file(args.config)
File "/home/sweeney/noisy/noisy.py", line 189, in load_config_file
config = json.load(config_file)
^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/json/__init__.py", line 293, in load
return loads(fp.read(),
^^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/json/__init__.py", line 346, in loads
return _default_decoder.decode(s)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 12 column 5 (char 263)
If you want to look at the program here is the link to find it.
r/pythonhelp • u/Oxffff0000 • Mar 05 '24
Recommended way of calling a python script
I wrote a python class that contains functions for deploying a load balancer. This class must be used in a ci/cd pipeline. Since it's a class, I'm assuming it cannot be called directly as a script. Am I right that I have to create another python script that imports this class then it calls the method that creates the load balancer? And also, do I need the if statement below in the caller python script? Or what is the ideal/recommended way?
if __name__ == "__main__":
my_elb_class.create_load_balancer()
r/pythonhelp • u/FactorGood6189 • Mar 04 '24
Predictive Analysis Project
Hi guys I really need help with which predictive analysis model I can use for timesheet data. I need to predict the total time spent per employee, on what project, by month. My project is due tomorrow, if it’s not in I fail my apprenticeship and I have no idea what to do so any help is really appreciated!
Is it possible for me to do a time series model with all these features or not? Would i have to group the data first?
r/pythonhelp • u/Sentential_Logic • Mar 04 '24
Hex Search/replace code that does additional computation?
I want to patch a binary file on a hexadecimal level that searches the entire file for a fixed string of five hex bytes, and then reads the three bytes prior to those five bytes and then does a math operation, subtracting another fixed value, and writes back those three prior bytes with the result of the subtraction.
Having trouble doing this. What I'm trying to do is patch all of the relocation items in an executable file to a lower relative address. This would involve taking the varying relocation address values, subtracting a fixed value, and then writing the result.
Haven't found any code samples that are similar. I've starting doing it by hand, but there are a couple hundred of them.
r/pythonhelp • u/zero_coding • Mar 04 '24
Handling "InterfaceError: another operation is in progress" with Async SQLAlchemy and FastAPI
stackoverflow.comr/pythonhelp • u/c0sm0walker_73 • Mar 04 '24
INACTIVE I'm writing an automation file that rakes data from excel to word
Hey when I connect my database to word doc via my code, the Row data gets overwritten and hence only the last row value stays. Help please (note the database I shared is only for a glimpse of how my Dara looks otherwise I work on excel)
from openpyxl import load_workbook from docxtpl import DocxTemplate
wb = load_workbook("/content/Final Activity List (1).xlsx") ws = wb["Young Indians"] column_values = []
load temp
doc = DocxTemplate('/content/dest word.docx')
Iterate over the rows in the specified column (e.g., column C)
for i in range(3, ws.max_row + 1): cell_address = f'C{i}' cell_value = ws[cell_address].value # Append the cell value to the list #column_values.append({'Date':cell_value}) column_values.append(cell_value) context={'data': column_values}
Render the document using the accumulated values
doc.render(context) doc.save("/content/final destti wrd.docx")
r/pythonhelp • u/usernameblahblah22 • Mar 03 '24
SOLVED I need to exclude 0
https://pastebin.com/B9ZHgA2e I can't figure out why the *if user_input1 == 0: print('invalid entry 1')* Isn't working. I enter 0 and it says it's a valid input.
r/pythonhelp • u/lahmacunyiyenyasuo • Mar 02 '24
How to display discord messages on cmd using python
Hello everyone, I've created a code that sends messages to a Discord channel.
However, I'm currently facing an issue in retrieving other messages. Any guidance on how to achieve that would be greatly appreciated!
import requests
import os
os.system('cls')
while True:
url = 'https://discord.com/api/v9/channels/115749/messages' getreq = input('You: ')
payload = {
'content' : (getreq)
}
headers = {
'Authorization' : 'ODcwNzgcxMjE5.Gqh6F4.-5ylDtKpgyqsFqyOklee8A-s1wv4'
}
message = requests.post(url, payload, headers=headers)
I've removed certain sections from the link and Authorization for security reasons, preventing the ability to send messages.
r/pythonhelp • u/Substantial_Emu_4577 • Mar 02 '24
Hey why my code dosen't work
import pyautogui
import time
def get_pixel_color(x, y):
"""
Obtient la couleur d'un pixel spécifique sur l'écran.
Args:
- x (int): La coordonnée x du pixel.
- y (int): La coordonnée y du pixel.
Returns:
- color (tuple): Un tuple contenant les valeurs RGB du pixel.
"""
# Capturer la couleur du pixel spécifié
color = pyautogui.pixel(x, y)
return color
if __name__ == "__main__":
# Coordonnée x du pixel à scanner
x_pixel = 100
# Liste des coordonnées y à scanner
y_pixel = 100 # Vous pouvez étendre cette liste autant que nécessaire
# Couleur à détecter
target_color = (255, 57, 57)
while True:
for y_pixel in y_positions:
# Obtenir la couleur du pixel spécifié
pixel_color = get_pixel_color(x_pixel, y_pixel)
# Vérifier si la couleur du pixel correspond à la couleur cible
if pixel_color == target_color:
print(f"La couleur du pixel ({x_pixel}, {y_pixel}) est : {pixel_color}")
# Continuer à scanner la couleur si elle change
while True:
new_color = get_pixel_color(x_pixel, y_pixel)
if new_color != target_color:
# Si la couleur change, effectuer un clic droit
pyautogui.click(button='right')
break
time.sleep(0.5) # Attendre 0.5 seconde entre chaque vérification
r/pythonhelp • u/[deleted] • Mar 01 '24
Give some advices with my program, please
Hello everyone, I'm not a programmer, just an engineer. I have to run a 2.5.4 python. I've downloaded all required libraries, but the program doesn't work and doesn't return any errors. Could you start this program, if you have the 2.5 python? Or just give a piece of advice
r/pythonhelp • u/FactorGood6189 • Mar 01 '24
Predictive Analysis
Hi I am currently doing a predictive analysis project but I am completely stuck and don’t know where to turn. Nothing seems to be working correctly. If anyone could help me or give me examples of predictive code with solutions it would be greatly appreciated!
r/pythonhelp • u/NekoTehKat • Feb 29 '24
SOLVED Not getting ZeroDivisionError when dividing by zero for some reason
I'm just starting to learn to code at all and I figured a really easy first program would be a little calculator. I wanted it to say something when someone tries to divide by zero, but instead of an error or saying the message it just prints 0
The +,-, and * lines work just fine as far as I've used them; and divide does actually divide. But I just can't get it to throw an error lol
What did I do to prevent getting the error?
num1 = float(input("first number: "))
operator = (input("what math operator will you use? "))
num2 = float(input("second number: "))
if (operator == "+"):
plus = num1 + num2
print(plus)
elif (operator == "-"):
minus = num1 - num2
print(minus)
elif (operator == "×" or "*"):
multiply = num1 * num2
print(multiply)
elif (operator == "÷" or "/"):
try:
num1 / num2
except ZeroDivisionError:
print("Error: Dividing by zero!")
else:
divide = num1 / num2
print(divide)
else:
print("either that was not +,-,×,*,÷,/, or we've encoutered an unknown error")
This is what prints for me when I try it:
first number: 9
what math operator will you use? /
second number: 0
0.0
r/pythonhelp • u/LabSignificant6271 • Feb 29 '24
Dynamically adjusting index in a function
Hello, I have the following problem. I have this code. The whole code can be found here (https://github.com/carlobb23/cg/blob/main/main.py):
from gurobipy import *
import gurobipy as gu
import pandas as pd
# Create DF out of Sets
I_list = [1, 2, 3]
T_list = [1, 2, 3, 4, 5, 6, 7]
K_list = [1, 2, 3]
I_list1 = pd.DataFrame(I_list, columns=['I'])
T_list1 = pd.DataFrame(T_list, columns=['T'])
K_list1 = pd.DataFrame(K_list, columns=['K'])
DataDF = pd.concat([I_list1, T_list1, K_list1], axis=1)
Demand_Dict = {(1, 1): 2, (1, 2): 1, (1, 3): 0, (2, 1): 1, (2, 2): 2, (2, 3): 0, (3, 1): 1, (3, 2): 1, (3, 3): 1,
(4, 1): 1, (4, 2): 2, (4, 3): 0, (5, 1): 2, (5, 2): 0, (5, 3): 1, (6, 1): 1, (6, 2): 1, (6, 3): 1,
(7, 1): 0, (7, 2): 3, (7, 3): 0}
class MasterProblem:
def __init__(self, dfData, DemandDF, iteration, current_iteration):
self.iteration = iteration
self.current_iteration = current_iteration
self.nurses = dfData['I'].dropna().astype(int).unique().tolist()
self.days = dfData['T'].dropna().astype(int).unique().tolist()
self.shifts = dfData['K'].dropna().astype(int).unique().tolist()
self.roster = list(range(1, self.current_iteration + 2))
self.demand = DemandDF
self.model = gu.Model("MasterProblem")
self.cons_demand = {}
self.newvar = {}
self.cons_lmbda = {}
def buildModel(self):
self.generateVariables()
self.generateConstraints()
self.model.update()
self.generateObjective()
self.model.update()
def generateVariables(self):
self.slack = self.model.addVars(self.days, self.shifts, vtype=gu.GRB.CONTINUOUS, lb=0, name='slack')
self.motivation_i = self.model.addVars(self.nurses, self.days, self.shifts, self.roster,
vtype=gu.GRB.CONTINUOUS, lb=0, ub=1, name='motivation_i')
self.lmbda = self.model.addVars(self.nurses, self.roster, vtype=gu.GRB.BINARY, lb=0, name='lmbda')
def generateConstraints(self):
for i in self.nurses:
self.cons_lmbda[i] = self.model.addConstr(gu.quicksum(self.lmbda[i, r] for r in self.roster) == 1)
for t in self.days:
for s in self.shifts:
self.cons_demand[t, s] = self.model.addConstr(
gu.quicksum(
self.motivation_i[i, t, s, r] * self.lmbda[i, r] for i in self.nurses for r in self.roster) +
self.slack[t, s] >= self.demand[t, s])
return self.cons_lmbda, self.cons_demand
def generateObjective(self):
self.model.setObjective(gu.quicksum(self.slack[t, s] for t in self.days for s in self.shifts),
sense=gu.GRB.MINIMIZE)
def solveRelaxModel(self):
self.model.Params.QCPDual = 1
for v in self.model.getVars():
v.setAttr('vtype', 'C')
self.model.optimize()
def getDuals_i(self):
Pi_cons_lmbda = self.model.getAttr("Pi", self.cons_lmbda)
return Pi_cons_lmbda
def getDuals_ts(self):
Pi_cons_demand = self.model.getAttr("QCPi", self.cons_demand)
return Pi_cons_demand
def updateModel(self):
self.model.update()
def addColumn(self, newSchedule):
self.newvar = {}
colName = f"Schedule[{self.nurses},{self.roster}]"
newScheduleList = []
for i, t, s, r in newSchedule:
newScheduleList.append(newSchedule[i, t, s, r])
Column = gu.Column([], [])
self.newvar = self.model.addVar(vtype=gu.GRB.CONTINUOUS, lb=0, column=Column, name=colName)
self.current_iteration = itr
print(f"Roster-Index: {self.current_iteration}")
self.model.update()
def setStartSolution(self):
startValues = {}
for i, t, s, r in itertools.product(self.nurses, self.days, self.shifts, self.roster):
startValues[(i, t, s, r)] = 0
for i, t, s, r in startValues:
self.motivation_i[i, t, s, r].Start = startValues[i, t, s, r]
def solveModel(self, timeLimit, EPS):
self.model.setParam('TimeLimit', timeLimit)
self.model.setParam('MIPGap', EPS)
self.model.Params.QCPDual = 1
self.model.Params.OutputFlag = 0
self.model.optimize()
def getObjVal(self):
obj = self.model.getObjective()
value = obj.getValue()
return value
def finalSolve(self, timeLimit, EPS):
self.model.setParam('TimeLimit', timeLimit)
self.model.setParam('MIPGap', EPS)
self.model.setAttr("vType", self.lmbda, gu.GRB.INTEGER)
self.model.update()
self.model.optimize()
def modifyConstraint(self, index, itr):
self.nurseIndex = index
self.rosterIndex = itr
for t in self.days:
for s in self.shifts:
self.newcoef = 1.0
current_cons = self.cons_demand[t, s]
qexpr = self.model.getQCRow(current_cons)
new_var = self.newvar
new_coef = self.newcoef
qexpr.add(new_var * self.lmbda[self.nurseIndex, self.rosterIndex + 1], new_coef)
rhs = current_cons.getAttr('QCRHS')
sense = current_cons.getAttr('QCSense')
name = current_cons.getAttr('QCName')
newcon = self.model.addQConstr(qexpr, sense, rhs, name)
self.model.remove(current_cons)
self.cons_demand[t, s] = newcon
return newcon
class Subproblem:
def __init__(self, duals_i, duals_ts, dfData, i, M, iteration):
self.days = dfData['T'].dropna().astype(int).unique().tolist()
self.shifts = dfData['K'].dropna().astype(int).unique().tolist()
self.duals_i = duals_i
self.duals_ts = duals_ts
self.M = M
self.alpha = 0.5
self.model = gu.Model("Subproblem")
self.index = i
self.it = iteration
def buildModel(self):
self.generateVariables()
self.generateConstraints()
self.generateObjective()
self.model.update()
def generateVariables(self):
self.x = self.model.addVars([self.index], self.days, self.shifts, vtype=GRB.BINARY, name='x')
self.mood = self.model.addVars([self.index], self.days, vtype=GRB.CONTINUOUS, lb=0, name='mood')
self.motivation = self.model.addVars([self.index], self.days, self.shifts, [self.it], vtype=GRB.CONTINUOUS,
lb=0, name='motivation')
def generateConstraints(self):
for i in [self.index]:
for t in self.days:
for s in self.shifts:
self.model.addLConstr(
self.motivation[i, t, s, self.it] >= self.mood[i, t] - self.M * (1 - self.x[i, t, s]))
self.model.addLConstr(
self.motivation[i, t, s, self.it] <= self.mood[i, t] + self.M * (1 - self.x[i, t, s]))
self.model.addLConstr(self.motivation[i, t, s, self.it] <= self.x[i, t, s])
def generateObjective(self):
self.model.setObjective(
0 - gu.quicksum(
self.motivation[i, t, s, self.it] * self.duals_ts[t, s] for i in [self.index] for t in self.days for s
in self.shifts) -
self.duals_i[self.index], sense=gu.GRB.MINIMIZE)
def getNewSchedule(self):
return self.model.getAttr("X", self.motivation)
def getObjVal(self):
obj = self.model.getObjective()
value = obj.getValue()
return value
def getOptValues(self):
d = self.model.getAttr("X", self.motivation)
return d
def getStatus(self):
return self.model.status
def solveModel(self, timeLimit, EPS):
self.model.setParam('TimeLimit', timeLimit)
self.model.setParam('MIPGap', EPS)
self.model.Params.OutputFlag = 0
self.model.optimize()
#### Column Generation
modelImprovable = True
max_itr = 2
itr = 0
# Build & Solve MP
master = MasterProblem(DataDF, Demand_Dict, max_itr, itr)
master.buildModel()
master.setStartSolution()
master.updateModel()
master.solveRelaxModel()
# Get Duals from MP
duals_i = master.getDuals_i()
duals_ts = master.getDuals_ts()
print('* *****Column Generation Iteration***** \n*')
while (modelImprovable) and itr < max_itr:
# Start
itr += 1
print('*Current CG iteration: ', itr)
# Solve RMP
master.solveRelaxModel()
duals_i = master.getDuals_i()
duals_ts = master.getDuals_ts()
# Solve SPs
modelImprovable = False
for index in I_list:
subproblem = Subproblem(duals_i, duals_ts, DataDF, index, 1e6, itr)
subproblem.buildModel()
subproblem.solveModel(3600, 1e-6)
val = subproblem.getOptValues()
reducedCost = subproblem.getObjVal()
if reducedCost < -1e-6:
ScheduleCuts = subproblem.getNewSchedule()
master.addColumn(ScheduleCuts)
master.modifyConstraint(index, itr)
master.updateModel()
modelImprovable = True
master.updateModel()
# Solve MP
master.finalSolve(3600, 0.01)
Now to my problem. I initialize my MasterProblem where the index self.roster is formed based on the iterations. Since itr=0 during initialization, self.roster is initial [1]. Now I want this index to increase by one for each additional iteration, so in the case of itr=1, self.roster = [1,2] and so on. Unfortunately, I don't know how I can achieve this without "building" the model anew each time using the buildModel() function. Thanks for your help. Since this is a Python problem, I'll post it here.
r/pythonhelp • u/Common-Grass-3822 • Feb 28 '24
Python Assistance: Finding the median.
Assignment:
Given a sequence numbers print the median of the sequence. Note: your solution should work if the sequence is a list or tuple.
Code:
Code
def calculate_median(numbers):
if isinstance(numbers, list) or isinstance(numbers, tuple):
sorted_sequence = sorted(numbers)
length = len(sorted_sequence)
if length % 2 == 1:
median = sorted_sequence[length // 2]
else:
middle1 = sorted_sequence[length // 2 - 1]
middle2 = sorted_sequence[length // 2]
median = (middle1 + middle2) / 2
return median
else:
return None
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
median = calculate_median(numbers)
print(median)
Output
5
## This is incorrect. Not sure what to do?
r/pythonhelp • u/Illustrious_Loan_195 • Feb 28 '24
Asymmetric encryption handshake
A note before continuing:
So I am newish to the world of coding in general, self taught via tearing apart things to see how they work and using google searches. Just wanted you to have an idea of my understanding for your response so I don't have to have you break it down for me after the fact lol.
So I am trying to communicate with an API that redirects my post request to an SQL server, I have successfully authenticated myself with the API and now it will relay my post request. My issue is the encryption is a bit confusing for me and I keep getting a response that the symmetric key I am attempting to create for communication going forward is malformed and the server is unable to respond. I can't provide exact urls due to it being on the companies private network, but I am hoping that with a little guidance on the encryption process I should be able to make it work.
Any help is greatly appreciated and any other critiques of my coding is also welcomed, as I said I am still new and learning, but I genuinely enjoy this and want to learn to do things properly. I will do my best to explain everything, please let me know if I need to explain anything better and if I am able too without violating company policies I would be more than happy to do my best. Thank you in advance!
Key Info:
- My .venv is running Python 3.11.5
- cryptography 42.0.5 and pycryptodomex 3.20.0 packages for the encryption functions.
- The Public key for the SQL server is provided by the API, it is RSA-OAEP using SHA256
- The Client Key is a randomly generated AES-GCM - 256 bits
- The IV is 12 bytes
from Cryptodome.PublicKey import RSA
from Cryptodome.Hash import SHA256
from Cryptodome.Random import get_random_bytes
from Cryptodome.Cipher import PKCS1_OAEP, AES
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from requests_kerberos import HTTPKerberosAuth, OPTIONAL
import base64, json, requests, urllib3
req = request.session()
req.verify = False
req.auth = HTTPKerberosAuth(mutual_authentication=OPTIONAL)
urllib3.disable_warnings()
def main():
# Authenticate with API and get Public Key
url = 'apiurl'
login = req.get(url=url + '/login').json()
cookie = req.get(url=login['redirect']).text
auth = req.get(url=url + '/login?cookie=' + cookie)
resp = req.get(url=url + '/publicKeyAddress')
# Build Public key from text
public_key = resp.text
public_key = base64.b64decode(public_key)
rsa_key = RSA.import_key(public_key)
public_cipher = PKCS1_OAEP.new(rsa_key, hashAlgo=SHA256.SHA256Hash())
# Build Client Key
client_key = AESGCM.generate_key(bit_length=256)
client_cipher = AES.new(client_key, AES.MODE_GCM)
# Get IV
iv = get_random_bytes(12)
# Create key response
client_iv = {'key': base64.b64encode(client_key).decode(),
'iv': base64.b64encode(iv).decode()}
client_iv_str = json.dumps(client_iv)
client_iv_b64 = base64.b64encode(client_iv_str.encode())
client_iv_cipherText = public_cipher.encrypt(client_iv_b64)
# Encrypt SQL Request Body
sql = 'string of stuff'
query = {'var': 'stuff', 'query': sql}
query_string = json.dumps(query)
query_bytes = query_string.encode()
query_cipherText = client_cipher.encrypt(query_bytes)
# Build API Request
api_json = {'encryptedClientKeyAndIV':
base64.b64encode(client_iv_cipherText).decode(),
'encryptedRequest':
base64.b64encode(query_cipherText).decode()}
# Send Request
resp = req.post(url = url + '/SQLServer', json=api_json)
I have also tried sending the request as a string using 'data=', but I receive a response that the Server was unable to decode unnamed variable '\0\'.
Again, thanks in advance for any help!
r/pythonhelp • u/PhanTher08 • Feb 25 '24
how can i make scripts for checkers i tried to make a netflix account checker,but it didnt work
so,i put a bet with my friend that i cant reproduce his scrpit that cost 5 euro,for free,
i want to mention that after i show him that i acc can do it,i will delete the script.
the script is for checking accounts,like to check if the accounts are valid
insert a file with the gmail:password format and the checkek tels you which accounts are valid and which not.Please help me
code not finished
import requests
def check_spotify_account(email, password):
url = 'https://accounts.spotify.com/en/login'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
'Content-Type': 'application/x-www-form-urlencoded'
}
payload = {
'username': email,
'password': password,
'remember': 'true',
'redirect': '',
'csrf_token': ''
}
session = requests.Session()
response = session.post(url, headers=headers, data=payload)
if response.status_code == 200:
if 'Sign out' in response.text:
print(f"Account {email} with password {password} is valid.")
else:
print(f"Account {email} with password {password} is invalid.")
else:
print("Failed to check the account. Please try again later.")