I want to remove the end of a midi file in order to have a file of 30 seconds for example.
I tried to compute on each track the total time value and to delete messages each time it is over 30 seconds. However, when I listen to it, it is still the same duration, the only difference is that there is a gap without sound in the middle of the file.
Does any one have an idea of how I can do it ?
Thank you!
Most likely, you forgot to remove some MetaMessages.
Try this:
import mido
midifile = mido.MidiFile('old.mid')
lasttick = # last tick you want to keep
for track in midifile.tracks:
tick = 0
keep = []
for msg in track:
if tick > lasttick:
break
keep.append(msg)
tick += msg.time
track.clear()
track.extend(keep)
midifile.save('new.mid')
Related
import datetime
data = {'13:55':0,'13:56':1,'13:57':2, '13:58':3}
while True:
timee = datetime.datetime.now()
time = timee.strftime("%H:%M")
while time not in data:
timee = datetime.datetime.now()
time = timee.strftime("%H:%M")
if time in data:
print('Done')
print(data[time])
From the given code, I always get an output in case of the first or the last object in the dictionary, for example, if the current time is 13:55, I want it to display the output 'done', similarly if the time is 13:56, I want the same output and so on. Also, I don't want to break the loop since I want my program to run continuously. But it only gives me an output in case of 13:55 or 13:58 or it wouldn't even give me an output.
Whereas what I want is basically, I want it to give me an output every time the time is present in the dictionary. Please help me.
(I'm really sorry if you don't get it, I've tried my best to put this forward).
If any questions please let me know.
Thank you in advance.
an illustration of my comment; at the moment, both your while loops do the same thing; you can simplify to
import datetime
import time
data = {'13:51':0,'13:52':1,'13:53':2, '13:54':3,
'found':[]}
while True:
t = datetime.datetime.now().strftime("%H:%M")
if (t in data) & (t not in data['found']):
print(f'Done, found time {t} in data\n value: {data[t]}')
data['found'].append(t)
time.sleep(1)
I've added a little helper key to track which times were found.
I'm running a python script that will display messages on a board. One of the subroutines that I've created is supposed to grab a random line from a small text file, and display that line. It mostly works, except after looping a few times, it gets stuck on the same number, and just displays the same thing over and over.
I am running this in Python 2.7, on a Raspberry Pi in Raspbian. I am using this github as the base for the project, and added lines of my own to it:
https://github.com/CalebKussmaul/Stranger-Things-Integrated
This is part of a halloween display that will be Stranger Things-themed, so the preloaded messages have a reference to the show. I noticed this issue the other day, and have been pouring over the internet to try and figure out what the problem could be. I've tried doing different methods of selecting a randomized number, including some in some similar (but different) threads on this site. All of them produce exactly the same issue.
Below is the subroutine I created:
def preloaded_messages():
print "Preloaded Messages thread is loaded."
global displaying
while True:
if not displaying:
with open('preloaded_messages.txt') as f:
lines = len(f.readlines())
rgn = random.randint(1,lines)
msg = linecache.getline('preloaded_messages.txt', rgn)
print "rng: ", rgn
print "total lines: ", lines
print "line: ", msg
print "displaying from preloaded_messages.txt: ", msg
display(msg)
time.sleep(10)
And here's my preloaded_messages.txt file:
help me
im trapped in the upside down
leggo my eggo
friends dont lie
run /!
hopper is alive
rip barb
demogorgon is coming /!
mouthbreather
When I run it, my output is like this:
rng: 6
total lines: 9
line: hopper is alive
rng: 2
total lines: 9
line: im trapped in the upside down
rng: 9
total lines: 9
line: mouthbreather
...
rng: 9
total lines: 9
line: mouthbreather
the first few times are always random (and the number of times it successfully randomizes varies), but when it gets on 9, it just stays there for as long as I let it run. I am at a loss as to why it works the first few times, but not once it gets to 9.
EDIT: Interestingly, as I've been writing this, I also tried adding a blank line at the end, and while it looked like it'd be stuck again, as it did that one three times in a row, then it finally moved to others. I'm not sure how that changes things. And ideally, I'd rather not have the blank line in there, as it eats up time displaying nothing. So it'd be nice to fix the issue. Anyone have any ideas?
It is reseeding the random generator. See line 49 of stranger.py in the https://github.com/CalebKussmaul/Stranger-Things-Integrated: random.seed(i).
The color_of function should be written as:
def color_of(i):
"""
This function generates a color based on the index of an LED. This will always return the same color for a given
index. This allows the lights to function more like normal christmas lights where the color of one bulb wont change.
:param i: index of LED to get color of
:return: a pseudorandom color based on the index of the light
"""
_random = random.Random(i)
rgb = colorsys.hsv_to_rgb(_random.random(), 1, 1)
return int(rgb[0] * 255), int(rgb[1] * 255), int(rgb[2] * 255)
To create its own Random instance with the given seed rather than reseeding the Random instance that is a singleton in the random module.
This appears to work for me. Note that I'm seeding the RNG.
import time
import random
from datetime import datetime
def preloaded_messages():
print("Preloaded Messages thread is loaded.")
displaying = False
while True:
if not displaying:
with open('preloaded_messages.txt') as f:
random.seed(datetime.utcnow())
text = f.read().splitlines()
msg = random.choice(text)
print("line: ", msg)
# print("displaying from preloaded_messages.txt: ", msg)
time.sleep(10)
if __name__ == "__main__":
preloaded_messages()
Goal: I would like to see how many times python is able to print something per 1 second.
For educational purposes I'm trying to make a script that shows how many times per every second a random module will appear in a loop. How to do it in a fastest pythonic way?
At first, to count seconds I wrote this code:
import time
sec = 0
while True:
print(sec)
time.sleep(1)
sec += 1
But this one seems slower than a real seconds.
So I decided to use local seconds. Also, before continue my script I wanted to count how many times python will print 'you fool' manually, so I wrote following code:
import time
def LocalSeconds():
local_seconds = time.gmtime()[5:-3]
local_seconds = int(local_seconds[0])
return local_seconds
while True:
print(LocalSeconds(), 'you fool')
Output:
first second - 14 times per second;
next second - 13 times;
next second - 12 times, etc. Why it goes slower?
Where I end / stuck right now:
import time, random
def RandomNumbers():
return random.randint(3,100)
def LocalSeconds():
local_seconds = time.gmtime()[5:-3]
local_seconds = int(local_seconds[0])
return local_seconds
def LocalSecondsWithPing():
local_seconds_ping = time.gmtime()[5:-3]
local_seconds_ping = int(local_seconds[0:1])
return local_seconds_ping
record_seconds = []
record_seconds_with_ping = []
while True:
record_seconds.append(LocalSeconds())
record_seconds_with_ping.append(LocalSecondsWithPing())
if record_seconds == record_seconds_with_ping:
RandomNumbers()
del record_seconds_with_ping[0]
del record_seconds[-1]
Also, I guess I need to use "for" loop, not "while"? How to do this script?
Counting a single second won't give you a good result. The number of prints in a single second may vary depending on things like other threads currently running on your system (for the OS or other programs) and may be influenced by other unknown factor.
Consider the followind code:
import calendar
import time
NumOfSeconds=100 #Number of seconds we average over
msg='Display this message' #Message to be displayed
count=0 #Number of time message will end up being displayed
#Time since the epoch in seconds + time of seconds in which we count
EndTime=calendar.timegm(time.gmtime()) + NumOfSeconds
while calendar.timegm(time.gmtime())<EndTime: #While we are not at the end point yet
print(msg) #Print message
count=count+1 #Count message printed
print(float(count)/NumOfSeconds) #Average number of prints per second
Here calendar.timegm(time.gmtime()) gives us the time in seconds since the epoch (if you don't know what that is, read this. But basically it's just a fixed point in time most computer system now days use as a reference point.
So we set the EndTime to that point + the number of seconds we want to average over. Then, in a loop, we print the message we want to test and count the number of times we do that, between every iteration checking that we are not past the end time.
Finally we print the average number of times per seconds that we printed the message. This helps with the fact that we may end up start counting near the end of a whole second since the epoch, in which case we won't actually have a whole second to print messages, but just a fraction of that. If we make sure NumOfSeconds is large enough, that error addition will be small (for example, for NumOfSeconds=100 that error is ~1%).
We should note that the actual number would also depend on the fact that we are constantly testing the current time and counting the number of prints, however, while I haven't tested that here, it is usually the case that printing to the screen takes significantly longer time than those operations.
I try to use 'IF' in python in order to achieve the algorithm that can automatically ajust the value of a parameter in 'IF' according to some stock trasactions.
if self.sellcount==0 and int(time.time())-self.programstarttime>600:
if cur_sum/total_sum>0.15:
Other Code
else:
if cur_sum/total_sum>0.35:
Other Code
I try to achieve that if my algorithm do not sell any stock for 10 minutes, the algorithm can automatically change the condition from 0.35 to 0.15. However, the code above will change from 0.15 to 0.35 after selling stocks for one time. I want the code to keep 0.15 after selling stocks for one time.
I'd like to start with a disclaimer to be careful, stock trading is not this easy and you can lose a lot of money with a simple algorithm (just as you can with a complex one)
However, this is also a nice example to understand how to deal with running a program over time in Python and understanding conditional logic.
There are a few basic constructs you'll want to know for this. The first concept is that to keep track of time constantly in your program, you likely want to put your code in an infinite loop. That will keep your programming doing what you want until you are done. This can be done like this:
while True:
Now that you have this setup, we just need to keep track of time. This can be done easily by setting a variable and incrementing it by how long you wait between iterations. However, we still need to track time. Python has a nice sleep function implemented in the time module. This function causes your program to pause for a number of seconds that you desire and then resume going through the rest of your code.
from time import sleep
last_sold_stock_time = 0
wait_time = 1
while True:
# <Condition Code goes here>
# This is in seconds
sleep(wait_time)
# Keep track of how much time has passed.
last_sold_stock_time += wait_time
Now, you just need to change your condition value based on the time. The full code will probably end up looking something like this:
from time import sleep
# The number of seconds since last bought a stock, assumes start is 0
last_sold_stock_time = 0
# This is in seconds
wait_time = 1
# ten minutes in seconds
ten_minutes = 600
while True:
# Figure out these values however you do
cur_sum = 0
total_sum = 1
if last_sold_stock_time <= ten_minutes:
condition_value = 0.35
else:
condition_value = 0.15
if cur_sum/total_sum > condition_value:
# Do something
pass
sleep(wait_time)
last_sold_stock_time += wait_time
In my experiment I'm showing a random generated stimulus 'x', which I need to compare to a key that's been giving in by the user of the experiment.
Basically, I have two lists:
one with the stimuli
and one with the correct answers (the keys they should give)
The order is the same, by which I mean that stimulus 1 should get the key that's at 'place 1' in the list with answers.
I've searched several topics on how to compare these two lists but so far it hasn't been working.
These are the options I've tried:
Answerruning = True
while Answerrunning:
if event.getKeys(keyList):
ReactionTime.getTime()
Keys = event.waitKeys()
for givenKey in Keys:
if givenKey == keyList:
answer_stimulus = 2
Answerrunning = False
window.flip(clearBuffer = True)
else:
answer_stimulus = 0
And this option but I think the other one is better:
keyList = []
givenKey = event.getKeys(keyList)
Answerrunning = True
while Answerrunning:
for x in stimulus:
if givenKey in keyList:
ReactionTime.getTime()
answer_stimulus = 2
Answerrunning = False
window.flip(clearBuffer = True)
else:
answer_stimulus = 0
I hope one of you can give me a hint on the problem how to compare those two en from there on my window will clear en the experiment can go on.
You don't mention this, but you really need to be using a TrialHandler object http://www.psychopy.org/api/data.html which will handle the variables for you, stepping through your conditions file (.xlsx or .csv) a row at a time for each trial. i.e. don't put the stimulus and correct response values in lists: put them in an external file, and let PsychoPy do the housekeeping of managing them trial by trial.
If you have a column in that file called correctResponse, another called stimulusText, and a TrialHandler called trials, then some pseudo-code would look like this:
trialClock = core.Clock() # just create this once, & reset as needed
# trials is a TrialHandler object, constructed by linking to an
# external file giving the details for each trial:
for trial in trials:
# update the stimulus for this trial.
# the stimulusText variable is automatically populated
# from the corresponding column in your conditions file:
yourTextStimulus.setText(stimulusText)
# start the next trial:
trialClock.reset()
answerGiven = False
while not answerGiven:
# refresh the stimuli and flip the window
stimulus_1.draw() # and whatever other stimuli you have
win.flip() # code pauses here until the screen is drawn
# i.e. meaning we are checking for a keypress at say, 60 Hz
response = event.getKeys() # returns a list
if len(response) > 0: # if so, there was a response
reactionTime = trialClock.getTime()
# was it correct?
if correctResponse in response:
answer = True
else:
answer = False
# store some data
trials.addData('Keypress', response)
trials.addData('KeypressRT', reactionTime)
trials.addData('KeypressCorrect', answer)
# can now move on to next trial
answerGiven = True
PsychoPy code is generally constructed around a cycle of drawing to the screen on every refresh, so the code above shows how within each trial, the stimulus is updated once but redrawn to the screen on every refresh. In this cycle, the keyboard is also checked once every time the screen is redrawn.
In your code, you are mixing getKeys(), which checks the instantaneous state of the keyboard, and waitKeys(), which pauses until a response is given (and hence breaks the screen refresh cycle). So gerenally avoid the latter. Also, when you use getKeys(), you have to assign the result to a variable, as this function clears the buffer. Above, you use getKeys() and then follow up by checking the keyboard again. In that case, the initial response will have disappeared, as it wasn't stored.
Clear as mud?