Python compare current date to a specific date - python

So basically I have this python kodi which I'm running on Kodi since it's a Kodi addon.
import time
def checkPassword(path, lock=None):
expdate = "10/07/15"
datenow = time.strftime("%x")
if datenow == expdate:
return 'ERROR'
if not lock:
folderConfig = os.path.join(path, FOLDERCFG)
lock = getParam('LOCK', folderConfig)
title = GETTEXT(30069) % path.rsplit(os.sep, 1)[-1]
unlock = getText(title, hidden=True)
if not unlock:
return ''
md5 = utils.generateMD5(unlock)
match = md5 == lock
if not match:
return 'ERROR'
return md5
Basically I have a favourites folder which is locked with password, I want to show an error if the account is expired. I can preset the date from the addon myself like I did in the example, but somehow my addon is giving me an error with this code. Can you tell me what I have wrong? The problem is somewhere in the first 6 lines, since when I remove it, it works, but obviously without the date check.

Related

Python Boto3 SnapshotNotFound exception. Unable to delete snapshot

I'm new to AWS and I have written a Boto3 script which gets the snapshots by OwnerId and delete older snapshots one by one. I'm having a strange issue that boto client finds all Snapshots and when it reaches client.delete_snapshot(SnapshotId=snapshot.snapshot_id) It throws SnapshotNotFoundException - Unable to delete snapshot with id abcd.
It's weird that when i go to AWS Console and search for the ID, Snapshot is there and I can delete it from the AWS Console and I'm using the same account credentials with Boto3 config file.
[default]
aws_access_key_id=foo
aws_secret_access_key=bar
Here is what i have tried.
Boto3 Script
from datetime import datetime, timedelta, timezone
import boto3
ec2 = boto3.resource('ec2')
cl = boto3.client('ec2')
count=0
snapshots = ec2.snapshots.filter(OwnerIds=['xxxxxxxxxx'])
def if_associated_to_ami(client, snapshot_id):
img = client.describe_images(Filters=[{'Name': 'block-device-mapping.snapshot-id', 'Values': [snapshot_id]}])
try:
ami_id = img['Images'][0]['ImageId']
#print("Snapshot(" + snapshot_id + ") is associated to image(" + ami_id + "). Return True")
return True
except IndexError:
#print("Snapshot(" + snapshot_id + ") is not associated to any image. Return False")
return False
for snapshot in snapshots:
if if_associated_to_ami(cl, snapshot.snapshot_id):
print('Unabble to delete Snapshot with Id = {}. Snapshot is in used! '. format(snapshot.snapshot_id))
else:
start_time = snapshot.start_time
delete_time = datetime.now(tz=timezone.utc) - timedelta(days=90)
if delete_time > start_time:
#snapshot.delete()
cl.delete_snapshot(SnapshotId=snapshot.snapshot_id)
print('Snapshot with Id = {} is deleted '. format(snapshot.snapshot_id))
count+=1
if count == 1000:
break
if you face indentation issues, please check the file here.
https://github.com/DeveloperMujtaba/usual-resources/blob/master/boto3.py
can someone please indicate the issue please? It would be much appreciated. Thanks.
Honestly, just by looking at your code, I cannot tell why it bulks at that but also, b/c you already have the snapshot resource, why not just do:
snapshot.delete()

Repeat command in while loop or similar until not existing result is found

