#StackBounty: #python-3.x #flask Adding query parameter for every flask GET request

Bounty: 200

Trying to figure out the right mechanism to use here.

I want to modify the flask request coming in every time.

I think the request is immutable, so I am trying to figure out if this mechanism exists.

Basically, I want to append a string onto the end of the request coming in.

I can hook into the request and the right time in a before_request handler like this:

@app.before_app_request
def before_request_custom():
    # Get the request
    req = flask.request

    method = str(req.method)

    if method == "GET":
        # Do stuff here
        pass

But I am not sure what to actually do to add this in, and don’t see a way to accomplish it…I guess i could redirect, but that seems silly in this case. Any ideas?


Get this bounty!!!

#StackBounty: #python-3.x #django #django-models #ffmpeg #django-rest-framework Encoded Video's path gets changed in database after…

Bounty: 50

Hey guys the I have this code to transcode video and it works well without celery. With celery, the path of the file in the database shows a different path and the video cannot be played in the browser, but it saves the file in the correct location in the pc.

If I don’t use celery, then the file path in database is media/videos/videos/<filename>.mp4 and file also gets saved here. This way the template is able to play the video. But if i use celery, the output gets saved in media/videos/videos/<filename>.mp4 but the path in database will be media/<filename>.mp4 somehow and thus template can’t play the video.

Is it because my page gets updated before the task? and not getting saved properly?

views.py

def post(self, *args, **kwargs):
    form = VideoPostForm(self.request.POST or None, self.request.FILES or None)
    if form.is_valid():
        video = form.save(commit=False)
        video.user = self.request.user
        video.save()
        form.save_m2m()
        # task_video_encoding(video.id)
        task_video_encoding.delay(video.id)
        return redirect(reverse('videos:my_video_home'))
    else:
        raise ValidationError('Check all form fields.')

encoding.py

def encode_video(video_id):
    video = VideoPost.objects.get(id = video_id)
    input_file_path = video.temp_file.path
    # print(input_file_path)
    input_file_name = video.title
    #get the filename (without extension)
    filename = os.path.basename(input_file_path)
    # print(filename)
    # path to the new file, change it according to where you want to put it
    output_file_name = os.path.join('{}.mp4'.format(filename))
    # print(output_file_name)
    # output_file_path = os.path.join(settings.MEDIA_ROOT, output_file_name)
    output_file_path = os.path.join(settings.MEDIA_ROOT, 'videos', 'videos', output_file_name)
    # print(output_file_path)

    for i in range(1):
        subprocess.call([settings.VIDEO_ENCODING_FFMPEG_PATH, '-i', input_file_path, '-codec:v', 'libx264', '-crf', '-preset', 'medium',
                    '-b:v', '3000k', '-maxrate', '-bufsize', '6000k', '-vf', 'scale=-2:720',
                    '-codec:a', 'aac', '-b:a', '128k', '-strict', '-2', output_file_path])
    # Save the new file in the database
    video.file = output_file_name
    video.save(update_fields=['file'])
    print(video.file)
    video.temp_file.delete()

models

class VideoPost(models.Model):
    user                = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True)
    title               = models.TextField(max_length=1000)
    temp_file           = models.FileField(upload_to='videos/temp_videos/', validators=[validate_file_extension], null=True)
    file                = models.FileField(upload_to='videos/videos/', validators=[validate_file_extension], blank=True, max_length=255)
    post_date           = models.DateTimeField(auto_now_add=True, verbose_name="Date Posted")
    updated             = models.DateTimeField(auto_now_add=True, verbose_name="Date Updated")
    slug                = models.SlugField(blank=True, unique=True, max_length=255)

Can anyone help me how to change this code in a way to show the converted video properly in the template.


Get this bounty!!!

#StackBounty: #python #python-3.x #pygame Dungeon Ball, a Pygame

Bounty: 50

I just completed the first release for my first game on Python, called Dungeon Ball. I’m looking for people to test out the app and give me some feedback and constructive criticism. I’d like to use this project as a way to improve my programming skills and hopefully learn some efficient programming practices.

The game is called Dungeon Ball. It is pretty basic at the moment. It is pretty similar to games on breaking bricks with a ball and a racquet/paddle but I haven’t included the bricks just yet. Currently, the goal is to just keep the ball from falling using the paddle. By hitting the paddle you get points, which causes you to level up. The higher the level, the faster the paddle and ball move.

Main.py

import pygame
from pygame.locals import *
import numpy as np 
import math
from sys import exit
pygame.init()

from variables import *

