Increment string in Matlab - string

i am using a video with a simple background and prompting an alert text whenever someone passes by.
clear all
myVideoObj = VideoReader('video.avi');
nFrames = myVideoObj.NumberOfFrames;
sound = wavread('somethingwrong.wav');
flag = 1;
% Read one frame at a time.
for i = 2 : nFrames-1
frame1 = read(myVideoObj, i-1); frame2 = read(myVideoObj, i);
diff = abs(rgb2gray(frame1) - rgb2gray(frame2));
if sum(sum(diff)) < 46000
imshow(frame2, [])
drawnow
else
imshow(frame2, [])
text(100, 100, 'Intruder!!!' , 'FontSize',24)
drawnow
end
end
The drawon works. But now im trying to figure out how to do an increment of strings for each person that passes by. How do i start? Thanks in advance

Are you trying to make it so the text increments a counter each time it detects an intruder (so this is included in the "Intruder!!!" message)? If so, you should be able to accomplish this as follows:
You can make a string variable and a counter:
message_string = 'Intruder #';
count = 1;
and then each time you find a new person, you would set a new message string:
total_message = strcat(message_string, num2str(count));
which would be sent to the text function:
text(100, 100, total_message, 'FontSize', 24)
then increment the count.
If this is not an answer to your question, please clarify what you mean by doing an increment of strings for each person that passes by.

Related

Merge every x element in multiple lists to return new list

I'm writing a script that scrapes all of the data from my works ticketing site and the end goal is to have it send a text when a new ticket enters the bucket with all of the important info of the ticket.
Python 3.10
So far, it pulls from a scattered list and combines all of the elements into an appropriate group ie. ticket numbers,titles and priorities.
tn = rawTickets[0::14]
title = rawTickets[5::14]
priority = rawTickets[9::14]
With this I can say
num = x
wholeticket = tn[num], title[num], priority[num],
print(wholeticket)
and get x ticket in the list
# Results: "tn0, title0, priority0"
I want it to print all of the available tickets in the list based on a range
totaltickets = 0
for lines in rawTickets:
if lines == '':
totaltickets += 1
numrange = range(totaltickets)
so lets say there are only 3 tickets in the queue,
I want it to print
tn0, title0, priority0,
tn1, title1, priority1,
tn2, title2, priority2,
But I want to avoid doing this;
ticket1 = tn[0], title[0], priority[0],
ticket2 = tn[1], title[1], priority[1],
ticket3 = tn[2], title[2], priority[2],
flowchart to help explain
You could use zip:
tickets = list(zip(rawTickets[0::14], rawTickets[5::14], rawTickets[9::14]))
This will give you a list of 3-tuples.
You could do something like that:
l1 = [*range(0,5)]
l2 = [*range(5,10)]
l3 = [*range(10,15)]
all_lst = [(l1[i], l2[i], l3[i]) for i in range(len(l1))]
Or you could use zip as trincot offered.
Note that on large scales, zip is much faster.

Cannot figure out why this code isn't looping a second time

This for loop is running once, but not running a second time.
I've put print() statements everywhere to confirm:
-round = 2, on the second pass.
-The loop comes up to the 'for' statement on the second pass, but the 'print' statement I put before "doChecks = True" didn't trigger.
-ClockCheck() is no factor; it fires perfectly first time, isn't called second time.
I've been up for ~20 hours and I figure I have to be missing something obvious. I'm going to sleep so I can re-attack fresh in the morning...hopefully it's obvious to someone else?
def scoreThisRound(answerKey, round):
global stopTime
global gameInProgress
userInput = [] #Initialize user input list
for i in range(round): #This is not starting a second loop!
doChecks = True
if clockCheck(): #If there is still time remaining
userInput.append(input(">")) #Get user input and add it to a list.
else:
print("ClockCheck Failed # ScorethisRound")
gameInProgress = False
doChecks = False
if doChecks == True:
for i in range(len(answerKey)):
if answerKey[i] == userInput[i]:
print("Good Answer!") #change this code to add time
stopTime += 1.5
else:
print("Bad Answer!") #change this code to subtract time
stopTime -= 3
Here is the output from the console:
Solved, and it was something obvious. My "if doChecks" statement was tabbed too far over; that's why it was running fine the first time (round = answers = user input), but second time the loop went (2 = 2 = 1), and threw the exception.
Lesson learned:
1) Sleep. It's important.
2) Need to get an IDE that shows tabs and spaces as something other than whitespace, which kinda blends together for me.
Thanks!

How do I store the value of an indexed list in a global variable and call at it through a formatted function?