i need to repeat a cmd which always generated a new random string, after that i need to make sure that this specific string has not been generated before. I never did while loops before and im not able to figure out how to repate the cmd until a result has been found which is not already part of the database. I can't be to specific as this source is closed
all this is packed into a celery task
tasks.py
#app.task
def allocate_new_string(user_pk):
user = User.objects.get(pk=user_pk)
new_string = subprocess.Popen("$get_new_string_cmd", shell=True, stdout=subprocess.PIPE).communicate()[
0].decode('utf-8').strip()
try:
while True:
if Used_String.objects.filter(string=new_string, atom=0).exists():
new_string << how to repeat the command from above here until a new random string has been found?
else:
used_string = Used_String.objects.create(user=user, string=new_string, atom=0)
used_string.save()
logger.info(str("New String has been set)
except:
logger.info(str("Something went wrong while processing the task"))
The function i want to have here is: Search for a none existing sting until one has found that has never been generated before or is at least not part of the database.
the cmd im using isn't openSSL or something like that and it's quite likly that i hit two times the same random generated string.
Thanks in advance
Slight change.
#app.task
def allocate_new_string(user_pk):
user = User.objects.get(pk=user_pk)
try:
Found = True
while Found:
new_string = subprocess.Popen("$get_new_string_cmd", shell=True, stdout=subprocess.PIPE).communicate()[
0].decode('utf-8').strip()
if Used_String.objects.filter(string=new_string, atom=0).exists():
Found = True
else:
used_string = Used_String.objects.create(user=user, string=new_string, atom=0)
used_string.save()
logger.info(str("New String has been set"))
Found = False
except:
logger.info(str("Something went wrong while processing the task"))
I have not tested it but should work. Please try it out and let me know.

How do I run python '__main__' program file from bash prompt in Windows10?

I am trying to run a python3 program file and am getting some unexpected behaviors.
I'll start off first with my PATH and env setup configuration. When I run:
which Python
I get:
/c/Program Files/Python36/python
From there, I cd into the directory where my python program is located to prepare to run the program.
Roughly speaking this is how my python program is set up:
import modulesNeeded
print('1st debug statement to show program execution')
# variables declared as needed
def aFunctionNeeded():
print('2nd debug statement to show fxn exe, never prints')
... function logic...
if __name__ == '__main__':
aFunctionNeeded() # Never gets called
Here is a link to the repository with the code I am working with in case you would like more details as to the implementation. Keep in mind that API keys are not published, but API keys are in local file correctly:
https://github.com/lopezdp/API.Mashups
My question revolves around why my 1st debug statements inside the files are printing to the terminal, but not the 2nd debug statements inside the functions?
This is happening in both of the findRestaurant.py file and the geocode.py file.
I know I have written my if __name__ == '__main__': program entry point correctly as this is the same exact way I have done it for other programs, but in this case I may be missing something that I am not noticing.
If this is my output when I run my program in my bash terminal:
$ python findRestaurant.py
inside geo
inside find
then, why does it appear that my aFunctionNeeded() method shown in my pseudo code is not being called from the main?
Why do both programs seem to fail immediately after the first debug statements are printed to the terminal?
findRestaurant.py File that can also be found in link above
from geocode import getGeocodeLocation
import json
import httplib2
import sys
import codecs
print('inside find')
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
sys.stderr = codecs.getwriter('utf8')(sys.stderr)
foursquare_client_id = "..."
foursquare_client_secret = "..."
def findARestaurant(mealType,location):
print('inside findFxn')
#1. Use getGeocodeLocation to get the latitude and longitude coordinates of the location string.
latitude, longitude = getGeocodeLocation(location)
#2. Use foursquare API to find a nearby restaurant with the latitude, longitude, and mealType strings.
#HINT: format for url will be something like https://api.foursquare.com/v2/venues/search?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&v=20130815&ll=40.7,-74&query=sushi
url = ('https://api.foursquare.com/v2/venues/search?client_id=%s&client_secret=%s&v=20130815&ll=%s,%s&query=%s' % (foursquare_client_id, foursquare_client_secret,latitude,longitude,mealType))
h = httplib2.Http()
result = json.loads(h.request(url,'GET')[1])
if result['response']['venues']:
#3. Grab the first restaurant
restaurant = result['response']['venues'][0]
venue_id = restaurant['id']
restaurant_name = restaurant['name']
restaurant_address = restaurant['location']['formattedAddress']
address = ""
for i in restaurant_address:
address += i + " "
restaurant_address = address
#4. Get a 300x300 picture of the restaurant using the venue_id (you can change this by altering the 300x300 value in the URL or replacing it with 'orginal' to get the original picture
url = ('https://api.foursquare.com/v2/venues/%s/photos?client_id=%s&v=20150603&client_secret=%s' % ((venue_id,foursquare_client_id,foursquare_client_secret)))
result = json.loads(h.request(url, 'GET')[1])
#5. Grab the first image
if result['response']['photos']['items']:
firstpic = result['response']['photos']['items'][0]
prefix = firstpic['prefix']
suffix = firstpic['suffix']
imageURL = prefix + "300x300" + suffix
else:
#6. if no image available, insert default image url
imageURL = "http://pixabay.com/get/8926af5eb597ca51ca4c/1433440765/cheeseburger-34314_1280.png?direct"
#7. return a dictionary containing the restaurant name, address, and image url
restaurantInfo = {'name':restaurant_name, 'address':restaurant_address, 'image':imageURL}
print ("Restaurant Name: %s" % restaurantInfo['name'])
print ("Restaurant Address: %s" % restaurantInfo['address'])
print ("Image: %s \n" % restaurantInfo['image'])
return restaurantInfo
else:
print ("No Restaurants Found for %s" % location)
return "No Restaurants Found"
if __name__ == '__main__':
findARestaurant("Pizza", "Tokyo, Japan")
geocode.py File that can also be found in link above
import httplib2
import json
print('inside geo')
def getGeocodeLocation(inputString):
print('inside of geoFxn')
# Use Google Maps to convert a location into Latitute/Longitute coordinates
# FORMAT: https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=API_KEY
google_api_key = "..."
locationString = inputString.replace(" ", "+")
url = ('https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=%s' % (locationString, google_api_key))
h = httplib2.Http()
result = json.loads(h.request(url,'GET')[1])
latitude = result['results'][0]['geometry']['location']['lat']
longitude = result['results'][0]['geometry']['location']['lng']
return (latitude,longitude)
The reason you're not seeing the output of the later parts of your code is that you've rebound the standard output and error streams with these lines:
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
sys.stderr = codecs.getwriter('utf8')(sys.stderr)
I'm not exactly sure why those lines are breaking things for you, perhaps your console does not expect utf8 encoded output... But because they don't work as intended, you're not seeing anything from the rest of your code, including error messages, since you rebound the stderr stream along with the stdout stream.

Syncronizing files with AJA Ki Pro using Python

We have an AJA Ki Pro recorder at another location and I a need to created an automated system that pulls the recorded files over to my editing studio. So far I have successfully been able to pull recordings using a python script run via an Applescript through Automator. I than can trigger the application from iCal. Basically my script involves setting the "MediaState" parameter on my recorder to "Data" (value=1) so I can pull files, comparing the files on the recorder to my local files (it only downloads what I dont already have locally), and then setting the "MediaState" property back to "Rec" (value=0) so the recorder is ready to go again.
Here are the 2 problems I have been unable to resolve so far. Bear with me, I have about 2 days worth of experience with Python :) It seems that I have somehow created a loop where it constantly says "Looking for new clips" and "No new clips found". Ideally I would like to have the script terminate if no new clips are found. I would also like to set this up so that when it finishes a download through cURL, it automatically sets my "MediaState" back to value=0 and ends the script. Here is my code so far:
# This script polls the unit downloads any new clips it hasn't already downloaded to the current directory
# Arguments: hostname or IP address of Ki Pro unit
import urllib, sys, string, os, posix, time
def is_download_allowed(address):
f = urllib.urlopen("http://"+address+"/config?action=get&paramid=eParamID_MediaState")
response = f.read()
if (response.find('"value":"1"') > -1):
return True
f = urllib.urlopen("http://"+address+"/config?action=set&paramid=eParamID_MediaState&value=1")
def download_clip(clip):
url = "http://" + address + "/media/" + clip
print url
posix.system("curl --output " + clip + " " + url);
def download_clips(response):
values = response.split(":")
i = 0
for word in values:
i += 1
if(word.find('clipname') > -1):
clip = values[i].split(',')[0].translate(string.maketrans("",""), '[]{} \,\"\" ')
if not os.path.exists(clip):
print "Downloading clip: " + clip
download_clip(clip)
else:
f = urllib.urlopen("http://"+address+"/config?action=set&paramid=eParamID_MediaState&value=0")
print "No new clips found"
address = sys.argv[1]
while 1:
if (is_download_allowed(address)):
print "Looking for new clips"
f = urllib.urlopen("http://"+address+"/clips")
response = f.read()
download_clips(response)
If the download_clips function is looping through the clip names, why you need that infinite while 1 loop? I think it is not necessary. Just remove it and dedent the block.

How can I set or modify the commit message from a mercurial extension?

I'm trying to modify this Mercurial extension to prompt the user to add a FogBugz case number to their commit message. Ideally, I'd like the user to just type in a number after being prompted and have it automatically appended to the commit message.
Here's what I've got so far:
def pretxncommit(ui, repo, **kwargs):
tip = repo.changectx(repo.changelog.tip())
if not RE_CASE.search(tip.description()) and len(tip.parents()) < 2:
casenumResponse = ui.prompt('*** Please specify a case number, x to abort, or hit enter to ignore:', '')
casenum = RE_CASENUM.search(casenumResponse)
if casenum:
# this doesn't work!
# tip.description(tip.description() + ' (Case ' + casenum.group(0) + ')')
return True
elif (casenumResponse == 'x'):
ui.warn('*** User aborted\n')
return True
return True
return False
What I haven't been able to find is a way to edit the commit message. tip.description appears to be readonly, and I haven't seen anything in the documentation or examples that would let me modify it. The only references I've seen to editing commit messages have to do with patches and the Mq extension, and it doesn't seem like that can help here.
Any ideas as to how I could set the commit message?
I didn't end up finding a way using a hook, but I was able to do it using extensions.wrapcommand and modifying the options.
I've included the source of the resulting extension here.
Upon detecting the lack of a case in the commit message, my version prompts the user to either enter one, ignore the warning, or abort the commit.
If the user responds to the prompt by specifying a case number, it is appended to the existing commit message.
If the user responds with 'x', the commit is aborted and the changes remain outstanding.
If the user response by just hitting enter, the commit proceeds with the original caseless commit message.
I've also added the nofb option, which skips the prompt if a user is purposefully making a commit with no case number.
Here is the extension:
"""fogbugzreminder
Reminds the user to include a FogBugz case reference in their commit message if none is specified
"""
from mercurial import commands, extensions
import re
RE_CASE = re.compile(r'(case):?\s*\d+', re.IGNORECASE)
RE_CASENUM = re.compile(r'\d+', re.IGNORECASE)
def commit(originalcommit, ui, repo, **opts):
haschange = False
for changetype in repo.status():
if len(changetype) > 0:
haschange = True
if not haschange and ui.config('ui', 'commitsubrepos', default=True):
ctx = repo['.']
for subpath in sorted(ctx.substate):
subrepo = ctx.sub(subpath)
if subrepo.dirty(): haschange = True
if haschange and not opts["nofb"] and not RE_CASE.search(opts["message"]):
casenumResponse = ui.prompt('*** Please specify a case number, x to abort, or hit enter to ignore:', '')
casenum = RE_CASENUM.search(casenumResponse)
if casenum:
opts["message"] += ' (Case ' + casenum.group(0) + ')'
print '*** Continuing with updated commit message: ' + opts["message"]
elif (casenumResponse == 'x'):
ui.warn('*** User aborted\n')
return False
return originalcommit(ui, repo, **opts)
def uisetup(ui):
entry = extensions.wrapcommand(commands.table, "commit", commit)
entry[1].append(('', 'nofb', None, ('suppress the fogbugzreminder warning if no case number is present in the commit message')))
To use this extension, copy the source into a file named fogbugzreminder.py. Then in your Mercurial.ini file (or hgrc, whatever your preference is), add the following line to the [extensions] section:
fogbugzreminder=[path to the fogbugzreminder.py file]
You can't modify a commit message without modifying the changeset.
I would suggest looking into a precommit hook that denies committing if a bugid is left out.

Categories

Resources