def gameOver():
    pygame.mixer.music.stop()
    sounds['gameOver'].play()
    keyStatus = True
    blinkerCount = 0
    blinkerState = True
    blinkTime = 15
    while keyStatus:
        pygame.draw.rect(DISPLAYSURF, colours['grey'], dimensions['arena'])
        # pygame.draw.rect(DISPLAYSURF, colours['brown'], dimensions['arena'], borderWidth)
        if blinkerState:
            textSurfaceObj = fonts['largeFont'].render('GAME OVER!', True, colours['red'])
            textRectObj = textSurfaceObj.get_rect()
            textRectObj.center = (boxSize[0]/2, boxSize[1]/2)
            DISPLAYSURF.blit(textSurfaceObj, textRectObj)

        scoreSurface = fonts['midFont'].render('Score : {}'.format(gameStatus['points']), True, colours['white'])
        scoreSurfaceRect = scoreSurface.get_rect()
        scoreSurfaceRect.center = (boxSize[0]/2, boxSize[1]/2 + 50)
        DISPLAYSURF.blit(scoreSurface, scoreSurfaceRect)

        blinkerCount += 1

        if blinkerCount % blinkTime == 0:
            blinkerCount = 0
            blinkerState = not blinkerState

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RETURN:
                    sounds['gameOver'].stop()
                    keyStatus = False
                elif event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    exit()

        pygame.display.update()
        fpsClock.tick(FPS)

        if keyStatus == False:
            break

    main()

def renderFunction():
    global gameStatus
    pygame.draw.rect(DISPLAYSURF, colours['black'], dimensions['arena'])
    pygame.draw.rect(DISPLAYSURF, colours['brown'], dimensions['arena'], borderWidth)
    pygame.draw.rect(DISPLAYSURF, colours['red'], dimensions['paddle'])
    pygame.draw.circle(DISPLAYSURF, colours['blue'], (ball['position']['x'], ball['position']['y']), ball['rad'] , 0)
    pointSurface = fonts['tinyFont'].render('Points : ' + str(gameStatus['points']), True, colours['white'])
    pointSurfaceRect = pointSurface.get_rect()
    pointSurfaceRect.center = (40, boxSize[1]-10)
    DISPLAYSURF.blit(pointSurface, pointSurfaceRect)

    levelSurface = fonts['tinyFont'].render('Level : ' + str(gameStatus['level']), True, colours['white'])
    levelSurfaceRect = levelSurface.get_rect()
    levelSurfaceRect.center = (boxSize[0]-40, boxSize[1]-10)
    DISPLAYSURF.blit(levelSurface, levelSurfaceRect)

def introScreen():
    keyStatus = True
    blinkerCount = 0
    blinkerState = True
    blinkTime = 15
    pygame.mixer.music.load('audio/startScreenMusic.wav')
    pygame.mixer.music.play(-1, 0.0)
    while keyStatus:
        pygame.draw.rect(DISPLAYSURF, colours['grey'], dimensions['arena'])
        # pygame.draw.rect(DISPLAYSURF, colours['brown'], dimensions['arena'], borderWidth)
        textSurfaceObj = fonts['largeFont'].render(gameStatus['name'], True, colours['gold'])
        textRectObj = textSurfaceObj.get_rect()
        textRectObj.center = (boxSize[0]/2, boxSize[1]/2)
        DISPLAYSURF.blit(textSurfaceObj, textRectObj)

        if blinkerState:
            spaceSurfaceObj = fonts['midFont'].render('Press Enter to Continue', True, colours['white'])
            spaceRectObj = spaceSurfaceObj.get_rect()
            spaceRectObj.center = (boxSize[0]/2, boxSize[1]/2+50)
            DISPLAYSURF.blit(spaceSurfaceObj, spaceRectObj)

        versionSurface = fonts['tinyFont'].render(gameStatus['version'], True, colours['white'])
        versionSurfaceRect = versionSurface.get_rect()
        versionSurfaceRect.center = (boxSize[0]-20, boxSize[1]-10)
        DISPLAYSURF.blit(versionSurface, versionSurfaceRect)
        blinkerCount += 1

        if blinkerCount % blinkTime == 0:
            blinkerCount = 0
            blinkerState = not blinkerState

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RETURN:
                    keyStatus = False
                elif event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    exit()
        pygame.display.update()
        fpsClock.tick(FPS)

    keyStatus=True
    pygame.mixer.music.stop()       