How do I store the value of an index and then use that value in a formatted exec function to print me the second results of each list under class Animal(): Dog list, which is what I expect to print. A simplified version of the essence of my problem along with further clarification below:
class Global():
str_list = []
current_word = ""
adj_word = 'poofy'
adj_int = 0
size = 0
pounds = 0
dog_years = 0
class Animal():
##### Formatted like so:[[visual size],[pounds],[age in dog years],[almost dead]] #####
dog = [['small', 'poofy'],[7, 45],[18, 101],[0, 1]]
input = 'dog'
def done():
print(Global.adj_int)
print(str(Global.size), str(Global.pounds), str(Global.dog_years))
def split_str():
Global.str_list = input.split()
split_str()
def analyze():
Global.current_word = Global.str_list.pop(0)
exec(f"""if Global.adj_word in Animal.{Global.current_word}[0]:
Global.adj_int = Animal.{Global.current_word}[0].index('{Global.adj_word}')
Global.size = Animal.{Global.current_word}[1][{Global.adj_int}]
Global.pounds = Animal.{Global.current_word}[2][{Global.adj_int}]
Global.dog_years = Animal.{Global.current_word}[3][{Global.adj_int}]""")
if len(Global.str_list) == 0:
done()
analyze()
it returns:
1
7 18 0
When I expect it to return "45 101 1" for size, pounds, dog_years because I am storing the .index value of 'poofy' for Animal.dog list in Global.adj_int. which in this case is '1'. Then I try to format the code so it uses that value to print the second values of each list but for some reason it will not print the expected results(under def analyze():... exec(f""".... Does anyone have an answer to this question?? This is a much more simple version of what I originally have but produces the exact same result. when I try to use the formatted code it acts as if adj_int = 0 when really it's adj_int = 1 (and I know it is stored as 1 like it should be because I print adj_int at the end to check) or I am not able to format the code in this way? But I need a work around regardless.
The problem is that the string argument to exec is being evaluated before it is executed. So, when you are calling exec this is what is called:
exec(f"""if Global.adj_word in Animal.dog[0]:
Global.adj_int = Animal.{dog}[0].index('poofy')
Global.size = Animal.dog[1][0]
Global.pounds = Animal.dog[2][0]
Global.dog_years = Animal.dog[3][0]""")
And after this, Global.adj_int becomes 1. The control flow and the structure of your code is incredibly complex comparing to its simplicity so I would carefully rethink its design, but for a quick fix, you probably want to first execute the part that sets the adj_int and then the rest, like this:
exec(f"""if Global.adj_word in Animal.{Global.current_word}[0]:
Global.adj_int = Animal.{Global.current_word}[0].index('{Global.adj_word}'"""))
exec(f"""if Global.adj_word in Animal.{Global.current_word}[0]:
Global.size = Animal.{Global.current_word}[1][{Global.adj_int}]
Global.pounds = Animal.{Global.current_word}[2][{Global.adj_int}]
Global.dog_years = Animal.{Global.current_word}[3][{Global.adj_int}]""")
Even after stating that your program is unnecessarily complex, let me additionally point out that using a global, mutable state is a really really bad practice, which makes your programs hard to follow, maintain & debug. The same concern relates to using exec.

Bad output when building a histogram

I am having some issues building a histogram.
Here is my code:
distribution = dict()
count = 0
name = input("Enter file:")
handle = open(name)
for line in handle:
line = line.rstrip()
if not line.startswith("From "):
continue
count = count + 1
firstSplit = line.split() # This gets me the line of text
time = firstSplit[5] # This gets me time - ex: 09:11:38
# print(firstSplit[5])
timeSplit = time.split(':')
hr = timeSplit[1] # This gets me hrs - ex: 09
# Gets me the histogram
if hr not in distribution:
distribution[hr[1]] = 1
else:
distribution[hr[1]] = distribution[hr[1]] + 1
print(distribution)
# print(firstSplit[5])
I read the text in, and I split it to get the lines, done by firstSplit. This line of text includes a time stamp. I do a second split to get the time, done by timeSplit.
From here, I try to build the histogram by trying to see if the hour is in the dictionary, if it is, add one, if not, add the hour. But this is where it goes wrong. My output looks like:
Example of Output
Any advise or suggestions would be great!
Seán
You are using an incorrect method to check if the hour is a key in the histogram. Here is the correct way to check:
if not (hr in list(distribution.keys()):
Also, you should be checking if a value is a key, then using the same value as the key that you create / add to. Therefore, the above will now be:
if not (hr[1] in list(distribution.keys()):
These two changes should fix your code and build you a great histogram!
Note: Code is untested

Get user input to declare a global variable (int and string) python

I am making a life counter for MTG I would like to ask the user for the life total and their name. Then use both in the program. I have a running and functional program that uses declared values for the healt count for player 1 and 2 and label and text for the players
p1hc = 20
p2hc = 20
I tested setting the values with the "input" function and printing the numbers in a different window to make sure
p1healthc = input (' What is the starting life count? ')
p2healthc = input (' What is the starting life count? ')
print (p1healthc)
print (p1healthc)
When I added the code to my running and working program with
### Declare global health count values for player 1 and player 2 variables
p1healthc = input (' What is the starting life count? ')
p2healthc = input (' What is the starting life count? ')
p1hc = p1healthc
p2hc = p2healthc
It would ask for the and set the values in the SHELL window and not start the program window after.

Resources