def eventHandler():
    global dimensions
    keys=pygame.key.get_pressed()
    if keys[K_LEFT] and not (dimensions['paddle'].left <= (dimensions['arena'].left+borderWidth)):
        direction = -1*paddle['speed']
        # print('hi left')
        paddle['position']['x'] += direction
    elif keys[K_RIGHT] and not (dimensions['paddle'].right >= (dimensions['arena'].right-borderWidth)):
        direction = paddle['speed']
        # print('hi right')
        paddle['position']['x'] += direction
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            exit()

    dimensions['paddle'] = pygame.Rect(paddle['position']['x'], paddle['position']['y'], paddle['length'], 10)

def ballEngine():
    global gameStatus
    if (ball['position']['x'] <= (dimensions['arena'].left+borderWidth+ball['rad'])):
        # print('LeftSideBounce')
        ball['direction'] = 180 - ball['direction'] + np.random.randint(-1*gameStatus['random'],gameStatus['random'])
        sounds['wallHit'].play()

    elif (ball['position']['x'] >= (dimensions['arena'].right-borderWidth-ball['rad'])):
        # print('RightSideBounce')
        ball['direction'] = 180 - ball['direction'] + np.random.randint(-1*gameStatus['random'],gameStatus['random'])
        sounds['wallHit'].play()

    elif ball['position']['y'] <= (dimensions['arena'].top+borderWidth+ball['rad']):
        # print('TopBounce')
        ball['direction'] = 360 - ball['direction'] + np.random.randint(-1*gameStatus['random'],gameStatus['random'])

        if ball['direction'] >= 250 and ball['direction'] <= 290:
            ball['direction'] += np.random.randint(-2*gameStatus['random'],2*gameStatus['random'])

        sounds['wallHit'].play()
    elif ball['position']['y'] >= (dimensions['arena'].bottom - borderWidth - ball['rad']):
        # print('BottomBounce')
        # ball['speed'] = 0
        # gameStatus = True
        gameOver()
    # print(ball['direction'])
    if (ball['position']['y'] >= (paddle['position']['y']-ball['rad']) and ball['position']['y'] <= paddle['position']['y']+dimensions['paddle'].height+ball['rad']) and ball['position']['x'] >= dimensions['paddle'].left and ball['position']['x'] <= dimensions['paddle'].right:
        # print('Paddle hit')
        ball['direction'] = 360 - ball['direction'] + np.random.randint(-1*gameStatus['random'],gameStatus['random'])
        gameStatus['points'] = gameStatus['points'] + 1

        sounds['paddleHit'].play()
        print(ball['position'], paddle['position'], ball['direction'])

        gameStatus['paddleHitsPerLevel'] += 1

        if ball['position']['y'] >= dimensions['paddle'].top and ball['position']['y'] <= dimensions['paddle'].bottom:
            ball['position']['y'] = dimensions['paddle'].top - ball['rad']

        if gameStatus['paddleHitsPerLevel'] == (gameStatus['level']*5) and not gameStatus['points']  == 0:
            ball['speed'] += 2
            gameStatus['level'] += 1
            gameStatus['random'] += 2
            gameStatus['paddleHitsPerLevel'] = 0
            sounds['levelUp'].play()

        if gameStatus['points'] % 10 == 0 and not gameStatus['points']  == 0:
            paddle['speed'] += 1

    if (ball['direction']>360 or ball['direction'] < 0):
        ball['direction'] %= 360

    if ball['direction'] % 90 >= 85 and ball['direction'] % 90 <=89 or ball['direction'] % 90 >= 0 and ball['direction'] % 90 <= 5:
        ball['direction'] += np.random.randint(-2*gameStatus['random'],2*gameStatus['random'])


    if ball['position']['y'] < borderWidth+ball['rad']:
        ball['position']['y'] = borderWidth+ball['rad']
    elif ball['position']['x'] < borderWidth+ball['rad']:
        ball['position']['x'] = borderWidth+ball['rad']
    elif ball['position']['x'] > dimensions['arena'].right-borderWidth-ball['rad']:
        ball['position']['x'] = dimensions['arena'].right-borderWidth-ball['rad']

    ball['position']['x'] += int(ball['speed']*math.cos(ball['direction']*math.pi/180))
    ball['position']['y'] += int(ball['speed']*math.sin(ball['direction']*math.pi/180))

def init():
    global ball, paddle, gameStatus
    ball['position']['x']=boxSize[0]/2
    ball['position']['y']=int(boxSize[1]/3)
    ball['direction']=np.random.randint(295, 325)
    ball['speed']=5
    ball['rad']=5

    paddle['position']['x']=boxSize[0]/2
    paddle['position']['y']=boxSize[1]-50
    paddle['length']=100
    paddle['speed']=5

    gameStatus['points']=0
    gameStatus['level']=1
    gameStatus['random']=5

def main():
    introScreen()
    init()
    pygame.mixer.music.load('audio/gamePlayMusic.wav')
    pygame.mixer.music.play(-1, 0.0)

    while True:
        eventHandler()
        ballEngine()
        renderFunction()
        pygame.display.update()
        fpsClock.tick(FPS)

if __name__ == '__main__':
    fpsClock = pygame.time.Clock()
    DISPLAYSURF = pygame.display.set_mode(boxSize, 0, 32)
    pygame.display.set_caption(gameStatus['name'])
    main()

Variables.py

import numpy as np
import pygame
pygame.init()
from pygame.locals import *
import os

FPS = 30
borderWidth = 5

boxSize = (700, 400)

colours = {'black':(0, 0, 0),
           'red': (255, 0, 0),
           'blue':(0, 0, 255),
           'brown':(210, 105, 30),
           'green':(0, 255, 0),
           'white':(255, 255, 255),
           'gold':(255, 215, 0),
           'silver':(192, 192, 192),
           'grey':(128, 128, 128)}

ball = {'position':{'x':boxSize[0]/2, 'y':boxSize[1]/3}, 'direction':np.random.randint(295, 325), 'speed':5, 'rad':5}

paddle = {'position':{'x':boxSize[0]/2, 'y':boxSize[1]-50}, 'length':100, 'speed':5}

dimensions = {
              'arena': pygame.Rect(0, 0, boxSize[0], boxSize[1]+10), 
              'paddle': pygame.Rect(paddle['position']['x'], paddle['position']['y'], paddle['length'], 10)
             }

gameStatus = {'points': 0, 'level': 1, 'random': 5, 'paddleHitsPerLevel':0, 'name': 'Dungeon Ball', 'version': 'v1.0'}


fonts = {
         'largeFont':pygame.font.Font(os.path.join(os.getcwd(),'fonts','Ancient_Modern_Tales_Regular.ttf'), 64),
         'midFont':pygame.font.Font(os.path.join(os.getcwd(),'fonts', 'Old_School_Adventures_Regular.ttf'), 12),
         'tinyFont': pygame.font.Font(os.path.join(os.getcwd(),'fonts', 'Old_School_Adventures_Regular.ttf'), 8)
        }

sounds = {
            'paddleHit': pygame.mixer.Sound(os.path.join(os.getcwd(), 'audio', 'paddle_hit.wav')), 
            'wallHit': pygame.mixer.Sound(os.path.join(os.getcwd(), 'audio', 'wall_hit.wav')), 
            'gameOver':pygame.mixer.Sound(os.path.join(os.getcwd(), 'audio', 'game_over.wav')),
            'levelUp': pygame.mixer.Sound(os.path.join(os.getcwd(), 'audio', 'level_up.wav'))
        }

Currently, the release is only for Linux and Windows. Mac users could try and build the environment and run the program directly. First step, you need to download your OS specific release and unzip it. Enter the extracted directory. Windows users just double click to run. Linux users need to open the directory in terminal and run ./main.


Get this bounty!!!

#StackBounty: #python #python-3.x #pandas #dataframe #pandas-groupby How to check for stuck data in a pandas dataframe

Bounty: 50

All,

** EDIT **

Please show timing as dealing with time-series data can have a lot of rows.

This is a common problem that I face while working with time-series data sets across languages. So, let us say we have hourly data for a day. I would like to check for 2 things:

  1. Variable # of consecutive stuck values depending on a group
  2. Jumps in data which violate a tolerance

Here is the example data set to work with and what I have attempted:

import pandas as pd
import numpy as np

# Constants
UPPER_LIMIT_RANGE_FILTER = 1.2
LOWER_LIMIT_RANGE_FILTER = 0.5


def count_consecutive_values(
        df_input: pd.DataFrame,
        column: str,
        n_consecutive_values: int
) -> pd.DataFrame:
    """

    :param df_input: input data frame to test consecutive values in
    :param column: column with consecutive values in
    :param n_consecutive_values: # of consecutive occurrences to count
    :return: original data frame with an extra column called 'count'
    """
    df_input[column + '_count'] = df_input[column].groupby(
        (df_input[column] != df_input[column].shift(n_consecutive_values)).cumsum()).cumsum()
    return df_input


# Create a random data frame
df = pd.DataFrame(data=[["2015-01-01 00:00:00", -0.76, 2, 2, 1.2],
                        ["2015-01-01 01:00:00", -0.73, 2, 4, 1.1],
                        ["2015-01-01 02:00:00", -0.71, 2, 4, 1.1],
                        ["2015-01-01 03:00:00", -0.68, 2, 32, 1.1],
                        ["2015-01-01 04:00:00", -0.65, 2, 2, 1.0],
                        ["2015-01-01 05:00:00", -0.76, 2, 2, 1.2],
                        ["2015-01-01 06:00:00", -0.73, 2, 4, 1.1],
                        ["2015-01-01 07:00:00", -0.71, 2, 4, 1.1],
                        ["2015-01-01 08:00:00", -0.68, 2, 32, 1.1],
                        ["2015-01-01 09:00:00", -0.65, 2, 2, 1.0],
                        ["2015-01-01 10:00:00", -0.76, 2, 2, 1.2],
                        ["2015-01-01 11:00:00", -0.73, 2, 4, 1.1],
                        ["2015-01-01 12:00:00", -0.71, 2, 4, 1.1],
                        ["2015-01-01 13:00:00", -0.68, 2, 32, 1.1],
                        ["2015-01-01 14:00:00", -0.65, 2, 2, 1.0],
                        ["2015-01-01 15:00:00", -0.76, 2, 2, 1.2],
                        ["2015-01-01 16:00:00", -0.73, 2, 4, 1.1],
                        ["2015-01-01 17:00:00", -0.71, 2, 4, 1.1],
                        ["2015-01-01 18:00:00", -0.68, 2, 32, 1.1],
                        ["2015-01-01 19:00:00", -0.65, 2, 2, 1.0],
                        ["2015-01-01 20:00:00", -0.76, 2, 2, 1.2],
                        ["2015-01-01 21:00:00", -0.73, 2, 4, 1.1],
                        ["2015-01-01 22:00:00", -0.71, 2, 4, 1.1],
                        ["2015-01-01 23:00:00", -0.68, 2, 32, 1.1],
                        ["2015-01-02 00:00:00", -0.65, 2, 2, 1.0]],
                  columns=['DateTime', 'column1', 'column2', 'column3', 'column4'])
consecutive_values_to_test_for = {
    'Zone_1': 4,
    'Zone_2': 2
}

# Set the index
df["DateTime"] = pd.to_datetime(df["DateTime"])
df.set_index("DateTime", inplace=True)

# Calculate difference between every 2 values in each column
df1 = df.diff()
print(df1)

# Add hour and time of day to create flag
df1['Hour'] = df1.index.hour
df1['Flag'] = np.where((df1['Hour'] <= 8) | (df1['Hour'] >= 18), 'Zone1', 'Zone2')

# Create Groups & apply filters on groups
grouped_data = df1.groupby(['Flag'])

Problem 1 :

So, I have split my day’s worth of data into 2 sets – Zone1 and Zone2. Now, I would like to see if the data is stuck. There should be a boolean flag at every timestamp when at least 2 consecutive occurrences of a value are observed in Zone 1, while this should happen if there are at least 4 consecutive occurrences of the value are observed in Zone 2.

Problem 2 :

I would like a boolean flag at every timestamp when the value in a column changes from one timestamp to another by more than the pre-defined tolerance value.

I think, problem-2 is straightforward and could be solved with the following, but I could use some help with detecting the stuck values.

My solution for problem-2 or jump values

def flag_jumps(
        df_input: pd.DataFrame,
        tolerance: float = 10**-2
) -> pd.DataFrame:
    """
    Returns a data frame the size of the input

    Flags rows in each column where tolerance is violated
    :param df_input: input data frame to test for jumps
    :param tolerance: acceptable value of tolerance
    :return: data frame with flags indicating whether tolerance has been violated or not
    """
    # Calculate the difference between every two rows
    df2 = df_input.diff()
    
    # Check for tolerance violation
    df3 = df2.gt(tolerance)

    return df3


Get this bounty!!!

#StackBounty: #python-3.x #bing-maps #geocoder Open a Bing Map of the world and put a pushpin on a location in Python 3

Bounty: 100

Given a Bing Maps API key, Python 3 and the location on a Bing Map of a city, as given by for example

import geocoder # pip install geocoder
g = geocoder.bing('Mountain View, CA', key=BING_KEY)
print(g.json['bbox'])

How do I, in Python 3 and using geocoder with or without another package:

  • Open up Bing Maps to a map of the world
  • Set a pushpin on Mountain View, as specified by the BBOX or any other element of the JSON from Bing obtained as above using geocoder?

Microsoft shows Javascript examples but doesn’t seem to have a native Python API, and I couldn’t find a Bing Maps API for pushpins in GitHub, only a few APIs that extract information but not any that decorate a map.


Get this bounty!!!

#StackBounty: #python-3.x #pyqt5 #filtering #qtableview #qsqltablemodel How to create filter rows for Qtableview with using QSqlTableMo…

Bounty: 50

Is it possible to create row filter for Qtableview with QSqlTableModel.
I am sing " QSqlTableModel" to show the data on Qtableview from SQLite thats working. But i am trying to filter rows. When i am executing the code i am getting below error is

line 44, in
for row in range(self.model.rowCount()) AttributeError: ‘QSqlTableModel’ object has no attribute ‘item’

I Tried but did not get any solution. Is it possible to make this with QSqlTableModel?
i want to show filtered items from tableview when i clicked on any of the columns of Qtableview. I am using Qtableview with QSqlTableModel.

I want to do like shown in the image is
enter image description here

from PyQt5 import QtCore, QtGui, QtWidgets, QtSql
from PyQt5.QtSql import *


class myWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(myWindow, self).__init__(parent)
        self.centralwidget  = QtWidgets.QWidget(self)
        self.view           = QtWidgets.QTableView(self.centralwidget)

        self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)

        self.gridLayout.addWidget(self.view, 1, 0, 1, 3)

        self.setCentralWidget(self.centralwidget)

       # self.model = QtGui.QStandardItemModel(self)

        db = QSqlDatabase.addDatabase("QSQLITE")
        db.setDatabaseName("model.db")
        db.open()

        self.model = QSqlTableModel(self)
        self.model.setTable("sheet")
        self.model.select()
        self.view.setModel(self.model)

        self.proxy = QtCore.QSortFilterProxyModel(self)
        self.proxy.setSourceModel(self.model)

        self.view.setModel(self.proxy)


        self.horizontalHeader = self.view.horizontalHeader()
        self.horizontalHeader.sectionClicked.connect(self.on_view_horizontalHeader_sectionClicked)

    @QtCore.pyqtSlot(int)
    def on_view_horizontalHeader_sectionClicked(self, logicalIndex):
        self.logicalIndex   = logicalIndex
        self.menuValues     = QtWidgets.QMenu(self)
        self.signalMapper   = QtCore.QSignalMapper(self)  

        valuesUnique = [    self.model.item(row, self.logicalIndex).text()
                            for row in range(self.model.rowCount())
                            ]

        actionAll = QtWidgets.QAction("All", self)
        actionAll.triggered.connect(self.on_actionAll_triggered)
        self.menuValues.addAction(actionAll)
        self.menuValues.addSeparator()


        for actionNumber, actionName in enumerate(sorted(list(set(valuesUnique)))):              
            action = QtWidgets.QAction(actionName, self)
            self.signalMapper.setMapping(action, actionNumber)  
            action.triggered.connect(self.signalMapper.map)  
            self.menuValues.addAction(action)

        self.signalMapper.mapped.connect(self.on_signalMapper_mapped)  

        headerPos = self.view.mapToGlobal(self.horizontalHeader.pos())        

        posY = headerPos.y() + self.horizontalHeader.height()
        posX = headerPos.x() + self.horizontalHeader.sectionPosition(self.logicalIndex)

        self.menuValues.exec_(QtCore.QPoint(posX, posY))

    @QtCore.pyqtSlot()
    def on_actionAll_triggered(self):
        filterColumn = self.logicalIndex
        filterString = QtCore.QRegExp(  "",
                                        QtCore.Qt.CaseInsensitive,
                                        QtCore.QRegExp.RegExp
                                        )

        self.proxy.setFilterRegExp(filterString)
        self.proxy.setFilterKeyColumn(filterColumn)

    @QtCore.pyqtSlot(int)
    def on_signalMapper_mapped(self, i):
        stringAction = self.signalMapper.mapping(i).text()
        filterColumn = self.logicalIndex
        filterString = QtCore.QRegExp(  stringAction,
                                        QtCore.Qt.CaseSensitive,
                                        QtCore.QRegExp.FixedString
                                        )

        self.proxy.setFilterRegExp(filterString)
        self.proxy.setFilterKeyColumn(filterColumn)


if __name__ == "__main__":
    import sys

    app  = QtWidgets.QApplication(sys.argv)
    main = myWindow()
    main.show()
    main.resize(400, 600)
    sys.exit(app.exec_())


Get this bounty!!!

#StackBounty: #python-3.x #django #django-request How to send POST request after form submit 302 in Django?

Bounty: 50

I have an implimentation as follows,

  1. There is a payment form wherein user fills all the details.(API1), here I’m getting 302.
    enter image description here
  2. On submit of that form one of the function in my views is called.
  3. In the backend implimentation ie. in views.py, I want to send a POST request to one of the gateways I have integrated.(API2)
    enter image description here

But the problem is coming as the request is going as GET and hence it is dropping all the form data I’m sending along with the request.

Following is the code for the same,
views.py –>

headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
}
payload = {
    'CustomerID': 'abc',
    'TxnAmount': '1.00',
    'BankID': '1',
    'AdditionalInfo1': '999999999',
    'AdditionalInfo2': 'test@test.test',
}


payload_encoded = urlencode(payload, quote_via=quote_plus)

response = requests.post('https://www.billdesk.com/pgidsk/PGIMerchantRequestHandler?hidRequestId=****&hidOperation=****', data=payload_encoded, headers=headers)

content = response.url
return_config = {
    "type": "content",
    "content": redirect(content)
}
return return_config

How do i send the 2nd request(API2) as POST request along with all params?

What am i doing wrong here?
Thank you for your suggestions.


Get this bounty!!!

#StackBounty: #python-3.x #summarization Pandas Data Summarization

Bounty: 50

I have a fuzzy data, which is as below. Kindly note that the first item has repeating names(which is kind of important to consider).

('Alex', ['String1', 'String34'])
('Piper', ['String5', 'String64', 'String12'])
('Nicky', ['String3', 'String21', 'String42', 'String51'])
('Linda', ['String14'])
('Suzzane', ['String11', 'String36', String16'])
('Alex', ['String64', 'String34', 'String12', 'String5'])
('Linda', ['String3', 'String77'])
('Piper', ['String41', 'String64', 'String11', 'String34'])
('Suzzane', ['String12'])
('Nicky', ['String11',  'String51'])
('Alex', ['String77', 'String64', 'String3', 'String5'])
('Linda', ['String51'])
('Nicky', ['String77', 'String12', 'String34'])
('Suzzane', ['String51', 'String3'])
('Piper', ['String11', 'String64', 'String5'])

Is it possible that the data can be summarized as shown below?

[Only unique names remain, and for each main name, only unique strings will be populated from all the duplicates that existed]

('Alex', ['String1', 'String34', 'String64', 'String12', 'String5', 'String77', 'String3'])
('Piper', ['String5', 'String64', 'String12', 'String11', 'String41', 'String34'])
('Nicky', ['String3', 'String21', 'String42', 'String51', 'String11', 'String77', 'String12', 'String34'])
('Linda', ['String14', 'String3', 'String77', 'String51'])
('Suzzane', ['String11', 'String36', 'String16', 'String12', 'String51', 'String3'])


Get this bounty!!!

#StackBounty: #python-3.x #django #django-models Django Models inheritance and avoid using multiple django.setup() calls

Bounty: 50

We are using Django’s ORM portion of the framework.

We have 1 Shared app, and a couple of Apps, without relationship between themselves. the Shared app defines an abstract BaseModel that all other models from all other apps inherit from, along with a few shared models, that may be referenced as a foreign key in the other apps.

We are using a monorepo, so no different repositories or anything like that.

These models can be used in various applications, from (non django) web apps, and to processing units that are deployed when needed and gets destroyed when done with their processing.

I’m trying to understand if there’s a single place we can call

import django
django.setup()

and remove the need to call it in the top of every app that imports one of the models, and that will comply with both of our unittests and service run.

This is the shared models.py file

import json
import uuid
from datetime import datetime

import common.db.enums as shared_enums
from django.db import models
from django.db.models import CASCADE

MAX_VARCHAR_LENGTH = 255


def generate_uuid():
    return uuid.uuid4().hex


class UUIDString(models.UUIDField):  # pragma: no cover
    def from_db_value(self, value, expression, connection):
        if isinstance(value, uuid.UUID):
            return value.hex
        else:
            return value



class BaseModel(models.Model):  # pragma: no cover
    id = UUIDString(primary_key=True, default=generate_uuid, editable=False, unique=True, db_index=True)
    created_on = models.DateTimeField(default=datetime.now)
    updated_on = models.DateTimeField(auto_now_add=True)

    class Meta:
        abstract = True


class Customer(BaseModel):  # pragma: no cover
    customer_guid = UUIDString(max_length=MAX_VARCHAR_LENGTH, db_index=True, unique=True)


class FlowInstance(BaseModel):  # pragma: no cover
    name = models.CharField(max_length=MAX_VARCHAR_LENGTH, null=False)
    customer = models.ForeignKey(Customer, on_delete=CASCADE, db_index=True)
    flow_type = models.IntegerField(null=True, choices=shared_enums.FlowType.get_choices())
    created_by = models.CharField(max_length=MAX_VARCHAR_LENGTH, null=True)


class FlowRun(BaseModel):  # pragma: no cover
    flow_instance = models.ForeignKey(FlowInstance, on_delete=CASCADE, db_index=True)
    status = models.IntegerField(null=True, choices=shared_enums.ExecutionStatus.get_choices())
    start_time = models.DateTimeField(null=True)
    finish_time = models.DateTimeField(null=True)


class FlowRunResults(BaseModel):  # pragma: no cover
    flow_run = models.OneToOneField(FlowRun, on_delete=CASCADE, db_index=True)
    errors = models.TextField(null=True)
    output_location = models.TextField(null=True)

And this is one of the apps using the shared models.py

from common.db.shared.models import BaseModel, FlowInstance, FlowRun, UUIDString, MAX_VARCHAR_LENGTH
from django.db import models
from django.db.models.deletion import CASCADE, DO_NOTHING


class Action(BaseModel):  # pragma: no cover
    action_id = models.CharField(max_length=MAX_VARCHAR_LENGTH, null=True, db_index=True)
    action_name = models.CharField(max_length=MAX_VARCHAR_LENGTH, null=True)


class DataSetDetails(BaseModel):  # pragma: no cover
    action = models.OneToOneField(Action, on_delete=DO_NOTHING, db_index=True, null=False)
    frequency = models.IntegerField(null=True)
    identified_frequency = models.IntegerField(null=True)


class RunDataSet(BaseModel):  # pragma: no cover
    dataset_details = models.ForeignKey(DataSetDetails, null=False, on_delete=CASCADE)
    flow_run = models.ForeignKey(FlowRun, on_delete=DO_NOTHING, null=True)
    storage_path = models.TextField(null=True)


class DataCollection(BaseModel):  # pragma: no cover

    name = models.CharField(max_length=MAX_VARCHAR_LENGTH, null=False)
    target = models.OneToOneField(DataSetDetails, on_delete=DO_NOTHING, null=False, related_name="target")
    related = models.OneToOneField(DataSetDetails, on_delete=DO_NOTHING, null=True, related_name="related")
    metadata = models.OneToOneField(DataSetDetails, on_delete=DO_NOTHING, null=True, related_name="metadata")
    flow_instance = models.OneToOneField(FlowInstance, on_delete=DO_NOTHING, null=False)


Get this bounty!!!

#StackBounty: #python-3.x #django #unit-testing #django-3.0 #factory-boy In FactoryBoy, how do I setup my factory with an empty many-to…

Bounty: 50

I’m using Django 3 with Python 3.8. I have the following model …

class Coop(models.Model):
    objects = CoopManager()
    name = models.CharField(max_length=250, null=False)
    types = models.ManyToManyField(CoopType, blank=False)
    addresses = models.ManyToManyField(Address)
    enabled = models.BooleanField(default=True, null=False)
    phone = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_phone')
    email = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_email')
    web_site = models.TextField()

I have created the following factory (using Factory boy) to attempt create the model in a test …

class CoopFactory(factory.DjangoModelFactory):
    """
        Define Coop Factory
    """
    class Meta:
        model = Coop

    name = "test model"
    enabled = True
    phone = factory.SubFactory(PhoneContactMethodFactory)
    email = factory.SubFactory(EmailContactMethodFactory)
    web_site = "http://www.hello.com"

    @factory.post_generation
    def addresses(self, create, extracted, **kwargs):
        if not create:
            # Simple build, do nothing.
            return

        if extracted:
            # A list of types were passed in, use them
            for address in extracted:
                self.addresses.add(address)
        else:
            address = AddressFactory()
            self.addresses.add( address )

    @factory.post_generation
    def types(self, create, extracted, **kwargs):
        if not create:
            # Simple build, do nothing.
            return

        if extracted:
            # A list of types were passed in, use them
            for type in extracted:
                self.types.add(type)
        else:
            print("Creating type ...n")
            type = CoopTypeFactory()
            self.types.add( type )

but I’m having trouble creating a factory with a many-to-many field (types) that is empty. I tried the below

@pytest.mark.django_db
def test_coop_create_with_no_types(self):
    """ Test customer model """    # create customer model instance
    coop = CoopFactory.create(types=[])
    print("size: ", coop.types.all().count())
    self.assertIsNotNone(coop)
    self.assertIsNotNone( coop.id )

but the value of types.all().count() is always equal to 1. How do I properly setup a factory with an empty many-to-many field?


Get this bounty!!!