blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 616 | content_id stringlengths 40 40 | detected_licenses listlengths 0 69 | license_type stringclasses 2 values | repo_name stringlengths 5 118 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 63 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 2.91k 686M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 220 values | src_encoding stringclasses 30 values | language stringclasses 1 value | is_vendor bool 2 classes | is_generated bool 2 classes | length_bytes int64 2 10.3M | extension stringclasses 257 values | content stringlengths 2 10.3M | authors listlengths 1 1 | author_id stringlengths 0 212 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a92346d06c6d1e8ea8bb79fb93940843a809259a | 312487674db6ed02749236f192bbd14178a023ce | /.~c9_invoke_jsEp6f.py | 1b2d1fc62dfbb29ff595700284db2a674c7d9da0 | [] | no_license | charbelmarche33/WeatherWebApp | 013723f77bf2e0e79579c62d8090a57d3db5ef86 | 53eb2e741f6786fd2498f41d41f66080d36535fc | refs/heads/master | 2022-06-23T13:11:34.090932 | 2020-11-24T20:35:24 | 2020-11-24T20:35:24 | 123,991,076 | 1 | 0 | null | 2022-06-21T21:17:25 | 2018-03-05T23:13:47 | Python | UTF-8 | Python | false | false | 40,904 | py | import os, time, os.path, psycopg2, psycopg2.extras, requests
from flask import Flask, render_template, request, session, redirect, url_for
#Need this for calendar widget
import datetime
#Need these lines so drop down by location will work
import sys
#Need for json.loads
import json, ast
#Need for getting rid of special characters in location output
import re
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt # Do not do this prior to calling use()
import matplotlib.pyplot as plt1
import matplotlib.pyplot as plt2
import matplotlib.pyplot as plt3
import matplotlib.pyplot as plt4
import numpy as np
import Image
reload(sys)
sys.setdefaultencoding('utf8')
#Need these lines so drop down by location will work
app = Flask(__name__)
app.secret_key = os.urandom(24).encode('hex')
application = app
password = False
key = "447f7d449acdbcbda631c51d6b696ebc"
def connectToDB():
connectionString = 'dbname=world user=weatherapp password=password1 host=localhost'
try:
return psycopg2.connect(connectionString)
except:
print("Cannot connect to DB")
@application.route('/signout', methods=['GET', 'POST'])
def logout():
#This is a dummy function that the link that logs users out refers to. No page is loaded here
#All that happens is the user is logged out and gets redirected to the main page.
session['username'] = ''
return redirect(url_for('mainIndex'))
@application.route('/', methods=['GET', 'POST'])
def mainIndex():
#If the user name hasn't been created yet then set to '' otherwise someone is logged in dont
#The try will break and make you go to the except where you set username to ''
try:
print('User: ' + session['username'])
except:
#Session ensures that the logged in status remains across tabs and clicks. It is a variable stored in the cache of the browser being used!
#ALSO NOTE that username is used in the index file as a way to tell if anyone is logged in!
session['username'] = ''
#Starts off true, even tho noone is logged in so that when they view the log in pop up
#they don't see an error message
validSignUpCredentials = True
validLogInCredentials = True
validDate = True
validLocation = True
isZip = True
years = np.arange(0,10,5)
weekdayName = ""
totalDates = ""
totalDates1 = ""
totalDates2 = ""
totalDates3 = ""
totalDates4 = ""
now = datetime.datetime.now()
todaysDate = now.strftime("%Y-%m-%d")
TodaysDate = time.mktime(datetime.datetime.strptime(todaysDate, "%Y-%m-%d").timetuple())
conn = connectToDB()
curr = conn.cursor()
lowTemp = ""
highTemp = ""
precip = ""
wind = ""
humidity = ""
currentTemp = ""
location = ""
currentTempBool = ""
date = ""
unixDate = ""
getLocation= ""
wicon = ""
todayicon = "static/images/icons/icon-umberella.png"
precipType = ""
average_temperature = 0
average_temperature1 = 0
average_temperature2 = 0
average_temperature3 = 0
average_temperature4 = 0
totalTime = ""
timestr = ""
timestr1 = ""
timestr2 = ""
timestr3 = ""
timestr4 = ""
plotFred= True
plotCharlottesville = True
plotHonolulu = True
plotRichmond = True
if request.method == 'POST':
print("Here in main in post")
try:
print("Here in main in try")
try:
if request.form['signup']:
print("Here in main in sign up")
#Get the entered username and pwd from form
username = request.form['newUsername']
password = request.form['newPassword']
print('Here')
try:
#See if these credentials match anything in the users table
print(curr.mogrify("SELECT * FROM users where username = %s;", (username, )))
curr.execute("SELECT * FROM users where username = %s;", (username, ))
#If there are results
if (curr.fetchone()):
validSignUpCredentials = False
else:
#Set a session variable (so that the user stays logged in across multiple tabs)
session['username'] = username
query = curr.mogrify("INSERT into users (username, password) VALUES (%s,%s);", (username, password))
print(query)
curr.execute(query)
conn.commit()
curr.execute("SELECT * FROM users;")
res = curr.fetchall()
print(res)
except:
print("There was an error in the sign up")
#If the user hit the Search for Weather data button do this
except:
print("Here in weather search")
if request.form['weatherSearch']:
#Grab what is in the location field
print("Here in if of weather search date is " + date)
location = request.form['locationInput']
getLocation = location
date = request.form['dateInput']
if date == '':
#They entered an invalid date
print("Invalid date")
validDate = False
else:
try:
#Try and see if you can get anything in the city, state_id format (most will be this), format the string by delimiting by ','
location = location.split(',')
#Did user enter zip code
isZip = False
#If the location string had a comma in it
if (len(location) > 1):
#Then we should check and see if they formatted the input like King George, VA and remove the white space before 'VA'
#The string would now be ['King George', ' VA'] we want ['King George', 'VA']
if (location[1][0] == ' '):
#If there is white space at the start of the string, splice it off
location[1] = location[1][1:]
#Run the query
print(curr.mogrify("SELECT lat, lng FROM cities where city=%s and (state_id=%s or state_name=%s);", (location[0], location[1], location[1])))
curr.execute("SELECT lat, lng FROM cities where city=%s and (state_id=%s or state_name=%s);", (location[0], location[1], location[1]))
else:
#Then user probably entered just a zip code
print(location[0])
if (len(location[0]) == 5):
print("Here in main in zip")
#Necessary to get a zip for the ones that have many zips!
wildCardedZipCode = '%'+location[0]+'%'
print(curr.mogrify("SELECT lat, lng FROM cities where zip like %s;", (wildCardedZipCode, )))
curr.execute("SELECT lat, lng, city, state_id FROM cities where zip like %s;", (wildCardedZipCode, ))
print("Here in main after execute")
#It is a zip code
isZip = True
else:
#It was not a valid entry, please reenter, try and figure out how to do this message lol
print("This was not a valid zip cause wrong number of numbers, who taught you to count")
getLocation = ''
validLocation = False
#If there is a result, then it was a valid entry
latLong = curr.fetchone()
if latLong:
print(latLong)
latitude = latLong[0]
longitude = latLong[1]
if (isZip):
getLocation = latLong[2] + ', ' + latLong[3]
print(latLong)
latitude = latLong[0]
longitude = latLong[1]
date = time.mktime(datetime.datetime.strptime(date, "%Y-%m-%d").timetuple())
unixDate = date
validLocation = True
#if date equals todaysdate statement
#how to get u code back
TodaysDate = time.mktime(datetime.datetime.strptime(todaysDate, "%Y-%m-%d").timetuple())
# Returns average temperature for each half decade that the system has information about at the given location.
c = 0
count = 0
count1 = 0
count2 = 0
count3 = 0
count4 = 0
oneYear = 31536000
oneDay = 86400
# Gets a range of years; Starts at 5 years, increments by 5 years and ends by 30 years
years = np.arange(5*oneYear,30*oneYear,5*oneYear+oneDay)
years1 = np.arange(5*oneYear,30*oneYear,5*oneYear+oneDay)
years2 = np.arange(5*oneYear,30*oneYear,5*oneYear+oneDay)
years3 = np.arange(5*oneYear,30*oneYear,5*oneYear+oneDay)
years4 = np.arange(5*oneYear,30*oneYear,5*oneYear+oneDay)
average_temperature = np.empty(years.size)
average_temperature1 = np.empty(years1.size)
average_temperature2 = np.empty(years2.size)
average_temperature3 = np.empty(years3.size)
average_temperature4 = np.empty(years4.size)
totalDates = np.array([])
totalDates1 = np.array([])
totalDates2 = np.array([])
totalDates3 = np.array([])
totalDates4 = np.array([])
d = ""
#Fredericksburg, VA
while plotFred:
latitude1 = 38.30318370
longitude1 = -77.46053990
print "this worked 0"
for i in years1:
# Loop that returns the correct date that corresponds with the
# day the user chooses. There are 5 dates. All are 5 years apart.
# The dates are in the past and have historical averages for temperature.
# The dates begin 5 years before the users chosen date and continue to
# decrease every five years
newDate1 = date
if newDate1 - i <= newDate1 - (15*oneYear):
newDate1 = newDate1 - i - oneDay - oneDay
else:
newDate1 = newDate1 - i - oneDay
a1 = "https://api.darksky.net/forecast/" + key + "/" + str(latitude1) + "," + str(longitude1) + "," + str(int(newDate1)) + "?exclude=minutely,hourly,alerts,flags"
r1 = requests.get(a1)
data1 = r1.json()
current1 = data1['currently']
c1 = current1['temperature']
# Gets all the dates, converts to Y-m-d, and stores them in an array
d1 = datetime.datetime.fromtimestamp(newDate1)
d1 = d1.date()
totalDates1 = np.append(totalDates1, d1)
# Gets average temp at each year and stores value in an array
average_temperature1[count1] = c1
count1+=1
len_average_temperature1 = np.arange(len(average_temperature1))
plt1.cla() # Clear axis
plt1.clf() # Clear figure
#Plots bar graph for average temp for each half decade of given location
plt1.bar(len_average_temperature1, average_temperature1, align="center", alpha=0.5)
plt1.xticks(len_average_temperature1, totalDates1)
plt1.xlabel("Date (Y-M-D)", fontsize=10)
plt1.ylabel("Average Temperature in Fahrenheit", fontsize=10)
plt1.title("Average Temperature for Each Half Decade in Fredericksburg, VA", fontsize=12)
#Creates an image file with the timestamp in the name so the image is always refreshed in window
timestr1 = now.strftime("%Y%m%d-%H%M%S")
plt1.savefig('static/images/'+timestr1+"moretime"'.png')
plotFred = False
# Charlottesville, VA
while plotCharlottesville:
latitude2 = 38.02930590
longitude2 = -78.47667810
print "this worked 0"
for k in years2:
# Loop that returns the correct date that corresponds with the
# day the user chooses. There are 5 dates. All are 5 years apart.
# The dates are in the past and have historical averages for temperature.
# The dates begin 5 years before the users chosen date and continue to
# decrease every five years
newDate2 = date
if newDate2 - k <= newDate2 - (15*oneYear):
newDate2 = newDate2 - k - oneDay - oneDay
else:
newDate2 = newDate2 - k - oneDay
a2 = "https://api.darksky.net/forecast/" + key + "/" + str(latitude2) + "," + str(longitude2) + "," + str(int(newDate2)) + "?exclude=minutely,hourly,alerts,flags"
r2 = requests.get(a2)
data2 = r2.json()
current2 = data2['currently']
c2 = current2['temperature']
# Gets all the dates, converts to Y-m-d, and stores them in an array
d2 = datetime.datetime.fromtimestamp(newDate2)
d2 = d2.date()
totalDates2 = np.append(totalDates2, d2)
# Gets average temp at each year and stores value in an array
average_temperature2[count2] = c2
count2+=1
len_average_temperature2 = np.arange(len(average_temperature2))
plt2.cla() # Clear axis
plt2.clf() # Clear figure
#Plots bar graph for average temp for each half decade of given location
plt2.bar(len_average_temperature2, average_temperature2, align="center", alpha=0.5)
plt2.xticks(len_average_temperature2, totalDates2)
plt2.xlabel("Date (Y-M-D)", fontsize=10)
plt2.ylabel("Average Temperature in Fahrenheit", fontsize=10)
plt2.title("Average Temperature for Each Half Decade in Charlottesville, VA", fontsize=12)
#Creates an image file with the timestamp in the name so the image is always refreshed in window
timestr2 = now.strftime("%Y%m%d-%H%M%S")
plt2.savefig('static/images/'+timestr2+"moretime2"'.png')
plotCharlottesville = False
# Honolulu, HI
while plotHonolulu:
latitude3 = 21.30694440
longitude3 = -157.85833330
print "this worked 0"
for h in years3:
# Loop that returns the correct date that corresponds with the
# day the user chooses. There are 5 dates. All are 5 years apart.
# The dates are in the past and have historical averages for temperature.
# The dates begin 5 years before the users chosen date and continue to
# decrease every five years
newDate3 = date
if newDate3 - h <= newDate3 - (15*oneYear):
newDate3 = newDate3 - h - oneDay - oneDay
else:
newDate3 = newDate3 - h - oneDay
a3 = "https://api.darksky.net/forecast/" + key + "/" + str(latitude3) + "," + str(longitude3) + "," + str(int(newDate3)) + "?exclude=minutely,hourly,alerts,flags"
r3 = requests.get(a3)
data3 = r3.json()
current3 = data3['currently']
c3 = current3['temperature']
# Gets all the dates, converts to Y-m-d, and stores them in an array
d3 = datetime.datetime.fromtimestamp(newDate3)
d3 = d3.date()
totalDates3 = np.append(totalDates3, d3)
# Gets average temp at each year and stores value in an array
average_temperature3[count3] = c3
count3+=1
len_average_temperature3 = np.arange(len(average_temperature3))
plt3.cla() # Clear axis
plt3.clf() # Clear figure
#Plots bar graph for average temp for each half decade of given location
plt3.bar(len_average_temperature3, average_temperature3, align="center", alpha=0.5)
plt3.xticks(len_average_temperature3, totalDates3)
plt3.xlabel("Date (Y-M-D)", fontsize=10)
plt3.ylabel("Average Temperature in Fahrenheit", fontsize=10)
plt3.title("Average Temperature for Each Half Decade in Charlottesville, VA", fontsize=12)
#Creates an image file with the timestamp in the name so the image is always refreshed in window
timestr3 = now.strftime("%Y%m%d-%H%M%S")
plt3.savefig('static/images/'+timestr3+"moretime3"'.png')
plotHonolulu = False
# Richmond, VA
while plotRichmond:
latitude4 = 37.55375750
longitude4 = -77.46026170
print "this worked 0"
for j in years4:
# Loop that returns the correct date that corresponds with the
# day the user chooses. There are 5 dates. All are 5 years apart.
# The dates are in the past and have historical averages for temperature.
# The dates begin 5 years before the users chosen date and continue to
# decrease every five years
newDate4 = date
if newDate4 - j <= newDate4 - (15*oneYear):
newDate4 = newDate4 - j - oneDay - oneDay
else:
newDate4 = newDate4 - j - oneDay
a4 = "https://api.darksky.net/forecast/" + key + "/" + str(latitude4) + "," + str(longitude4) + "," + str(int(newDate4)) + "?exclude=minutely,hourly,alerts,flags"
r4 = requests.get(a4)
data4 = r4.json()
current4 = data4['currently']
c4 = current4['temperature']
# Gets all the dates, converts to Y-m-d, and stores them in an array
d4 = datetime.datetime.fromtimestamp(newDate4)
d4 = d4.date()
totalDates4 = np.append(totalDates4, d4)
# Gets average temp at each year and stores value in an array
average_temperature4[count4] = c4
count4+=1
len_average_temperature4 = np.arange(len(average_temperature4))
plt4.cla() # Clear axis
plt4.clf() # Clear figure
#Plots bar graph for average temp for each half decade of given location
plt4.bar(len_average_temperature4, average_temperature4, align="center", alpha=0.5)
plt4.xticks(len_average_temperature4, totalDates4)
plt4.xlabel("Date (Y-M-D)", fontsize=10)
plt4.ylabel("Average Temperature in Fahrenheit", fontsize=10)
plt4.title("Average Temperature for Each Half Decade in Charlottesville, VA", fontsize=12)
#Creates an image file with the timestamp in the name so the image is always refreshed in window
timestr4 = now.strftime("%Y%m%d-%H%M%S")
plt4.savefig('static/images/'+timestr4+"moretime4"'.png')
plotRichmond = False
print "this worked 1"
# Location user chooses
for y in years:
# Loop that returns the correct date that corresponds with the
# day the user chooses. There are 5 dates. All are 5 years apart.
# The dates are in the past and have historical averages for temperature.
# The dates begin 5 years before the users chosen date and continue to
# decrease every five years
newDate = date
if newDate - y <= newDate - (15*oneYear):
newDate = newDate - y - oneDay - oneDay
else:
newDate = newDate - y - oneDay
a = "https://api.darksky.net/forecast/" + key + "/" + str(latitude) + "," + str(longitude) + "," + str(int(newDate)) + "?exclude=minutely,hourly,alerts,flags"
r = requests.get(a)
data = r.json()
current = data['currently']
c = current['temperature']
# Gets all the dates, converts to Y-m-d, and stores them in an array
d = datetime.datetime.fromtimestamp(newDate)
d = d.date()
totalDates = np.append(totalDates, d)
# Gets average temp at each year and stores value in an array
average_temperature[count] = c
count+=1
len_average_temperature = np.arange(len(average_temperature))
plt.cla() # Clear axis
plt.clf() # Clear figure
#Plots bar graph for average temp for each half decade of given location
plt.bar(len_average_temperature, average_temperature, align="center", alpha=0.5)
plt.xticks(len_average_temperature, totalDates)
plt.xlabel("Date (Y-M-D)", fontsize=10)
plt.ylabel("Average Temperature in Fahrenheit", fontsize=10)
plt.title("Average Temperature for Each Half Decade in " + str(location[0]) +", "+ str(location[1]), fontsize=12)
#Creates an image file with the timestamp in the name so the image is always refreshed in window
timestr = now.strftime("%Y%m%d-%H%M%S")
plt.savefig('static/images/'+timestr+'.png')
print "this worked 2"
#if within next seven days give current
if date <= (TodaysDate + (86400*7)):
try:
print "this worked 3"
#Allows you to access your JSON data easily within your code. Includes built in JSON decoder
apiCall = "https://api.darksky.net/forecast/" + key + "/" + str(latitude) + "," + str(longitude) + "," + str(int(date)) + "?exclude=minutely,hourly,alerts,flags"
#Request to access API
print "this worked 4"
response = requests.get(apiCall)
#Creates python dictionary from JSON weather information from API
weatherData = response.json()
#Set date equal to todays date and change format
date = datetime.datetime.fromtimestamp(date)
date = date.date()
weekdayName = datestrftime
print "this worked 5"
#Daily data information
dailyData = weatherData['daily']['data'][0]
#Currently data information
currentData = weatherData['currently']
currentTemp = currentData['temperature']
lowTemp = dailyData['temperatureLow'] #Degrees Farenheit
highTemp = dailyData['temperatureHigh'] #Degrees Farenheit
precip = dailyData['precipProbability'] * 100 # percentage
wind = dailyData['windSpeed'] # miles/hour
humidity = dailyData['humidity'] * 100 # percentage
wicon = dailyData['icon']
currentTempBool = bool(currentTemp)
if wicon == "clear-day":
todayicon = "static/images/icons/icon-2.svg"
if wicon == "clear-night":
todayicon = ""
if wicon == "rain":
todayicon = "static/images/icons/icon-10.svg"
if wicon == "sleet":
todayicon = "static/images/icons/icon-10.svg"
if wicon == "snow":
todayicon = "static/images/icons/icon-14.svg"
if wicon == "hail":
todayicon = "static/images/icons/icon-14.svg"
if wicon == "wind":
todayicon = "static/images/icons/icon-wind.png"
if wicon == "fog":
todayicon = "static/images/icons/icon-7.svg"
if wicon == "cloudy":
todayicon = "static/images/icons/icon-5.svg"
if wicon == "partly-cloudy-day":
todayicon = "static/images/icons/icon-6.svg"
if wicon == "partly-cloudy-night":
todayicon = ""
if wicon == "thunderstorm":
todayicon = "static/images/icons/icon-11.svg"
if wicon == "tornado":
todayicon = "static/images/icons/icon-8.svg"
except:
print("Call to api failed in next 7 days")
else:
try:
#Allows you to access your JSON data easily within your code. Includes built in JSON decoder
apiCall = "https://api.darksky.net/forecast/" + key + "/" + str(latitude) + "," + str(longitude) + "," + str(int(date)) + "?exclude=minutely,hourly,alerts,flags"
#Request to access API
response = requests.get(apiCall)
#Creates python dictionary from JSON weather information from API
weatherData = response.json()
#Set date equal to todays date and change format
date = datetime.datetime.fromtimestamp(date)
date = date.date()
weekdayName = date.strftime("%A")
#print(weatherData)
#Daily data information
dailyData = weatherData['daily']['data'][0]
#Currently data information
currentData = weatherData['currently']
#Retrieving a current temperature
currentTemp = currentData['temperature']
lowTemp = dailyData['temperatureLow'] #Degrees Farenheit
highTemp = dailyData['temperatureHigh'] #Degrees Farenheit
wicon = dailyData['icon']
precipType = dailyData['precipType']
currentTempBool = bool(currentTemp)
if wicon == "clear-day":
todayicon = "static/images/icons/icon-2.svg"
if wicon == "clear-night":
todayicon = ""
if wicon == "rain":
todayicon = "static/images/icons/icon-10.svg"
if wicon == "sleet":
todayicon = "static/images/icons/icon-10.svg"
if wicon == "snow":
todayicon = "static/images/icons/icon-14.svg"
if wicon == "hail":
todayicon = "static/images/icons/icon-14.svg"
if wicon == "wind":
todayicon = "static/images/icons/icon-wind.png"
if wicon == "fog":
todayicon = "static/images/icons/icon-7.svg"
if wicon == "cloudy":
todayicon = "static/images/icons/icon-5.svg"
if wicon == "partly-cloudy-day":
todayicon = "static/images/icons/icon-6.svg"
if wicon == "partly-cloudy-night":
todayicon = ""
if wicon == "thunderstorm":
todayicon = "static/images/icons/icon-11.svg"
if wicon == "tornado":
todayicon = "static/images/icons/icon-8.svg"
except:
print("Call to api failed in next 7 days.")
else:
#It was not a valid entry, please reenter, try and figure out how to do this message lol
print("This was not a valid input.")
validLocation = False
except:
print("Error selecting information from cities.")
getLocation = ''
#If the user hit the submit button on the login form then do this
except:
#This is the sign in. This is here because there is a weird thing with having two models and using request.form that makes that
#throw an error when I try and do it in the first if in the try. As a result I put the log in down here so that it works out.
#any questions ask me (charbel) and I can explain better in person
#Get the entered username and pwd from form
username = request.form['username']
password = request.form['password']
#See if these credentials match anything in the users table
print(curr.mogrify("SELECT * FROM users where username = %s and password = %s;", (username, password)))
curr.execute("SELECT * FROM users where username = %s and password = %s;", (username, password))
#If there are results
if (curr.fetchone()):
#Set a session variable (so that the user stays logged in across multiple tabs)
session['username'] = username
else:
validLogInCredentials = False
try:
curr.execute("SELECT city, state_id, zip FROM cities;")
except:
print("Error selecting information from cities.")
getLocation = ''
results = curr.fetchall()
#Return location as a string and replaces extra characters
if (isZip == False and getLocation != ''):
getLocation = ast.literal_eval(json.dumps(location))
getLocation = str(getLocation)
getLocation = getLocation.translate(None, '\'[!@#$]')
getLocation = getLocation.replace("",'')
print("get loc " + getLocation)
return render_template('index.html', username=session['username'], validSignUpCredentials=validSignUpCredentials,
validLogInCredentials=validLogInCredentials, results=results, date=date, unixDate = unixDate,
todaysDate=todaysDate, TodaysDate=TodaysDate, weekdayName=weekdayName, average_temperature=average_temperature, lowTemp=lowTemp,
highTemp=highTemp, precip=precip, precipType=precipType, currentTemp=currentTemp, wind=wind, humidity=humidity,
getLocation=getLocation, todayicon=todayicon, wicon=wicon, validDate=validDate, validLocation=validLocation,
currentTempBool=currentTempBool, timestr=timestr, timestr1=timestr1, timestr2=timestr2, timestr3=timestr3, timestr4=timestr4)
#Start the server here
if __name__ == '__main__':
application.run(host = os.getenv('IP', '0.0.0.0'), port = int(os.getenv('PORT', 8080)), debug = True) | [
"dylon.garrett@gmail.com"
] | dylon.garrett@gmail.com |
fa95f623b2599c90f42e459fce3ea3a9f073244c | 7019318d9922aded6a8a70d0e53ee5abc0475952 | /dataloader/test_alternate_sampling.py | 6985212ff4e5b473f4d57b03470d4143714f39e0 | [] | no_license | rajatmodi62/multi-purpose-networks | 68979977ff884a603cbfecf55caeda6a6e1d31f0 | 2c456247b2c3a2f4f5c9bcc0fdba250176a07851 | refs/heads/master | 2022-12-28T17:46:05.278048 | 2020-10-15T16:29:08 | 2020-10-15T16:29:08 | 286,252,077 | 0 | 0 | null | 2020-10-15T16:29:09 | 2020-08-09T14:22:14 | Python | UTF-8 | Python | false | false | 1,259 | py | import torch
from torch.utils.data.dataset import ConcatDataset
from dataloader.cifar10 import CIFAR10
from dataloader.fashion_mnist import FashionMNIST
from dataloader.multi_task_batch_scheduler import BatchSchedulerSampler
import matplotlib.pyplot as plt
cifar = CIFAR10(data_root="dataset/cifar10",
transform=None,
mode='train',
)
fashion_mnist = FashionMNIST(data_root="dataset/fashion-mnist",
transform=None,
mode='train',
)
concat_dataset = ConcatDataset([cifar, fashion_mnist])
batch_size = 4
# dataloader with BatchSchedulerSampler
dataloader = torch.utils.data.DataLoader(dataset=concat_dataset,
sampler=BatchSchedulerSampler(dataset=concat_dataset,
batch_size=batch_size),
batch_size=batch_size,
)
for inputs in dataloader:
# print(type(inputs),len(inputs),type(inputs[0]),type(inputs[1]),type(inputs[2]),inputs[0].shape)
print(inputs[2]['conditioning_label'])
plt.imshow(inputs[0][0])
plt.show()
| [
"rajatmodi62@gmail.com"
] | rajatmodi62@gmail.com |
12cc7867264992bda01279ee9bf6b8158ec5707c | caaede923b3e9f7d591887f1332242f3afe356ea | /venv/Scripts/easy_install-3.6-script.py | 7766e52de6542fe2f6215609ef36fc0a749996a6 | [] | no_license | 1433993695/alien_invasion | 8b4a6b18c6e7979eb80be9950daf7be862afced8 | 3ec82c647b697865fa4375b3af5d73fc0963c832 | refs/heads/master | 2021-09-19T19:30:19.165874 | 2018-07-31T09:25:46 | 2018-07-31T09:25:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 467 | py | #!C:\Users\zc-cris\PycharmProjects\alien_invasion\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==39.1.0','console_scripts','easy_install-3.6'
__requires__ = 'setuptools==39.1.0'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('setuptools==39.1.0', 'console_scripts', 'easy_install-3.6')()
)
| [
"17623887386@163.com"
] | 17623887386@163.com |
f21e0e01331ba46a179178aa5615df5f6987f89c | 127f22e03511ec2f4c31d07a12d95084d967ecfe | /fitangle.py | ff8f07502ac13181c52359f8c17cbb64ebe1e0b7 | [] | no_license | wang101/coherentac | 9dd16e166b135f11ea6c36ceb663fb853de4a2ca | 82fcca638a910acbce30020ad8d9dc74d3d56c29 | refs/heads/master | 2020-09-07T11:42:59.096521 | 2017-06-15T10:26:55 | 2017-06-15T10:26:55 | 94,426,498 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,090 | py | # -*- coding: utf-8 -*-
"""
Created on Sun May 22 10:54:38 2016
@author: wang
"""
# -*- coding: utf-8 -*-
"""
Created on Sun May 8 10:33:33 2016
@author: wang
"""
import numpy as np
import matplotlib.pyplot as plt
import string
import os
import h5py
import re
import pickle as pkl
ptask = open("task.input","r")
job = []
para = {}
for line in ptask.readlines():
if(line[0]=='/' or line[0]=='\n'):
continue
[a,b] = line.split("=")
if a=='angle':
job.append([float(x) for x in b.strip().split(',')])
else:
para[a]=b.strip()
filename = para['protein_file']
filepath=para['save_path']
pix_size= float(para['pix_size'])
D = float(para['distance'])
lambdaxray=float(para['lambda'])
if not os.path.exists(filepath):
os.mkdir(filepath)
filename_list = os.listdir(filepath)
filename_list.sort()
rere = re.compile(r'c\d+:(\w|-|\.)*:(\w|-|\.)*,(\w|-|\.)*,(\w|-|\.)*.dat')
arrlst = []
anglst = []
for filename in filename_list:
if rere.match(filename.strip()):
protein_name,filenum,angs = filename.split(":")
ang1,ang2,ang3 = angs[:-4].split(",")
filenum = int(filenum)
ang1 = float(ang1)
ang2 = float(ang2)
ang3 = float(ang3)
anglst.append(np.array((ang1,ang2,ang3)))
f = open(filepath+filename,'r')
lst = []
for line in f.readlines():
comp = line.strip().split(',')[:-1]
linereal = [float(y[0]) for y in [x.split('+') for x in comp]]
lineimag = [float(y[1]) for y in [x.split('+') for x in comp]]
arrRow = np.array([linereal[i]+lineimag[i]*1j for i in range(len(linereal))])
lst.append(arrRow)
arr = np.array(lst)
arrlst.append(arr)
h = h5py.File('lst'+protein_name+'.h5','w')
sparr = arr.shape
arrall = np.array(arrlst)
angall = np.array(anglst)
protein_namelst = (protein_name,)*len(arrall)
h.create_dataset('pattern',arrall.shape,data=arrall)
h.create_dataset('angle',angall.shape,data=angall)
h.create_dataset('protein_name',(len(protein_namelst),),data=protein_namelst)
h.close()
| [
"hxwang1992@gmail.com"
] | hxwang1992@gmail.com |
68c11e7899d80a15888e4252296049bf2b4e8843 | 2fd087fbc5faf43940153693823969df6c8ec665 | /pyc_decrypted/latest/dropbox/client/watchdog.py | 6983e510c3bd0826ea5395ce93826e40f4907e9b | [] | no_license | mickeystone/DropBoxLibrarySRC | ed132bbffda7f47df172056845e5f8f6c07fb5de | 2e4a151caa88b48653f31a22cb207fff851b75f8 | refs/heads/master | 2021-05-27T05:02:30.255399 | 2013-08-27T13:16:55 | 2013-08-27T13:16:55 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 17,772 | py | #Embedded file name: dropbox/client/watchdog.py
import hashlib
import os
import socket
import struct
import threading
import time
from Crypto.Random import random
from trace_report import make_report
from dropbox.build_common import get_build_number
from dropbox.callbacks import Handler
from dropbox.fileutils import safe_remove
from dropbox.globals import dropbox_globals
from dropbox.native_event import AutoResetEvent
from dropbox.native_queue import Queue
from dropbox.platform import platform
from dropbox.sqlite3_helpers import sqlite3_get_memory_statistics
from dropbox.threadutils import StoppableThread
from dropbox.trace import TRACE, unhandled_exc_handler, add_exception_handler, report_bad_assumption
import arch
from dropbox.client.high_trace import sample_process, send_ds_store, send_finder_crashes, send_trace_log
_ONE_WEEK = 604800
class Watchdog2(object):
UNIT_REPORT_INTERVAL = 900
HIGH_CPU_USAGE = 0.3
def __init__(self, status_controller, conn, handler = None):
self.status_controller = status_controller
self.sync_engine = None
self.conn = conn
add_exception_handler(self.handle_exception)
self.clear()
if handler:
handler.add_handler(self.update_counts)
def clear(self):
self.last_times = (time.time(), 0, 0)
self.hung_since = None
self.high_cpu_minutes = 0
self.over_quota = False
self.report_interval = self.UNIT_REPORT_INTERVAL
self.last_cpu_minutes = 0
self.last_dbfseventsd_broken = False
self.last_counts = (0, 0, 0, 0)
self.last_report = 0
self.last_exception_hash = None
self.last_upload_exception_hash = None
self.last_reconstruct_exception_hash = None
self.last_hash_exception_hash = None
self.exc_lock = threading.Lock()
def handle_exception(self, *exc_info, **kw):
with self.exc_lock:
self.last_exception_hash = make_report(exc_info)[1]
thr_name = threading.currentThread().getName()
if thr_name == 'UPLOAD':
self.last_upload_exception_hash = self.last_exception_hash
elif thr_name == 'RECONSTRUCT':
self.last_reconstruct_exception_hash = self.last_exception_hash
elif thr_name == 'HASH':
self.last_hash_exception_hash = self.last_exception_hash
def set_sync_engine(self, sync_engine):
self.sync_engine = sync_engine
self.sync_engine.add_list_callback(self._handle_list)
def _handle_list(self, ret):
try:
self.over_quota = ret['in_use'] > ret['quota']
except KeyError:
pass
def update_counts(self):
if not self.sync_engine:
return
if not self.sync_engine.running:
self.clear()
return
ct = time.time()
elapsed = ct - self.last_times[0]
if elapsed >= 60:
sys_time = ct, utime, stime = self.sync_engine.get_system_time_tuple()
cpu_usage = (stime + utime - (self.last_times[1] + self.last_times[2])) / elapsed
if cpu_usage > self.HIGH_CPU_USAGE:
self.high_cpu_minutes += 1
TRACE('!! Warning: high CPU usage (%d mins total; %.1f%% used)' % (self.high_cpu_minutes, cpu_usage * 100))
self.last_times = sys_time
if ct - self.last_report >= self.report_interval:
queue_stats = self.sync_engine.get_queue_stats()
counts = (queue_stats['hash']['total_count'],
queue_stats['upload']['total_count'],
queue_stats['reconstruct']['total_count'],
queue_stats['conflicted']['total_count'])
is_hung = self.last_counts == counts and sum(counts)
cpu_minutes = self.high_cpu_minutes - self.last_cpu_minutes
dbfseventsd_broken = dropbox_globals.get('dbfseventsd_is_broken', False)
try:
if is_hung or self.last_dbfseventsd_broken != dbfseventsd_broken and dbfseventsd_broken or cpu_minutes >= 5:
TRACE('!! Sync engine appears stalled: %r (%s high cpu mins) dbfseventsd_broken:%r' % (counts, cpu_minutes, dbfseventsd_broken))
if self.hung_since is None:
self.hung_since = time.time()
send_trace_log()
if cpu_minutes >= 5:
sample_process()
current_upload_speed = self.status_controller.upload_status.get_transfer_speed() or 0
current_download_speed = self.status_controller.download_status.get_transfer_speed() or 0
upload_bytecount, upload_hashcount = self.sync_engine.upload_queue_size()
download_bytecount, download_hashcount = self.sync_engine.download_queue_size()
unreconstructable_count = 0
self.conn.report_hang2(dict(is_hung=is_hung, dbfseventsd_broken=dbfseventsd_broken, cpu_minutes=cpu_minutes, cpu_minutesp=float(cpu_minutes) / self.report_interval, hung_for=time.time() - self.hung_since, queue_stats=queue_stats, conflicted_count=queue_stats['conflicted']['total_count'], over_quota=self.over_quota, current_upload_speed=current_upload_speed, current_download_speed=current_download_speed, low_disk_space=self.status_controller.is_true('low_disk_space'), upload_bytecount=upload_bytecount, download_bytecount=download_bytecount, upload_hashcount=upload_hashcount, download_hashcount=download_hashcount, unreconstructable_count=unreconstructable_count, exception_hashes=(self.last_exception_hash,
self.last_hash_exception_hash,
self.last_upload_exception_hash,
self.last_reconstruct_exception_hash)))
elif self.hung_since:
TRACE('!! Sync engine no longer stalled: %r' % (counts,))
self.conn.report_hang2(None)
self.hung_since = None
except Exception as e:
if self.conn.is_transient_error(e):
TRACE('!! Failed to communicate with server: %r%r', type(e), e.args)
else:
unhandled_exc_handler()
self.report_interval += self.UNIT_REPORT_INTERVAL
else:
self.last_counts = counts
self.last_dbfseventsd_broken = dbfseventsd_broken
self.last_cpu_minutes = self.high_cpu_minutes
self.last_report = ct
self.report_interval = self.UNIT_REPORT_INTERVAL
class StatReporter(object):
DEFAULT_INTERVAL = 900
def __init__(self, csr, buildno, status_controller, conn, config, handler = None):
self.csr = csr
self.config = config
self.old_stats = {}
self.last_report = 0
self.buildno = buildno
self.interval = self.DEFAULT_INTERVAL
self.status_controller = status_controller
self.conn = conn
self.sync_engine = None
self.failure_backoff = None
try:
with self.config as config:
try:
last_stats_build = config['stats_build']
except KeyError:
self.next_report_id = config.get('stats_next_report_id', 0)
self.next_report_time = config.get('stats_next_report_time')
self.dont_send_until_upgrade = config.get('stats_dont_send_until_upgrade')
else:
if last_stats_build != get_build_number():
self.next_report_id = 0
self.next_report_time = None
self.dont_send_until_upgrade = False
else:
self.next_report_id = config.get('stats_next_report_id', 0)
self.next_report_time = config.get('stats_next_report_time')
self.dont_send_until_upgrade = config.get('stats_dont_send_until_upgrade')
except Exception:
unhandled_exc_handler()
self.next_report_id = 0
self.next_report_time = None
self.dont_send_until_upgrade = False
if self.next_report_time:
TRACE('Client stats wants us to hit the server again at %s (%s seconds) (local: %s)' % (self.next_report_time, self.next_report_time - time.time(), time.ctime(self.next_report_time)))
if handler:
handler.add_handler(self.run)
def set_reporting_interval(self, interval):
self.interval = interval
def set_sync_engine(self, sync_engine):
self.sync_engine = sync_engine
def report_queryable_stats(self):
us = self.status_controller.upload_status.get_transfer_speed()
if us is not None:
self.csr.report_stat('upload_speed', str(us))
ds = self.status_controller.download_status.get_transfer_speed()
if ds is not None:
self.csr.report_stat('download_speed', str(ds))
if self.sync_engine:
queue_stats = self.sync_engine.get_queue_stats()
self.csr.report_stat('pending_cache_count', str(queue_stats['upload']['total_count']))
self.csr.report_stat('to_hash_cache_count', str(queue_stats['hash']['total_count']))
self.csr.report_stat('updated_cache_count', str(queue_stats['reconstruct']['total_count']))
self.csr.report_stat('conflicted_cache_count', str(queue_stats['conflicted']['total_count']))
self.csr.report_stat('quota_pending_cache_count', str(queue_stats['upload']['failure_counts'].get('quota', 0)))
self.csr.report_stat('invalid_path_pending_cache_count', str(queue_stats['upload']['failure_counts'].get('invalid_path', 0)))
self.csr.report_stat('directory_not_empty_updated_cache_count', str(queue_stats['reconstruct']['failure_counts'].get('directory_not_empty', 0)))
self.csr.report_stat('low_disk_space_updated_cache_count', str(queue_stats['reconstruct']['failure_counts'].get('low_disk_space', 0)))
self.csr.report_stat('permission_denied_updated_cache_count', str(queue_stats['reconstruct']['failure_counts'].get('permission_denied', 0)))
n = int(time.time())
self.csr.report_stat('gui_backoff_factor', str(struct.unpack('<Q', hashlib.md5('Open %s Folder Launch %d Website Apple CarbonEventManager Windows %d' % (self.buildno, n, self.conn.host_int)).digest()[:struct.calcsize('<Q')])[0]), n)
rss = arch.startup.get_rss()
if rss is not None and rss != -1:
self.csr.report_stat('rss', str(rss))
try:
mem_used, highwater = sqlite3_get_memory_statistics()
except Exception:
unhandled_exc_handler()
else:
self.csr.report_stat('sqlite3_memory_used', str(mem_used))
self.csr.report_stat('sqlite3_memory_highwater', str(highwater))
try:
if self.sync_engine and self.sync_engine.p2p_state and self.sync_engine.p2p_state.pool:
peer_dict = self.sync_engine.p2p_state.pool.getPeerAndConnCount()
self.csr.report_stat('peer_count', str(peer_dict['peer_count']))
self.csr.report_stat('peer_connections', str(peer_dict['total_connections']))
except Exception:
unhandled_exc_handler()
def run(self):
if self.dont_send_until_upgrade:
return
if self.failure_backoff:
if time.time() < self.failure_backoff[1]:
return
if self.next_report_time is not None and time.time() < self.next_report_time:
report_bad_assumption('Client-stats backoff was less than our next report time, %s < %s' % (self.next_report_time, self.failure_backoff[1]))
elif self.next_report_time is not None and time.time() < self.next_report_time:
return
self.report_queryable_stats()
self.csr.lock_updates()
try:
total_stats = self.csr.total_stats()
total_events = self.csr.total_events()
report_id = self.next_report_id
divisor = 1
done = False
while not done:
to_pull_from_stats = total_stats / divisor
to_pull_from_events = total_events / divisor
for i in xrange(divisor):
stat_batch = self.csr.iterate_n_stats(to_pull_from_stats)
event_batch = self.csr.iterate_n_events(to_pull_from_events)
stats_to_send = [ (stat, arg, ts) for stat, (arg, ts) in stat_batch ]
try:
event_ids_to_clear, events_to_send = zip(*event_batch)
except ValueError:
event_ids_to_clear, events_to_send = (), ()
if not (stats_to_send or events_to_send):
done = True
break
try:
ret = self.conn.report_stats(time.time(), stats_to_send, events_to_send, self.buildno, report_id)
except Exception as e:
unhandled_exc_handler()
if isinstance(e, socket.error) and e[0] == 32:
break
if self.failure_backoff:
self.failure_backoff = (self.failure_backoff[0] * 2, min(random.uniform(0, self.failure_backoff[0] * 4), _ONE_WEEK) + time.time())
else:
self.failure_backoff = (1, random.uniform(0, 2) + time.time())
TRACE('!! Client Stats failed, backing off until %s for (%s seconds) (local: %s)' % (self.failure_backoff[1], self.failure_backoff[1] - time.time(), time.ctime(self.failure_backoff[1])))
done = True
else:
self.failure_backoff = None
try:
self.dont_send_until_upgrade = ret['dont_send_until_upgrade']
except KeyError:
stats_backoff = float(ret['backoff'])
next_report_id = long(ret['report_id'])
self.next_report_time = stats_backoff + time.time()
self.next_report_id = next_report_id
else:
self.next_report_time = None
self.next_report_id = 0
try:
with self.config as config:
config['stats_dont_send_until_upgrade'] = self.dont_send_until_upgrade
config['stats_next_report_time'] = self.next_report_time
config['stats_next_report_id'] = self.next_report_id
config['stats_build'] = get_build_number()
except Exception:
unhandled_exc_handler()
TRACE('Client stats wants us to hit the server again at %s (%s seconds) (local: %s)', self.next_report_time, stats_backoff, time.ctime(self.next_report_time))
self.csr.clean_reported_stats_and_event_ids(stats_to_send, event_ids_to_clear)
divisor *= 2
finally:
self.csr.unlock_updates()
def maybe_send_explorer_crash():
if arch.util.unreported_explorer_crash():
send_trace_log()
class WatchdogThread(StoppableThread):
def __init__(self, app, *n, **kw):
kw['name'] = 'WATCHDOG'
super(WatchdogThread, self).__init__(*n, **kw)
self.app = app
self.bangp = AutoResetEvent()
self.one_time_q = Queue(100)
self.handler = Handler(handle_exc=unhandled_exc_handler)
self.add_handler(self._one_time_handler)
def set_wakeup_event(self, *n, **kw):
self.bangp.set(*n, **kw)
def add_handler(self, *n, **kw):
self.handler.add_handler(*n, **kw)
def remove_handler(self, *n, **kw):
self.handler.remove_handler(*n, **kw)
def add_one_time_handler(self, cb):
try:
self.one_time_q.put(cb)
except Exception:
unhandled_exc_handler()
def _one_time_handler(self, *n, **kw):
for fn in self.one_time_q.get_all_and_clear():
try:
fn(*n, **kw)
except Exception:
unhandled_exc_handler()
def run(self):
TRACE('Watchdog thread starting.')
if platform == 'mac':
def maybe_send_finder_crashes():
sarch = self.app.sync_engine.arch
if sarch.fschange and sarch.fschange.potential_finder_restart():
send_finder_crashes()
self.add_handler(maybe_send_finder_crashes)
self.add_handler(send_ds_store)
if platform == 'win':
self.add_handler(maybe_send_explorer_crash)
send_finder_crashes()
self.remove_installer_logs()
while not self.stopped():
self.handler.run_handlers()
self.bangp.wait(60)
TRACE('Stopping...')
def remove_installer_logs(self):
if platform != 'win':
return
try:
installer_log_dir = os.path.join(self.app.appdata_path, 'installer', 'l')
if not os.path.exists(installer_log_dir):
return
for x in os.listdir(installer_log_dir):
full_path = os.path.join(installer_log_dir, x)
safe_remove(full_path)
except Exception:
unhandled_exc_handler()
| [
"bizonix@me.com"
] | bizonix@me.com |
1a932c0e0b4f85b37b433d204a237c7f7a544837 | 688b5380775d8084977706e17a95ed984a8a1cbe | /Array/intersection_two_arr.py | cea510e18d0dc4b2a0737a05c5f9a951b4a1c1c2 | [] | no_license | priyanka-punjabi/Leetcode | 29c270346d101446e83320993002b0bba033e99b | e9fa95d66ada6d541826005a306623dbf90d24a8 | refs/heads/master | 2020-08-12T06:11:15.554678 | 2020-05-12T17:48:55 | 2020-05-12T17:48:55 | 214,704,110 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 232 | py | class Solution:
def intersection(self, nums1, nums2):
res = []
for ele in range(len(nums1)):
if nums1[ele] in nums2 and nums1[ele] not in res:
res.append(nums1[ele])
return res | [
"pp4762@rit.edu"
] | pp4762@rit.edu |
7cdf3b2369d577abb7bf0d5e39f8acb376997c86 | c4265723cf2c5532687edca784a03001c8b48e56 | /examples/tweet_notify.py | e511a7622a0364b62251d2475d5a7a2ffdb278cc | [
"MIT"
] | permissive | jsikorsky/blynk-library-python | f3c5da8d17665c5d4cb01d541eb171412453d10a | e40208fc9cbb3dc3784046753ce27e0d20884b07 | refs/heads/master | 2020-04-29T02:34:29.540831 | 2019-03-15T21:14:32 | 2019-03-15T21:14:32 | 175,774,359 | 1 | 0 | MIT | 2019-03-15T07:56:02 | 2019-03-15T07:56:00 | Python | UTF-8 | Python | false | false | 1,213 | py | """
Blynk is a platform with iOS and Android apps to control
Arduino, Raspberry Pi and the likes over the Internet.
You can easily build graphic interfaces for all your
projects by simply dragging and dropping widgets.
Downloads, docs, tutorials: http://www.blynk.cc
Sketch generator: http://examples.blynk.cc
Blynk community: http://community.blynk.cc
Social networks: http://www.fb.com/blynkapp
http://twitter.com/blynk_app
This example shows how to handle a button press and
send Twitter & Push notifications.
In your Blynk App project:
Add a Button widget, bind it to Virtual Pin V4.
Add a Twitter widget and connect it to your account.
Add a Push notification widget.
Run the App (green triangle in the upper right corner).
"""
import BlynkLib
BLYNK_AUTH = 'YourAuthToken'
# initialize Blynk
blynk = BlynkLib.Blynk(BLYNK_AUTH)
@blynk.VIRTUAL_WRITE(4)
def v4_write_handler(value):
if value[0]: # is the the button is pressed?
blynk.notify('You pressed the button and I know it ;)')
blynk.tweet('My IoT project is tweeting using @blynk_app and it’s awesome! #IoT #blynk')
while True:
blynk.run()
| [
"vshymanskyi@gmail.com"
] | vshymanskyi@gmail.com |
3231911515adfd0365eae0b7ab08f656f1a18ce5 | 134c429df7d5c4d067d9761cb1435992b048adaf | /notes/0431/0431.py | 11bc6ce8611f6db618e1efae727ca798d3c25e41 | [] | no_license | PaulGuo5/Leetcode-notes | 65c6ebb61201d6f16386062e4627291afdf2342d | 431b763bf3019bac7c08619d7ffef37e638940e8 | refs/heads/master | 2021-06-23T09:02:58.143862 | 2021-02-26T01:35:15 | 2021-02-26T01:35:15 | 177,007,645 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,261 | py | """
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
"""
class Codec:
# Encodes an n-ary tree to a binary tree.
def encode(self, root: 'Node') -> TreeNode:
if not root:
return None
new = TreeNode(root.val)
if not root.children:
return new
new.left = self.encode(root.children[0]) # node's children
node = new.left
for child in root.children[1:]: # node's sibling
node.right = self.encode(child)
node = node.right
return new
# Decodes your binary tree to an n-ary tree.
def decode(self, data: TreeNode) -> 'Node':
if not data:
return None
new = Node(data.val, [])
node = data.left
while node:
new.children.append(self.decode(node))
node = node.right
return new
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(root))
| [
"zhg26@pitt.edu"
] | zhg26@pitt.edu |
ffac4098afe441fcc5e4eb1ea93af766a908a7e1 | b8be7e196833a95b693465f173b75a36be407358 | /numpy_any.app.py | 58ebd5051830725ff97b133e906e2db36d16ac25 | [] | no_license | bogonets/answer-lambda-numpy | 08f7764a4ad9805c05d9a5fc4f85515c6929cf6e | 8a048c5d6d929067ef706c5d0521a45a5ff3b795 | refs/heads/master | 2022-12-08T21:02:40.087663 | 2020-08-27T01:36:06 | 2020-08-27T01:36:06 | 265,148,366 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 265 | py | # -*- coding: utf-8 -*-
# https://numpy.org/doc/stable/reference/generated/numpy.any.html
import numpy as np
def on_run(condition, data):
if np.any(condition):
return {'result': data}
else:
return {}
if __name__ == '__main__':
pass
| [
"osom8979@gmail.com"
] | osom8979@gmail.com |
637b713ff0a8fbc625aef4b16bbcaf8611510cef | 71f4bf9d92c548b442dc2667bca520c746b01481 | /ex5/assignment5.py | 85cf474fc659023ec4ea628229cb8ae2ec0377a2 | [] | no_license | vhellem/TDT4136 | 2eb3b1c7b55866a6732f160d01291a920f7cc37a | 071e00ae8bfa7f33b5454db809204ed3dd49efc3 | refs/heads/master | 2021-05-02T13:39:29.163862 | 2016-11-02T13:51:33 | 2016-11-02T13:51:33 | 72,644,520 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 10,760 | py | #!/usr/bin/python
import copy
import itertools
from glob import glob
class CSP:
def __init__(self):
# self.variables is a list of the variable names in the CSP
self.variables = []
# self.domains[i] is a list of legal values for variable i
self.domains = {}
# self.constraints[i][j] is a list of legal value pairs for
# the variable pair (i, j)
self.constraints = {}
self.backtrackingCalls = 0
self.backtrackingFailures = 0
def add_variable(self, name, domain):
"""Add a new variable to the CSP. 'name' is the variable name
and 'domain' is a list of the legal values for the variable.
"""
self.variables.append(name)
self.domains[name] = list(domain)
self.constraints[name] = {}
def get_all_possible_pairs(self, a, b):
"""Get a list of all possible pairs (as tuples) of the values in
the lists 'a' and 'b', where the first component comes from list
'a' and the second component comes from list 'b'.
"""
return itertools.product(a, b)
def get_all_arcs(self):
"""Get a list of all arcs/constraints that have been defined in
the CSP. The arcs/constraints are represented as tuples (i, j),
indicating a constraint between variable 'i' and 'j'.
"""
return [ (i, j) for i in self.constraints for j in self.constraints[i] ]
def get_all_neighboring_arcs(self, var):
"""Get a list of all arcs/constraints going to/from variable
'var'. The arcs/constraints are represented as in get_all_arcs().
"""
return [ (i, var) for i in self.constraints[var] ]
def add_constraint_one_way(self, i, j, filter_function):
"""Add a new constraint between variables 'i' and 'j'. The legal
values are specified by supplying a function 'filter_function',
that returns True for legal value pairs and False for illegal
value pairs. This function only adds the constraint one way,
from i -> j. You must ensure that the function also gets called
to add the constraint the other way, j -> i, as all constraints
are supposed to be two-way connections!
"""
if not j in self.constraints[i]:
# First, get a list of all possible pairs of values between variables i and j
self.constraints[i][j] = self.get_all_possible_pairs(self.domains[i], self.domains[j])
# Next, filter this list of value pairs through the function
# 'filter_function', so that only the legal value pairs remain
self.constraints[i][j] = filter(lambda value_pair: filter_function(*value_pair), self.constraints[i][j])
def add_all_different_constraint(self, variables):
"""Add an Alldiff constraint between all of the variables in the
list 'variables'.
"""
for (i, j) in self.get_all_possible_pairs(variables, variables):
if i != j:
self.add_constraint_one_way(i, j, lambda x, y: x != y)
def backtracking_search(self):
"""This functions starts the CSP solver and returns the found
solution.
"""
# Make a so-called "deep copy" of the dictionary containing the
# domains of the CSP variables. The deep copy is required to
# ensure that any changes made to 'assignment' does not have any
# side effects elsewhere.
assignment = copy.deepcopy(self.domains)
# Run AC-3 on all constraints in the CSP, to weed out all of the
# values that are not arc-consistent to begin with
self.inference(assignment, self.get_all_arcs())
# Call backtrack with the partial assignment 'assignment'
return self.backtrack(assignment)
def backtrack(self, assignment):
"""The function 'Backtrack' from the pseudocode in the
textbook.
The function is called recursively, with a partial assignment of
values 'assignment'. 'assignment' is a dictionary that contains
a list of all legal values for the variables that have *not* yet
been decided, and a list of only a single value for the
variables that *have* been decided.
When all of the variables in 'assignment' have lists of length
one, i.e. when all variables have been assigned a value, the
function should return 'assignment'. Otherwise, the search
should continue. When the function 'inference' is called to run
the AC-3 algorithm, the lists of legal values in 'assignment'
should get reduced as AC-3 discovers illegal values.
IMPORTANT: For every iteration of the for-loop in the
pseudocode, you need to make a deep copy of 'assignment' into a
new variable before changing it. Every iteration of the for-loop
should have a clean slate and not see any traces of the old
assignments and inferences that took place in previous
iterations of the loop.
"""
self.backtrackingCalls += 1
if self.completed_assignment(assignment):
return assignment
var = self.select_unassigned_variable(assignment)
for value in assignment[var]:
new_assignment = copy.deepcopy(assignment)
new_assignment[var] = [value]
if self.inference(new_assignment, self.get_all_neighboring_arcs(var)):
#If the assignment yields no conflicts with the board - continue with the search
result = self.backtrack(new_assignment)
if result:
return result
self.backtrackingFailures += 1
return False
def completed_assignment(self, assignment):
for key in assignment:
if len(assignment[key]) > 1:
return False
return True
def select_unassigned_variable(self, assignment):
"""The function 'Select-Unassigned-Variable' from the pseudocode
in the textbook. Should return the name of one of the variables
in 'assignment' that have not yet been decided, i.e. whose list
of legal values has a length greater than one.
"""
#Returns the variable with the largest domain
#return max(assignment.keys(), key=lambda key: len(assignment[key]))
#Returns variable with smallest legal domain
return min( {k: assignment[k] for k in assignment.keys() if len(assignment[k])>1}, key=lambda key: len(assignment[key]))
def inference(self, assignment, queue):
"""The function 'AC-3' from the pseudocode in the textbook.
'assignment' is the current partial assignment, that contains
the lists of legal values for each undecided variable. 'queue'
is the initial queue of arcs that should be visited.
"""
while queue:
x1, x2 = queue.pop()
if self.revise(assignment, x1, x2):
if not len(assignment[x1]):
return False
for x3, _ in self.get_all_neighboring_arcs(x1):
if x3 != x2:
queue.append((x3, x1))
return True
def revise(self, assignment, i, j):
"""The function 'Revise' from the pseudocode in the textbook.
'assignment' is the current partial assignment, that contains
the lists of legal values for each undecided variable. 'i' and
'j' specifies the arc that should be visited. If a value is
found in variable i's domain that doesn't satisfy the constraint
between i and j, the value should be deleted from i's list of
legal values in 'assignment'.
"""
foundInconsistency = []
for valueX in assignment[i]:
isPossibleValue = False
for valueY in assignment[j]:
if (valueX, valueY) in self.constraints[i][j]:
isPossibleValue=True
break
if not isPossibleValue:
foundInconsistency.append(valueX)
for x in foundInconsistency:
assignment[i].remove(x)
return len(foundInconsistency)>0
def create_map_coloring_csp():
"""Instantiate a CSP representing the map coloring problem from the
textbook. This can be useful for testing your CSP solver as you
develop your code.
"""
csp = CSP()
states = [ 'WA', 'NT', 'Q', 'NSW', 'V', 'SA', 'T' ]
edges = { 'SA': [ 'WA', 'NT', 'Q', 'NSW', 'V' ], 'NT': [ 'WA', 'Q' ], 'NSW': [ 'Q', 'V' ] }
colors = [ 'red', 'green', 'blue' ]
for state in states:
csp.add_variable(state, colors)
for state, other_states in edges.items():
for other_state in other_states:
csp.add_constraint_one_way(state, other_state, lambda i, j: i != j)
csp.add_constraint_one_way(other_state, state, lambda i, j: i != j)
return csp
def create_sudoku_csp(filename):
"""Instantiate a CSP representing the Sudoku board found in the text
file named 'filename' in the current directory.
"""
csp = CSP()
board = map(lambda x: x.strip(), open(filename, 'r'))
for row in range(9):
for col in range(9):
if board[row][col] == '0':
csp.add_variable('%d-%d' % (row, col), map(str, range(1, 10)))
else:
csp.add_variable('%d-%d' % (row, col), [ board[row][col] ])
for row in range(9):
csp.add_all_different_constraint([ '%d-%d' % (row, col) for col in range(9) ])
for col in range(9):
csp.add_all_different_constraint([ '%d-%d' % (row, col) for row in range(9) ])
for box_row in range(3):
for box_col in range(3):
cells = []
for row in range(box_row * 3, (box_row + 1) * 3):
for col in range(box_col * 3, (box_col + 1) * 3):
cells.append('%d-%d' % (row, col))
csp.add_all_different_constraint(cells)
return csp
def print_sudoku_solution(solution):
"""Convert the representation of a Sudoku solution as returned from
the method CSP.backtracking_search(), into a human readable
representation.
"""
for row in range(9):
for col in range(9):
print solution['%d-%d' % (row, col)][0],
if col == 2 or col == 5:
print '|',
print
if row == 2 or row == 5:
print '------+-------+------'
for file in glob("sudokus/*"):
print(file)
sudoku = create_sudoku_csp(file)
assignment = sudoku.backtracking_search()
print_sudoku_solution(assignment)
print "Failures: " + str(sudoku.backtrackingFailures)
print "Backtrack calls: " + str(sudoku.backtrackingCalls)
| [
"vhellem@gmail.com"
] | vhellem@gmail.com |
6ca88a0dbb97f37b2015940e3978efcb9c8a9f0b | bfc25f1ad7bfe061b57cfab82aba9d0af1453491 | /data/external/repositories_2to3/132160/kaggle-ndsb-master/configurations/bagging_27_convroll5_preinit_drop@420.py | 15acaee9e4b2e5862cb947b90c641219ff778759 | [
"MIT"
] | permissive | Keesiu/meta-kaggle | 77d134620ebce530d183467202cf45639d9c6ff2 | 87de739aba2399fd31072ee81b391f9b7a63f540 | refs/heads/master | 2020-03-28T00:23:10.584151 | 2018-12-20T19:09:50 | 2018-12-20T19:09:50 | 147,406,338 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 5,904 | py | import numpy as np
import theano
import theano.tensor as T
import lasagne as nn
import data
import load
import nn_plankton
import dihedral
import tmp_dnn
import tta
pre_init_path = "CONVROLL4_MODEL_FILE"
validation_split_path = "splits/bagging_split_27.pkl"
patch_size = (95, 95)
augmentation_params = {
'zoom_range': (1 / 1.6, 1.6),
'rotation_range': (0, 360),
'shear_range': (-20, 20),
'translation_range': (-10, 10),
'do_flip': True,
'allow_stretch': 1.3,
}
batch_size = 128 // 4
chunk_size = 32768 // 4
num_chunks_train = 580
momentum = 0.9
learning_rate_schedule = {
0: 0.003,
420: 0.0003,
540: 0.00003,
}
validate_every = 20
save_every = 20
def estimate_scale(img):
return np.maximum(img.shape[0], img.shape[1]) / 85.0
# augmentation_transforms_test = []
# for flip in [True, False]:
# for zoom in [1/1.3, 1/1.2, 1/1.1, 1.0, 1.1, 1.2, 1.3]:
# for rot in np.linspace(0.0, 360.0, 5, endpoint=False):
# tf = data.build_augmentation_transform(zoom=(zoom, zoom), rotation=rot, flip=flip)
# augmentation_transforms_test.append(tf)
augmentation_transforms_test = tta.build_quasirandom_transforms(70, **{
'zoom_range': (1 / 1.4, 1.4),
'rotation_range': (0, 360),
'shear_range': (-10, 10),
'translation_range': (-8, 8),
'do_flip': True,
'allow_stretch': 1.2,
})
data_loader = load.ZmuvRescaledDataLoader(estimate_scale=estimate_scale, num_chunks_train=num_chunks_train,
patch_size=patch_size, chunk_size=chunk_size, augmentation_params=augmentation_params,
augmentation_transforms_test=augmentation_transforms_test, validation_split_path=validation_split_path)
# Conv2DLayer = nn.layers.cuda_convnet.Conv2DCCLayer
# MaxPool2DLayer = nn.layers.cuda_convnet.MaxPool2DCCLayer
Conv2DLayer = tmp_dnn.Conv2DDNNLayer
MaxPool2DLayer = tmp_dnn.MaxPool2DDNNLayer
def build_model():
l0 = nn.layers.InputLayer((batch_size, 1, patch_size[0], patch_size[1]))
l0c = dihedral.CyclicSliceLayer(l0)
l1a = Conv2DLayer(l0c, num_filters=32, filter_size=(3, 3), border_mode="same", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu)
l1b = Conv2DLayer(l1a, num_filters=16, filter_size=(3, 3), border_mode="same", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu)
l1 = MaxPool2DLayer(l1b, ds=(3, 3), strides=(2, 2))
l1r = dihedral.CyclicConvRollLayer(l1)
l2a = Conv2DLayer(l1r, num_filters=64, filter_size=(3, 3), border_mode="same", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu)
l2b = Conv2DLayer(l2a, num_filters=32, filter_size=(3, 3), border_mode="same", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu)
l2 = MaxPool2DLayer(l2b, ds=(3, 3), strides=(2, 2))
l2r = dihedral.CyclicConvRollLayer(l2)
l3a = Conv2DLayer(l2r, num_filters=128, filter_size=(3, 3), border_mode="same", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu, untie_biases=True)
l3b = Conv2DLayer(l3a, num_filters=128, filter_size=(3, 3), border_mode="same", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu, untie_biases=True)
l3c = Conv2DLayer(l3b, num_filters=64, filter_size=(3, 3), border_mode="same", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu, untie_biases=True)
l3 = MaxPool2DLayer(l3c, ds=(3, 3), strides=(2, 2))
l3r = dihedral.CyclicConvRollLayer(l3)
l4a = Conv2DLayer(l3r, num_filters=256, filter_size=(3, 3), border_mode="same", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu, untie_biases=True)
l4b = Conv2DLayer(l4a, num_filters=256, filter_size=(3, 3), border_mode="same", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu, untie_biases=True)
l4c = Conv2DLayer(l4b, num_filters=128, filter_size=(3, 3), border_mode="same", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu, untie_biases=True)
l4 = MaxPool2DLayer(l4c, ds=(3, 3), strides=(2, 2))
l4r = dihedral.CyclicConvRollLayer(l4)
l5a = Conv2DLayer(l4r, num_filters=256, filter_size=(3, 3), border_mode="same", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu, untie_biases=True)
l5b = Conv2DLayer(l5a, num_filters=256, filter_size=(3, 3), border_mode="same", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu, untie_biases=True)
l5c = Conv2DLayer(l5b, num_filters=128, filter_size=(3, 3), border_mode="same", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu, untie_biases=True)
l5 = MaxPool2DLayer(l5c, ds=(3, 3), strides=(2, 2))
l5r = dihedral.CyclicConvRollLayer(l5)
l5f = nn.layers.flatten(l5r)
l6 = nn.layers.DenseLayer(nn.layers.dropout(l5f, p=0.5), num_units=256, W=nn_plankton.Orthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu)
l6r = dihedral.CyclicRollLayer(l6)
l7 = nn.layers.DenseLayer(nn.layers.dropout(l6r, p=0.5), num_units=256, W=nn_plankton.Orthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu)
l7m = dihedral.CyclicPoolLayer(l7, pool_function=nn_plankton.rms)
l8 = nn.layers.DenseLayer(nn.layers.dropout(l7m, p=0.5), num_units=data.num_classes, nonlinearity=T.nnet.softmax, W=nn_plankton.Orthogonal(1.0))
l_resume = l2
l_exclude = l2
return [l0], l8, l_resume, l_exclude
| [
"keesiu.wong@gmail.com"
] | keesiu.wong@gmail.com |
6a66f2962c4fd9197005b16fd3cd880738f7107b | dde885ca28d045f3fb015a2c04abac00d99ff871 | /tweets.py | 6f62778d7f2e207e61023530c974383e462136bb | [] | no_license | FrankPfirmann/MdB_SPN | e4d28c8534b2f3de7f7b362ff923637945ec4f97 | 06f1d750a47b70ddc8b5127c286a551f20ac62c4 | refs/heads/master | 2023-03-27T22:27:15.975148 | 2021-04-01T07:16:04 | 2021-04-01T07:16:04 | 353,059,336 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,371 | py | import pickle
import tweepy as tw
class BTTweet(object):
def __init__(self, text, id, retweets, favorites, created_at):
self.text = text
self.id = id
self.retweets = retweets
self.favorites = favorites
self.created_at = created_at
def load_tweet_list(filename):
with open(filename, "rb") as f:
tweet_list = pickle.load(f)
f.close()
return tweet_list
def tweet_scraping(tweet_list, api, filename):
for t in tweet_list:
try:
a = api.user_timeline(t[0], count=100, max_id=t[1], exclude_replies=True, include_rts=False)
for tweet in a:
t[2].append(BTTweet(tweet.text, tweet.id, tweet.retweet_count, tweet.favorite_count, tweet.created_at))
if len(t[2]) != 0:
t[1] = min(t[1], t[2][-1].id)
for p in t[2]:
print(p.text)
with open(filename, "wb") as f:
pickle.dump(tweet_list, f)
except tw.error.TweepError:
pass
def create_tweet_list(memberlist, filename="bttweets.dat"):
tweet_list = []
for member in memberlist:
#store tweet_list as tuple of name, id of latest tweet and the tweets themselves
tweet_list.append([member.name, 1373895723381587970, []])
with open(filename, "wb") as f:
pickle.dump(tweet_list, f)
| [
"pfirmannf@web.de"
] | pfirmannf@web.de |
6ceb9d1a80663a73976e941ebaa5c6143e75a5ce | c7e9ec5ce6627f6f68bab1b86a27a4516595154d | /consentrecords/migrations/0089_auto_20180123_2226.py | 738533784e45a55c62c2542c2229561d9a774b5b | [] | no_license | michaelcrubenstein/consentrecords | 7b79e82c9ad4b5efcfbb44a50ff1d4cadf7180e2 | 992fe78c68d1d5c083f9e2cc0e3e9aa24363b93d | refs/heads/master | 2021-01-23T19:28:13.807809 | 2018-07-03T16:10:34 | 2018-07-03T16:10:34 | 41,223,029 | 1 | 1 | null | 2018-07-03T16:10:35 | 2015-08-22T20:21:26 | JavaScript | UTF-8 | Python | false | false | 700 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2018-01-23 22:26
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('consentrecords', '0088_auto_20171227_2107'),
]
operations = [
migrations.RemoveField(
model_name='experience',
name='timeframe',
),
migrations.RemoveField(
model_name='experiencehistory',
name='timeframe',
),
migrations.AlterField(
model_name='experience',
name='era',
field=models.IntegerField(db_index=True, null=True),
),
]
| [
"michaelcrubenstein@gmail.com"
] | michaelcrubenstein@gmail.com |
0fe411a821c9c8d033e284c43fba39a10774bbb9 | 4a1273f72e7d8a07a3fa67ac9f2709b64ec6bc18 | /retiresmartz/advice_responses.py | 73223c61a7c14be764d3ae4c699eb9fc19d26e8d | [] | no_license | WealthCity/django-project | 6668b92806d8c61ef9e20bd42daec99993cd25b2 | fa31fa82505c3d0fbc54bd8436cfc0e49c896f3e | refs/heads/dev | 2021-01-19T14:10:52.115301 | 2017-04-12T11:23:32 | 2017-04-12T11:23:32 | 88,132,284 | 0 | 1 | null | 2017-04-13T06:26:30 | 2017-04-13T06:26:29 | null | UTF-8 | Python | false | false | 12,283 | py | # -*- coding: utf-8 -*-
from main import constants
from datetime import datetime
import logging
logger = logging.getLogger('api.v1.retiresmartz.advice_responses')
# Retiresmartz Advice feed Logic Calls
# On Track / Off Track
def get_on_track(advice):
return 'If you would like to change any of your retirement details \
you can do so by clicking on the items on this or the previous screen.'
def get_off_track(advice):
return 'I recommend changing some of your retirement details \
by clicking on this or the previous screen. This will help you \
to plan to be on track to a better retirement.'
# Change Retirement Age
def get_decrease_retirement_age_to_62(advice):
# TODO: Need to insert social security benefit in data
# By increasing your retirement age to 70 your social \
# security benefit would be estimated to be <estimated SS benefit \
# multiplied by inflator>
return "I see you have decreased your retirement age \
to 62. This will reduce your monthly benefit by 25% compared \
to if you retired at 66 giving you an estimated social security \
benefit of ${:,.2f} per month instead of ${:,.2f} if you chose to retire \
at 66. Social security benefits increase by up to 132% the longer \
you work.".format(advice.plan.spendable_income - (advice.plan.spendable_income * .25), advice.plan.spendable_income)
def get_decrease_retirement_age_to_63(advice):
# TODO: Need to insert social security benefit in data
# By increasing your retirement age to 70 \
# your social security benefit would be estimated to be \
# <estimated SS benefit multiplied by inflator>
return "I see you have decreased your retirement age to 63. \
This will reduce your monthly benefit by 20% compared to if \
you retired at 66 giving you an estimated social security \
benefit of ${:,.2f} per month instead of ${:,.2f} if you chose to \
retire at 66. Social security benefits increase by up to 132% \
the longer you work.".format(advice.plan.spendable_income - (advice.plan.spendable_income * .2), advice.plan.spendable_income)
def get_decrease_retirement_age_to_64(advice):
# TODO: Need to insert social security benefit in data\
# By increasing your retirement age to 70 \
# your social security benefit would be estimated to be \
# <estimated SS benefit multiplied by inflator>
return "I see you have decreased your retirement age to 64. \
This will reduce your monthly benefit by 13% compared to \
if you retired at 66 giving you an estimated social security \
benefit of ${:,.2f} per month instead of ${:,.2f} if you chose to \
retire at 66. Social security benefits increase by up to 132% \
the longer you work.".format(advice.plan.spendable_income - (advice.plan.spendable_income * .13), advice.plan.spendable_income)
def get_decrease_retirement_age_to_65(advice):
# TODO: Need to insert social security benefit in data
# By increasing your retirement age to 70 \
# your social security benefit would be estimated
# to be <estimated SS benefit multiplied by inflator>
return "I see you have decreased your retirement age to 65. \
This will reduce your monthly benefit by 7% compared to if \
you retired at 66 giving you an estimated social security \
benefit of ${:,.2f} per month instead of ${:,.2f} if you chose to \
retire at 66. Social security benefits increase by up to 132% \
the longer you work.".format(advice.plan.spendable_income - (advice.plan.spendable_income * .07), advice.plan.spendable_income)
def get_increase_retirement_age_to_67(advice):
# TODO: Need to insert social security benefit in data
return "I see you have increased your retirement age to 67. \
This will increase your monthly benefit by 8% of ${:,.2f} per \
month instead of ${:,.2f} if you chose to retire at 66. Increasing \
your retirement age will adjust the amount of social security \
benefits that you are able to obtain. Social security benefits \
increase by up to 132% the longer you work.".format(advice.plan.spendable_income + (advice.plan.spendable_income * .08), advice.plan.spendable_income)
def get_increase_retirement_age_to_68(advice):
# TODO: Need to insert social security benefit in data
return "I see you have increased your retirement age to 68. \
This will increase your monthly benefit by 16% of ${:,.2f} per \
month instead of ${:,.2f} if you chose to retire at 66. Increasing \
your retirement age will adjust the amount of social security \
benefits that you are able to obtain. Social security benefits \
increase by up to 132% the longer you work.".format(advice.plan.spendable_income + (advice.plan.spendable_income * .16), advice.plan.spendable_income)
def get_increase_retirement_age_to_69(advice):
# TODO: Need to insert social security benefit in data
return "I see you have increased your retirement age to 69. \
This will increase your monthly benefit by 24% of ${:,.2f} per \
month instead of ${:,.2f} if you chose to retire at 66. Increasing \
your retirement age will adjust the amount of social security \
benefits that you are able to obtain. Social security benefits \
increase by up to 132% the longer you work.".format(advice.plan.spendable_income + (advice.plan.spendable_income * .24), advice.plan.spendable_income)
def get_increase_retirement_age_to_70(advice):
# TODO: Need to insert social security benefit in data
return "I see you have increased your retirement age to 70. \
This will increase your monthly benefit by 32% of ${:,.2f} per \
month instead of ${:,.2f} if you chose to retire at 66. Increasing \
your retirement age will adjust the amount of social security \
benefits that you are able to obtain. Social security benefits \
increase by up to 132% the longer you work.".format(advice.plan.spendable_income + (advice.plan.spendable_income * .32), advice.plan.spendable_income)
# Life Expectancy
def get_manually_adjusted_age(advice):
return 'Your retirement age has been updated. \
Let us know if anything else changes in your wellbeing \
profile by clicking on the life expectancy bubble.'
def get_smoking_yes(advice):
return 'You could improve your life expectancy score \
by quitting smoking. Do you intend to quit smoking in \
the near future? Yes/No'
def get_quitting_smoking(advice):
# {formula = (Current Age – 18)/42]*7.7 or 7.3 years}
formula = ((advice.plan.client.age - 18) / 42) * 7.7
return "We will add this to your life expectancy. \
Based on your age we will add {} years to your life expectancy.".format(formula)
def get_smoking_no(advice):
return "By not smoking you're already increasing your \
life expectancy by 7 years."
def get_exercise_only(advice):
return "Thanks for telling us about your exercise. Exercise \
does impact your life expectancy. Regular exercise for at \
least 20 minutes each day 5 times a week increases your \
life expectancy by up to 3.2 years."
def get_weight_and_height_only(advice):
return "Thanks for telling us your weight and height. \
These combined details help us better understand your life expectancy."
def get_combination_of_more_than_one_entry_but_not_all(advice):
return "Thanks for providing more wellbeing information. This helps us \
better understand your life expectancy. By completing all of the \
details we can get an even more accurate understanding."
def get_all_wellbeing_entries(advice):
return "Thanks for providing your wellbeing information. This gives us \
the big picture and an accurate understanding of your life expectancy."
# Risk Slider
def get_protective_move(advice):
# TODO: Need to add risk and amounts
"""
This might reduce the returns from your portfolio or increase \
the amount you need to contribute from your paycheck each month \
from <previous amount> to <new amount>
"""
risk = round(advice.plan.recommended_risk, 2)
if risk == 1.0:
risk = 100
elif risk == 0.9:
risk = 90
elif risk == 0.8:
risk = 80
elif risk == 0.7:
risk = 70
elif risk == 0.6:
risk = 60
elif risk == 0.5:
risk == 50
elif risk == 0.4:
risk == 40
elif risk == 0.3:
risk = 30
elif risk == 0.2:
risk = 20
elif risk == 0.1:
risk = 10
else:
risk = str(risk)[2:]
return "I can see you have adjusted your risk profile to be more \
protective. We base your risk profile on the risk questionnaire \
you completed and recommended {}. By adjusting the slider you \
change the asset allocation in your retirement goal.".format(str(risk))
def get_dynamic_move(advice):
# TODO: Need to add risk and amounts
"""
This might increase the returns from your portfolio and decrease the amount \
you need to contribute from your paycheck each month from <previous amount> \
to <new amount>
"""
risk = round(advice.plan.recommended_risk, 2)
if risk == 1.0:
risk = 100
elif risk == 0.9:
risk = 90
elif risk == 0.8:
risk = 80
elif risk == 0.7:
risk = 70
elif risk == 0.6:
risk = 60
elif risk == 0.5:
risk == 50
elif risk == 0.4:
risk == 40
elif risk == 0.3:
risk = 30
elif risk == 0.2:
risk = 20
elif risk == 0.1:
risk = 10
else:
risk = str(risk)[2:]
return "I can see you have adjusted your risk profile to be more dynamic. \
We base your risk profile on the risk questionnaire you completed and \
recommended {}. By adjusting the slider you change the asset allocation \
in your retirement goal.\nYou will be taking more risk.".format(str(risk))
# Contributions / Spending
def get_increase_spending_decrease_contribution(advice, contrib, income):
# TODO: Need to add $X and $Y calculations, max_contributions needs to come in
# if advice.plan.client.account.account_type == constants.ACCOUNT_TYPE_401K or \
# advice.plan.client.account.account_type == constants.ACCOUNT_TYPE_ROTH401K:
# # [If 401K we need to remember here that for a person under 50 the
# # maximum contribution amount is $18,000 per annum and $24,000
# # if they are over 50]
# if advice.plan.client.age < 50:
# max_contribution = 18000
# else:
# max_contribution = 24000
rv = "Hey big spender! I can see you want to spend a bit more. \
If you decreased your spending by ${:,.2f} a week, you could increase your\
retirement income by ${:,.2f} a week.".format(contrib, income)
if advice.plan.client.employment_status == constants.EMPLOYMENT_STATUS_FULL_TIME or \
advice.plan.client.employment_status == constants.EMPLOYMENT_STATUS_PART_TIME:
rv += " Your employer will match these contributions making it easier to reach your goal."
return rv
def get_increase_contribution_decrease_spending(advice, contrib, income):
return "Well done, by increasing your retirement contributions to ${:,.2f} \
a month, you have increased your retirement income by ${:,.2f} a week.".format(contrib, income)
def get_increase_spending_decrease_contribution_again(advice, contrib, income):
# TODO: Need to add $X and $Y calculations
return "Are you sure you need to increase your spending again and reduce your \
retirement contributions? Just think, if your contributions stayed \
at ${:,.2f} a month you would be ${:,.2f} a week better off in retirement.".format(contrib, income)
def get_off_track_item_adjusted_to_on_track(advice):
years = advice.plan.retirement_age - advice.plan.client.age
return "Well done, by adjusting your details your retirement goal is now on track.\n\
We want to make sure our advice keeps you on track so that when you retire \
in {} there are no nasty surprises. If you would like to change or see the \
impact of any of your choices you can make changes to your details on \
this dashboard.".format(datetime.now().date().year + years)
def get_on_track_item_adjusted_to_off_track(advice):
return "Uh oh, you are now off track to achieve your retirement goal. \
We are here to give you’re the advice to ensure you get on track. \
You may want to reconsider the changes you have made to your details \
to get your retirement goal back on track."
| [
"peterroth0612@gmail.com"
] | peterroth0612@gmail.com |
1010a87e378223fd5275560d3cf5ea3eb1d65f07 | 017f02454cbb5616a9aa23e3ce76f84832378ec2 | /inferencia/task/pose_estimation/pose_estimation_2d/visualization/pose_estimation_2d_visualizer_factory.py | 451d1b7a92d7c0e6f4d200bafdc3e7bc2a2a02e1 | [
"Apache-2.0"
] | permissive | hampen2929/inferencia | a6e0f0b25abe95c3690ddfc7a225d4a4bdc2cb10 | c83563ff31d47cd441bb8ac3072df32a7fded0ee | refs/heads/main | 2023-08-18T13:53:32.882725 | 2021-09-18T12:15:52 | 2021-09-18T12:15:52 | 379,299,225 | 0 | 2 | Apache-2.0 | 2021-09-18T12:15:53 | 2021-06-22T14:30:36 | Jupyter Notebook | UTF-8 | Python | false | false | 813 | py | from .pose_estimation_2d_visualizer_name import PoseEstimation2DVisualizerName
from ..label.pose_estimation_2d_label_factory import PoseEstimation2DLabelFactory
class PoseEstimation2DVisualizerFactory():
def create(visualizer_name="PoseVisualizer",
label_name="COCOKeyPointLabel"):
if visualizer_name == PoseEstimation2DVisualizerName.pose_visualizer.value:
from .visualization.pose_vilualizer import PoseVilualizer
pose_label = PoseEstimation2DLabelFactory.create(
label_name=label_name)
pose_visualizer = PoseVilualizer(body_edges=pose_label.body_edges)
return pose_visualizer
else:
msg = "{} is not implemented".format(
visualizer_name)
raise NotImplementedError(msg)
| [
"mochi.no.kimochi.2929@gmail.com"
] | mochi.no.kimochi.2929@gmail.com |
d3ee02507c3e1f4e4e559d2b4bc620f04d542247 | d21be3f7b8680a4395a0b39762f26d3fa9b98eb1 | /lab9_problem4.py | 79dc742d4c7bd8ab899635e1c117c64cad7e157a | [] | no_license | Indra-Ratna/LAB9-1114 | e8dc3cd518fea84464ae8e4a4b3bb04c0ccdf980 | b730735a83edb5bf4802fa5c158d7a8c4162ca98 | refs/heads/master | 2020-04-14T16:07:20.961360 | 2019-01-03T08:23:28 | 2019-01-03T08:23:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 221 | py | #Indra Ratna
#CS-UY 1114
#2 Nov 2018
#Lab 9
#Problem 4
def mycount(lst,n):
count=0
for element in lst:
if(element == n):
count+=1
return count
print(mycount([7,2,1,3,7,9],7))
| [
"noreply@github.com"
] | Indra-Ratna.noreply@github.com |
fc20d1f4d186620b7c2e5048f92e41e08ee9a0c9 | b85f8be457512c6ad137a56f332bd65a64f314c4 | /crawl_sinmungo.py | 7c000baaebb5939570db6c30c6a9a62b5a36c125 | [] | no_license | dev-Lesser/sinmungo-crawl-ray | 87d1f2c7cbd11dc6f01b0ea58d53646cd26f61b7 | 142e298a596afcf262f16fc4f82b8a7b2d56ccd5 | refs/heads/master | 2023-05-29T01:28:38.444226 | 2021-06-18T00:14:11 | 2021-06-18T00:14:11 | 375,435,338 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 5,531 | py | import ray # 분산처리
import requests
import re
from lxml import html
import pandas as pd
@ray.remote
def start_crawl_sinmungo(i=0,page=20, cookie='JSESSIONID=b0yitmMBpWWbf2jX9VX83+9d.euser22'):
url = 'https://www.epeople.go.kr/nep/pttn/gnrlPttn/pttnSmlrCaseList.npaid' # 건의 리스트 url
detail_url = 'https://www.epeople.go.kr/nep/pttn/gnrlPttn/pttnSmlrCaseDetail.npaid' # 건의 1개의 내용관련 url
title_list = []
agency_list = []
date_list = []
question_list = []
answer_list = []
status_code_list = []
form_data = {
'pageIndex':i,
'rqstStDt': '2014-01-01', # 원하는 기간 설정
'rqstEndDt': '2021-06-10',
'recordCountPerPage': page
}
headers={
'Cookie':cookie
}
# 신문고 건의 리스트 가져오기
res = requests.post(url,headers=headers, data=form_data)
root = html.fromstring(res.text.strip())
rows = root.xpath('//table[contains(@class, tbl)]/tbody/tr')
# 건의 타이틀
title = [i.xpath('.//td[@class="left"]/a/text()')[0] for i in rows]
result = [i.xpath('.//td/text()') for i in rows]
title_list += title
# 처리기관
agency = [i[1] for i in result]
agency_list += agency
# 등록일
date = [i[2] for i in result]
date_list+= date
# 내용을 가져오기 위한 코드들 저장
detail_code = [re.sub('javaScript:fn_detail|;|\(|\)|\'','',i.xpath('.//td/a/@onclick')[0]) for i in rows] # contents
ep_union_sn,duty_sctn_nm = [],[]
for code in detail_code:
sn, nm =tuple(map(str, code.split(',')))[1:]
ep_union_sn.append(sn)
duty_sctn_nm.append(nm)
for idx in range(page):
headers={
'Cookie':cookie
}
form_data = {
'epUnionSn': ep_union_sn[idx],
'rqstStDt': '2014-01-01', # 원하는 기간 설정
'rqstEndDt': '2021-06-10',
'dutySctnNm':duty_sctn_nm[idx],
'_csrf': '721218f9-e01d-4f4f-ab43-c1cd55b3cbda' # csrf 와 cookie 값은 403에러가 떴을 때 변경 필요 > TODO 자동화
}
res = requests.post(detail_url, headers=headers, data=form_data)
if res.status_code ==200:
# 신문고 민원 사이트가 들어가지면
root=html.fromstring(res.text.strip())
# 질문 내용
question_content = ' '.join([i.strip() for i in root.xpath('//div[@class="samC_c"]/text()')])
# 답변 내용
answer = ' '.join([i.strip() for i in root.xpath(
'//div[@class="samBox ans"]'+
'/div[@class="sam_cont"]'+\
'/div[@class="samC_top"]/*/text()|//div[@class="samBox ans"]'+
'/div[@class="sam_cont"]'+\
'/div[@class="samC_top"]/text()|div[@class="samBox ans"]'+
'/div[@class="sam_cont"]'+\
'/div[@class="samC_top"]/span/span/span/text()')]).replace(u'\xa0', u' ')
question_list.append(question_content)
answer_list.append(answer)
status_code_list.append(res.status_code)
elif res.status_code ==500:
# 비공개 처리로 들어가지 못할때
# 타이틀, 관련부처, 등록일만 저장, 질문내용, 답변내용은 None 으로
question_list.append(None)
answer_list.append(None)
status_code_list.append(res.status_code)
else:
# 그외 cookie 값 오류로 권한 에로 403 결과가 나올때, 쿠키,_csfr 변경해야함.
print('error {}'.format(res.status_code), title[idx])
return False
return [title_list,question_list,answer_list,agency_list,date_list,status_code_list]
if __name__ == '__main__':
ray.init()
error_idx=0
_range=1
while True:
try:
while _range < 5 :
print('Starting from {}\n'.format(_range))
error_idx = _range
results = [start_crawl_sinmungo.remote(i=idx, page=200) for idx in range(_range, 5+_range)]
contents = ray.get(results)
title_list, question_list, answer_list, agency_list, date_list, status_code_list = [],[],[],[],[],[]
for i in contents:
title_list += i[0]
question_list += i[1]
answer_list += i[2]
agency_list += i[3]
date_list += i[4]
status_code_list += i[5]
data = {
'title': title_list,
'question': question_list,
'answer': answer_list,
'agency': agency_list,
'datetime':date_list,
'status_code':status_code_list
}
df = pd.DataFrame(data)
filename = 'results_{}_{}.csv'.format(str(int((_range-1)/5*1000)).zfill(6), str(int((_range-1)/5*1000+1000)).zfill(6))
df.to_csv(filename, encoding='UTF8', index=False)
print('Finished crawl data number {} file {}'.format(len(df), filename))
_range+=5
except Exception:
print('error index {}'.format(error_idx),'\n restarting from {}'.format(error_idx))
continue
if error_idx+5 >500:
break
print('Finished ! {} data'.format((error_idx-1)*200))
| [
"dev.jongmoon@gmail.com"
] | dev.jongmoon@gmail.com |
2b06b12ac66fa7762e6d0e14a7937b36c20c2674 | 15c8b2cf8e08068c47b3925ee13650bdb9fe98ed | /Estamp Creation/estamp/verify.py | 353e59615e4a590331286638712aba4ad697ba18 | [] | no_license | sky-sarthak/E-Stamp-Creation-and-Verification | 39a0de8f0fa348f14e07e8c91e66a7ba7c203611 | bc5fe6311fbbaf22762ebdc49de386eda1b951db | refs/heads/master | 2020-04-19T23:15:40.875726 | 2019-01-31T08:55:10 | 2019-01-31T08:55:10 | 168,490,848 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,004 | py | import base64
import cryptography.exceptions
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.serialization import load_pem_public_key
# Load the public key.
with open('public.pem', 'rb') as f:
public_key = load_pem_public_key(f.read(), default_backend())
# Load the payload contents and the signature.
with open('text.pdf', 'rb') as f:
payload_contents = f.read()
with open('signature1.sig', 'rb') as f:
signature = base64.b64decode(f.read())
# Perform the verification.
try:
public_key.verify(
signature,
payload_contents,
padding.PSS(
mgf = padding.MGF1(hashes.SHA256()),
salt_length = padding.PSS.MAX_LENGTH,
),
hashes.SHA256(),
)
except cryptography.exceptions.InvalidSignature as e:
print('ERROR: Payload and/or signature files failed verification!')
| [
"noreply@github.com"
] | sky-sarthak.noreply@github.com |
f9fade661402627c5a7c12936bed53fbd8d25454 | 50e90ce3870a66395aa2f4abd6a03c7e7de811e6 | /mishamovie/pipeline_steps/combine_frames.py | f92b81a9ca8a11193857ab424569e84310ab838d | [] | no_license | jgc128/mishamovie | c8dd960756d1cef7504d6060d1d7ceca89869c91 | ce8864fb311bff4c0936046a7efe121b5e5f8a3b | refs/heads/main | 2023-06-08T21:28:30.605756 | 2021-07-04T20:59:32 | 2021-07-04T20:59:32 | 361,487,351 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,388 | py | """
This script trains a simple model Cats and Dogs dataset and saves it in the SavedModel format
"""
import argparse
import subprocess
def parse_args():
parser = argparse.ArgumentParser(description='Split video into frames')
parser.add_argument('--input_dir', help='Input dir', required=True)
parser.add_argument('--output_dir', help='Output dir', required=True)
parser.add_argument('--output_filename', help='Output file name', required=True)
parser.add_argument('--input_name_template', default='frame_%5d.png', help='Input name template', required=False)
parser.add_argument('--fps', default=30, type=int, help='Frames per second', required=False)
args = parser.parse_args()
return args
def main():
# TODO: fmpeg -i face_close_aged_long.mp4 -filter "minterpolate='fps=120'" zzzz3.mp4
# https://superuser.com/a/1185430
# https://github.com/dthpham/butterflow
args = parse_args()
print(args)
input_filename = f'{args.input_dir}/{args.input_name_template}'
output_filename = f'{args.output_dir}/{args.output_filename}'
cmd = [
'ffmpeg', '-y', '-framerate', str(args.fps), '-i', input_filename,
'-c:v', 'libx264', '-vf', f'fps={args.fps},pad=ceil(iw/2)*2:ceil(ih/2)*2', '-pix_fmt', 'yuv420p',
output_filename
]
subprocess.run(cmd, check=True)
if __name__ == '__main__':
main()
| [
"jgc128@outlook.com"
] | jgc128@outlook.com |
a195e2f96103faee8ee4c2d44d96c7ff269bbb2f | 31fb20acd57af064190f69a1d33ee9ac1ed6ab4e | /wxagent/qq2any.py | cbf852b1c37d5ceea350dcad73433731ec0775e0 | [] | no_license | kakliu/wxagent | 2ba27b531d4a07b4e059a37f4de03a663173ae1b | b7c5ea47d6616556b4d43eb81c61cf7ac3031c18 | refs/heads/master | 2020-05-27T02:29:27.621687 | 2016-11-13T13:19:04 | 2016-11-13T13:19:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 38,187 | py | # web qq protocol
import os, sys
import json, re
import enum
import time
from PyQt5.QtCore import *
from PyQt5.QtNetwork import *
from PyQt5.QtDBus import *
from .imrelayfactory import IMRelayFactory
from .qqcom import *
from .qqsession import *
from .unimessage import *
from .filestore import QiniuFileStore, VnFileStore
from .tx2any import TX2Any, Chatroom
#
#
#
class WX2Tox(TX2Any):
def __init__(self, parent=None):
"docstring"
super(WX2Tox, self).__init__(parent)
self.agent_service = QQAGENT_SERVICE_NAME
self.agent_service_path = QQAGENT_SEND_PATH
self.agent_service_iface = QQAGENT_IFACE_NAME
self.agent_event_path = QQAGENT_EVENT_BUS_PATH
self.agent_event_iface = QQAGENT_EVENT_BUS_IFACE
self.relay_src_pname = 'WQU'
self.initDBus()
self.initRelay()
self.startWXBot()
return
# @param msg str
def uicmdHandler(self, msg):
if msg[0] != "'":
qDebug('not a uicmd, normal msg, omit for now.')
return
if msg.startswith("'help"):
friendId = self.peerToxId
uicmds = ["'help", "'qqnum <num>", "'passwd <pwd[|vfcode]>'", ]
self.peerRelay.sendMessage("\n".join(uicmds), self.peerRelay.peer_user)
pass
elif msg.startswith("'qqnum"):
qqnum = msg[6:].strip()
qDebug('the qqnum is:' + str(qqnum))
self.sendQQNum(qqnum)
pass
elif msg.startswith("'passwd"):
passwd, *vfcode = msg[8:].strip().split('|')
if len(vfcode) == 0: vfcode.append(4567)
vfcode = vfcode[0]
self.sendPasswordAndVerify(passwd, vfcode)
pass
else:
qDebug('unknown uicmd:' + msg[0:120])
return
def startWXBot(self):
cstate = self.getConnState()
qDebug('curr conn state:' + str(cstate))
need_send_notify = False
notify_msg = ''
if cstate == CONN_STATE_NONE:
# do nothing
qDebug('wait for qqagent bootup...')
QTimer.singleShot(2345, self.startWXBot)
pass
elif cstate == CONN_STATE_WANT_USERNAME:
need_send_notify = True
notify_msg = "Input qqnum: ('qqnum <1234567>)"
pass
elif cstate == CONN_STATE_WANT_PASSWORD:
need_send_notify = True
notify_msg = "Input password: ('passwd <yourpassword>)"
pass
elif cstate == CONN_STATE_CONNECTED:
qDebug('qqagent already logined.')
self.createWXSession()
pass
else:
qDebug('not possible.')
pass
if need_send_notify is True:
# TODO 这里有一个时序问题,有可能self.peerRelay为None,即relay还没有完全启动
# time.sleep(1) # hotfix lsself.peerRelay's toxkit is None sometime.
tkc = self.peerRelay.isPeerConnected(self.peerRelay.peer_user)
if tkc is True:
self.peerRelay.sendMessage(notify_msg, self.peerRelay.peer_user)
else:
self.notify_buffer.append(notify_msg)
self.need_send_notify = True
self.sendQRToRelayPeer()
# if logined is True: self.createWXSession()
return
@pyqtSlot(QDBusMessage)
def onDBusWantQQNum(self, message):
qDebug(str(message.arguments()))
self.startWXBot() # TODO 替换成登陆状态机方法
return
# @param a0=needvfc
# @param a1=vfcpic
@pyqtSlot(QDBusMessage)
def onDBusWantPasswordAndVerifyCode(self, message):
qDebug(str(message.arguments()))
need_send_notify = False
notify_msg = ''
cstate = CONN_STATE_WANT_PASSWORD
assert(cstate == CONN_STATE_WANT_PASSWORD)
need_send_notify = True
notify_msg = "Input password: ('passwd <yourpassword>)"
if need_send_notify is True:
tkc = False
tkc = self.peerRelay.isPeerConnected(self.peerRelay.peer_user)
qDebug(str(tkc))
if tkc is True:
self.peerRelay.sendMessage(notify_msg, self.peerRelay.peer_user)
else:
self.notify_buffer.append(notify_msg)
self.need_send_notify = True
return
@pyqtSlot(QDBusMessage)
def onDBusNewMessage(self, message):
# qDebug(str(message.arguments()))
args = message.arguments()
msglen = args[0]
msghcc = args[1]
if self.txses is None: self.createWXSession()
for arg in args:
if type(arg) == int:
qDebug(str(type(arg)) + ',' + str(arg))
else:
qDebug(str(type(arg)) + ',' + str(arg)[0:120])
hcc64_str = args[1]
hcc64 = hcc64_str.encode('utf8')
hcc = QByteArray.fromBase64(hcc64)
self.saveContent('qqmsgfromdbus.json', hcc)
wxmsgvec = QQMessageList()
wxmsgvec.setMessage(hcc)
strhcc = hcc.data().decode('utf8')
qDebug(strhcc[0:120].replace("\n", "\\n"))
jsobj = json.JSONDecoder().decode(strhcc)
# temporary send to friend
# self.toxkit.sendMessage(self.peerToxId, strhcc)
#############################
# AddMsgCount = jsobj['AddMsgCount']
# ModContactCount = jsobj['ModContactCount']
# grnames = self.wxproto.parseWebSyncNotifyGroups(hcc)
# self.txses.addGroupNames(grnames)
# self.txses.parseModContact(jsobj['ModContactList'])
msgs = wxmsgvec.getContent()
for msg in msgs:
fromUser = self.txses.getUserByName(msg.FromUserName)
toUser = self.txses.getUserByName(msg.ToUserName)
# qDebug(str(fromUser))
# qDebug(str(toUser))
if fromUser is None: qDebug('can not found from user object')
if toUser is None: qDebug('can not found to user object')
msg.FromUser = fromUser
msg.ToUser = toUser
# hot fix file ack
# {'value': {'mode': 'send_ack', 'reply_ip': 183597272, 'time': 1444550216, 'type': 101, 'to_uin': 1449732709, 'msg_type': 10, 'session_id': 27932, 'from_uin': 1449732709, 'msg_id': 47636, 'inet_ip': 0, 'msg_id2': 824152}, 'poll_type': 'file_message'}
if msg.FromUserName == msg.ToUserName:
qDebug('maybe send_ack msg, but dont known how process it, just omit.')
continue
self.sendMessageToToxByType(msg)
return
def sendMessageToToxByType(self, msg):
umsg = self.peerRelay.unimsgcls.fromQQMessage(msg, self.txses)
logstr = umsg.get()
dlogstr = umsg.dget()
qDebug(dlogstr.encode())
if msg.isOffpic():
qDebug(msg.offpic)
self.sendShotPicMessageToTox(msg, logstr)
elif msg.isFileMsg():
qDebug(msg.FileName.encode())
self.sendFileMessageToTox(msg, logstr)
else:
self.sendMessageToTox(msg, logstr)
return
def dispatchToToxGroup(self, msg, fmtcc):
if msg.FromUserName == 'newsapp':
qDebug('special chat: newsapp')
self.dispatchNewsappChatToTox(msg, fmtcc)
pass
elif msg.ToUserName == 'filehelper' or msg.FromUserName == 'filehelper':
qDebug('special chat: filehelper')
self.dispatchFileHelperChatToTox(msg, fmtcc)
pass
elif msg.PollType == QQ_PT_SESSION:
qDebug('qq sess chat')
self.dispatchQQSessChatToTox(msg, fmtcc)
pass
elif msg.FromUser.isGroup() or msg.ToUser.isGroup():
# msg.ToUserName.startswith('@@') or msg.FromUserName.startswith('@@'):
qDebug('wx group chat:')
# wx group chat
self.dispatchWXGroupChatToTox(msg, fmtcc)
pass
else:
qDebug('u2u group chat:')
# user <=> user
self.dispatchU2UChatToTox(msg, fmtcc)
pass
return
def dispatchNewsappChatToTox(self, msg, fmtcc):
groupchat = None
mkey = None
title = ''
mkey = 'newsapp'
title = 'newsapp@WQU'
if mkey in self.txchatmap:
groupchat = self.txchatmap[mkey]
# assert groupchat is not None
# 有可能groupchat已经就绪,但对方还没有接收请求,这时发送失败,消息会丢失
number_peers = self.peerRelay.groupNumberPeers(groupchat.group_number)
if number_peers < 2:
groupchat.unsend_queue.append(fmtcc)
### reinvite peer into group
self.peerRelay.groupInvite(groupchat.group_number, self.peerRelay.peer_user)
else:
self.peerRelay.sendGroupMessage(fmtcc, groupchat.group_number)
else:
groupchat = self.createChatroom(msg, mkey, title)
groupchat.unsend_queue.append(fmtcc)
return
def dispatchFileHelperChatToTox(self, msg, fmtcc):
groupchat = None
mkey = None
title = ''
if msg.FromUserName == 'filehelper':
mkey = msg.FromUser.Uin
title = '%s@WQU' % msg.FromUser.NickName
else:
mkey = msg.ToUser.Uin
title = '%s@WQU' % msg.ToUser.NickName
if mkey in self.txchatmap:
groupchat = self.txchatmap[mkey]
# assert groupchat is not None
# 有可能groupchat已经就绪,但对方还没有接收请求,这时发送失败,消息会丢失
number_peers = self.peerRelay.groupNumberPeers(groupchat.group_number)
if number_peers < 2:
groupchat.unsend_queue.append(fmtcc)
### reinvite peer into group
self.peerRelay.groupInvite(groupchat.group_number, self.peerRelay.peer_user)
else:
self.peerRelay.sendGroupMessage(fmtcc, groupchat.group_number)
else:
groupchat = self.createChatroom(msg, mkey, title)
groupchat.unsend_queue.append(fmtcc)
return
def dispatchWXGroupChatToTox(self, msg, fmtcc):
groupchat = None
mkey = None
title = ''
# TODO 这段代码好烂,在外层直接用的变量,到内层又检测是否为None,晕了
if msg.FromUser.isGroup():
if msg.FromUser is None:
# message pending and try get group info
qDebug('warning FromUser not found, wxgroup not found:' + msg.FromUserName)
if msg.FromUserName in self.pendingGroupMessages:
self.pendingGroupMessages[msg.FromUserName].append([msg,fmtcc])
else:
self.pendingGroupMessages[msg.ToUserName] = list()
self.pendingGroupMessages[msg.ToUserName].append([msg,fmtcc])
# QTimer.singleShot(1, self.getBatchGroupAll)
return
else:
mkey = msg.FromUser.Uin
title = '%s@WQU' % msg.FromUser.NickName
if len(msg.FromUser.NickName) == 0:
qDebug('maybe a temp group and without nickname')
title = 'TGC%s@WQU' % msg.FromUser.Uin
else:
if msg.ToUser is None:
qDebug('warning ToUser not found, wxgroup not found:' + msg.ToUserName)
if msg.FromUserName in self.pendingGroupMessages:
self.pendingGroupMessages[msg.ToUserName].append([msg,fmtcc])
else:
self.pendingGroupMessages[msg.ToUserName] = list()
self.pendingGroupMessages[msg.ToUserName].append([msg,fmtcc])
# QTimer.singleShot(1, self.getBatchGroupAll)
return
else:
mkey = msg.ToUser.Uin
title = '%s@WQU' % msg.ToUser.NickName
if len(msg.ToUser.NickName) == 0:
qDebug('maybe a temp group and without nickname')
title = 'TGC%s@WQU' % msg.ToUser.Uin
if mkey in self.txchatmap:
groupchat = self.txchatmap[mkey]
# assert groupchat is not None
# 有可能groupchat已经就绪,但对方还没有接收请求,这时发送失败,消息会丢失
number_peers = self.peerRelay.groupNumberPeers(groupchat.group_number)
if number_peers < 2:
groupchat.unsend_queue.append(fmtcc)
### reinvite peer into group
self.peerRelay.groupInvite(groupchat.group_number, self.peerRelay.peer_user)
else:
self.peerRelay.sendGroupMessage(fmtcc, groupchat.group_number)
else:
# TODO 如果是新创建的groupchat,则要等到groupchat可用再发,否则会丢失消息
groupchat = self.createChatroom(msg, mkey, title)
groupchat.unsend_queue.append(fmtcc)
return
def dispatchWXGroupChatToTox2(self, msg, fmtcc, GroupUser):
if msg.FromUser is None: msg.FromUser = GroupUser
elif msg.ToUser is None: msg.ToUser = GroupUser
else: qDebug('wtf???...')
self.dispatchWXGroupChatToTox(msg, fmtcc)
return
def dispatchQQSessChatToTox(self, msg, fmtcc):
groupchat = None
mkey = None
title = ''
# 如果来源User没有找到,则尝试新请求获取group_sig,则首先获取临时会话的peer用户信息
# 如果来源User没有找到,则尝试新请求获取好友信息
to_uin = None
if msg.FromUser is None:
to_uin = msg.FromUserName
elif msg.ToUser is None:
to_uin = msg.ToUserName
else:
pass
if to_uin is not None:
pcall = self.sysiface.asyncCall('getfriendinfo', to_uin, 'a0', 123, 'a1')
watcher = QDBusPendingCallWatcher(pcall)
watcher.finished.connect(self.onGetFriendInfoDone)
self.asyncWatchers[watcher] = [msg, fmtcc]
return
mkey = msg.ToUser.Uin
title = '%s@WQU' % msg.ToUser.NickName
if len(msg.ToUser.NickName) == 0:
qDebug('maybe a temp group and without nickname')
title = 'TGC%s@WQU' % msg.ToUser.Uin
if mkey in self.txchatmap:
groupchat = self.txchatmap[mkey]
# assert groupchat is not None
# 有可能groupchat已经就绪,但对方还没有接收请求,这时发送失败,消息会丢失
number_peers = self.peerRelay.groupNumberPeers(groupchat.group_number)
if number_peers < 2:
groupchat.unsend_queue.append(fmtcc)
### reinvite peer into group
self.peerRelay.groupInvite(groupchat.group_number, self.peerRelay.peer_user)
else:
self.peerRelay.sendGroupMessage(fmtcc, groupchat.group_number)
else:
# TODO 如果是新创建的groupchat,则要等到groupchat可用再发,否则会丢失消息
groupchat = self.createChatroom(msg, mkey, title)
groupchat.unsend_queue.append(fmtcc)
return
def dispatchU2UChatToTox(self, msg, fmtcc):
groupchat = None
mkey = None
title = ''
# 两个用户,正反向通信,使用同一个groupchat,但需要找到它
if msg.FromUser.Uin == self.txses.me.Uin:
mkey = msg.ToUser.Uin
title = '%s@WQU' % msg.ToUser.NickName
else:
mkey = msg.FromUser.Uin
title = '%s@WQU' % msg.FromUser.NickName
# TODO 可能有一个计算交集的函数吧
if mkey in self.txchatmap:
groupchat = self.txchatmap[mkey]
if groupchat is not None:
# assert groupchat is not None
# 有可能groupchat已经就绪,但对方还没有接收请求,这时发送失败,消息会丢失
number_peers = self.peerRelay.groupNumberPeers(groupchat.group_number)
if number_peers < 2:
groupchat.unsend_queue.append(fmtcc)
### reinvite peer into group
self.peerRelay.groupInvite(groupchat.group_number, self.peerRelay.peer_user)
else:
self.peerRelay.sendGroupMessage(fmtcc, groupchat.group_number)
else:
groupchat = self.createChatroom(msg, mkey, title)
groupchat.unsend_queue.append(fmtcc)
return
def createChatroom(self, msg, mkey, title):
group_number = ('WQU.%s' % mkey).lower()
group_number = self.peerRelay.createChatroom(mkey, title)
groupchat = Chatroom()
groupchat.group_number = group_number
groupchat.FromUser = msg.FromUser
groupchat.ToUser = msg.ToUser
groupchat.FromUserName = msg.FromUserName
self.txchatmap[mkey] = groupchat
self.relaychatmap[group_number] = groupchat
groupchat.title = title
if msg.PollType == QQ_PT_DISCUS:
groupchat.chat_type = CHAT_TYPE_DISCUS
elif msg.PollType == QQ_PT_QUN:
groupchat.chat_type = CHAT_TYPE_QUN
elif msg.PollType == QQ_PT_SESSION:
groupchat.chat_type = CHAT_TYPE_SESS
elif msg.PollType == QQ_PT_USER:
groupchat.chat_type = CHAT_TYPE_U2U
else:
qDebug('undefined behavior')
groupchat.Gid = msg.Gid
groupchat.ServiceType = msg.ServiceType
self.peerRelay.groupInvite(group_number, self.peerRelay.peer_user)
return groupchat
def sendMessageToWX(self, groupchat, mcc):
qDebug('here')
FromUser = groupchat.FromUser
ToUser = groupchat.ToUser
if groupchat.chat_type == CHAT_TYPE_QUN:
qDebug('send wx group chat:')
# wx group chat
self.sendWXGroupChatMessageToWX(groupchat, mcc)
pass
elif groupchat.chat_type == CHAT_TYPE_DISCUS:
qDebug('send wx discus chat:')
# wx discus chat
self.sendWXDiscusChatMessageToWX(groupchat, mcc)
pass
elif groupchat.chat_type == CHAT_TYPE_SESS:
qDebug('send wx sess chat:')
# wx sess chat
self.sendWXSessionChatMessageToWX(groupchat, mcc)
pass
elif groupchat.chat_type == CHAT_TYPE_U2U:
qDebug('send wx u2u chat:')
# user <=> user
self.sendU2UMessageToWX(groupchat, mcc)
pass
elif ToUser.isGroup() or FromUser.isGroup():
qDebug('send wx group chat:')
# wx group chat
self.sendWXGroupChatMessageToWX(groupchat, mcc)
pass
elif ToUser.isDiscus() or FromUser.isDiscus():
qDebug('send wx discus chat:')
# wx group chat
self.sendWXDiscusChatMessageToWX(groupchat, mcc)
pass
else:
qDebug('unknown chat:')
pass
# TODO 把从各群组来的发给WX端的消息,再发送给tox汇总端一份。
if True: return
from_username = groupchat.FromUser.UserName
to_username = groupchat.ToUser.UserName
args = [from_username, to_username, mcc, 1, 'more', 'even more']
reply = self.sysiface.call('sendmessage', *args) # 注意把args扩展开
rr = QDBusReply(reply)
if rr.isValid():
qDebug(str(len(rr.value())) + ',' + str(type(rr.value())))
else:
qDebug('rpc call error: %s,%s' % (rr.error().name(), rr.error().message()))
### TODO send message faild
return
def sendWXGroupChatMessageToWX(self, groupchat, mcc):
from_username = groupchat.FromUser.UserName
to_username = groupchat.ToUser.UserName
group_code = groupchat.ToUser.Uin
args = [to_username, from_username, mcc, group_code, 1, 'more', 'even more']
reply = self.sysiface.call('send_qun_msg', *args) # 注意把args扩展开
rr = QDBusReply(reply)
if rr.isValid():
qDebug(str(rr.value()) + ',' + str(type(rr.value())))
else:
qDebug('rpc call error: %s,%s' % (rr.error().name(), rr.error().message()))
### TODO send message faild
return
def sendWXDiscusChatMessageToWX(self, groupchat, mcc):
from_username = groupchat.FromUser.UserName
to_username = groupchat.ToUser.UserName
args = [to_username, from_username, mcc, 1, 'more', 'even more']
reply = self.sysiface.call('send_discus_msg', *args) # 注意把args扩展开
rr = QDBusReply(reply)
if rr.isValid():
qDebug(str(rr.value()) + ',' + str(type(rr.value())))
else:
qDebug('rpc call error: %s,%s' % (rr.error().name(), rr.error().message()))
### TODO send message faild
return
# TODO 修改为调用asyncGetRpc
def sendWXSessionChatMessageToWX(self, groupchat, mcc):
def on_dbus_reply(watcher):
groupchat, mcc = self.asyncWatchers[watcher]
pendReply = QDBusPendingReply(watcher)
message = pendReply.reply()
args = message.arguments()
qDebug(str(args))
# #####
hcc = args[0] # QByteArray
strhcc = self.hcc2str(hcc)
hccjs = json.JSONDecoder().decode(strhcc)
print('group sig', ':::', strhcc)
groupchat.group_sig = hccjs['result']['value']
self.sendWXSessionChatMessageToWX(groupchat, mcc)
self.asyncWatchers.pop(watcher)
return
# get group sig if None
if groupchat.group_sig is None:
gid = groupchat.Gid
tuin = groupchat.FromUser.UserName # 也有可能是ToUser.UserName
service_type = groupchat.ServiceType
pcall = self.sysiface.asyncCall('get_c2cmsg_sig', gid, tuin, service_type, 'a0', 123, 'a1')
watcher = QDBusPendingCallWatcher(pcall)
watcher.finished.connect(on_dbus_reply, Qt.QueuedConnection)
self.asyncWatchers[watcher] = [groupchat, mcc]
# ##########
from_username = groupchat.FromUser.UserName
to_username = groupchat.ToUser.UserName
group_sig = groupchat.group_sig
args = [to_username, from_username, mcc, group_sig, 1, 'more', 'even more']
reply = self.sysiface.call('send_sess_msg', *args) # 注意把args扩展开
rr = QDBusReply(reply)
if rr.isValid():
qDebug(str(rr.value()) + ',' + str(type(rr.value())))
else:
qDebug('rpc call error: %s,%s' % (rr.error().name(), rr.error().message()))
### TODO send message faild
return
def sendU2UMessageToWX(self, groupchat, mcc):
from_username = groupchat.FromUser.UserName
to_username = groupchat.ToUser.UserName
args = [to_username, from_username, mcc, 1, 'more', 'even more']
reply = self.sysiface.call('send_buddy_msg', *args) # 注意把args扩展开
rr = QDBusReply(reply)
if rr.isValid():
qDebug(str(rr.value()) + ',' + str(type(rr.value())))
else:
qDebug('rpc call error: %s,%s' % (rr.error().name(), rr.error().message()))
### TODO send message faild
return
def createWXSession(self):
if self.txses is not None:
return
self.txses = WXSession()
reply = self.sysiface.call('getselfinfo', 123, 'a1', 456)
rr = QDBusReply(reply)
# TODO check reply valid
qDebug(str(len(rr.value())) + ',' + str(type(rr.value())))
data64 = rr.value().encode() # to bytes
data = QByteArray.fromBase64(data64)
self.txses.setSelfInfo(data)
self.saveContent('selfinfo.json', data)
pcall = self.sysiface.asyncCall('getuserfriends', 'a0', 123, 'a1')
watcher = QDBusPendingCallWatcher(pcall)
watcher.finished.connect(self.onGetContactDone, Qt.QueuedConnection)
self.asyncWatchers[watcher] = 'getuserfriends'
pcall = self.sysiface.asyncCall('getgroupnamelist', 'a0', 123, 'a1')
watcher = QDBusPendingCallWatcher(pcall)
watcher.finished.connect(self.onGetContactDone, Qt.QueuedConnection)
self.asyncWatchers[watcher] = 'getgroupnamelist'
pcall = self.sysiface.asyncCall('getdiscuslist', 'a0', 123, 'a1')
watcher = QDBusPendingCallWatcher(pcall)
watcher.finished.connect(self.onGetContactDone, Qt.QueuedConnection)
self.asyncWatchers[watcher] = 'getdiscuslist'
# pcall = self.sysiface.asyncCall('getonlinebuddies', 'a0', 123, 'a1')
# watcher = QDBusPendingCallWatcher(pcall)
# watcher.finished.connect(self.onGetContactDone)
# self.asyncWatchers[watcher] = 'getgrouponlinebuddies'
# pcall = self.sysiface.asyncCall('getrecentlist', 'a0', 123, 'a1')
# watcher = QDBusPendingCallWatcher(pcall)
# watcher.finished.connect(self.onGetContactDone)
# self.asyncWatchers[watcher] = 'getrecentlist'
# reply = self.sysiface.call('getinitdata', 123, 'a1', 456)
# rr = QDBusReply(reply)
# # TODO check reply valid
# qDebug(str(len(rr.value())) + ',' + str(type(rr.value())))
# data64 = rr.value().encode('utf8') # to bytes
# data = QByteArray.fromBase64(data64)
# self.txses.setInitData(data)
# self.saveContent('initdata.json', data)
# reply = self.sysiface.call('getcontact', 123, 'a1', 456)
# rr = QDBusReply(reply)
# # TODO check reply valid
# qDebug(str(len(rr.value())) + ',' + str(type(rr.value())))
# data64 = rr.value().encode('utf8') # to bytes
# data = QByteArray.fromBase64(data64)
# self.txses.setContact(data)
# self.saveContent('contact.json', data)
# reply = self.sysiface.call('getgroups', 123, 'a1', 456)
# rr = QDBusReply(reply)
# # TODO check reply valid
# qDebug(str(len(rr.value())) + ',' + str(type(rr.value())))
# GroupNames = json.JSONDecoder().decode(rr.value())
# self.txses.addGroupNames(GroupNames)
# # QTimer.singleShot(8, self.getBatchContactAll)
# QTimer.singleShot(8, self.getBatchGroupAll)
return
def checkWXLogin(self):
reply = self.sysiface.call('islogined', 'a0', 123, 'a1')
qDebug(str(reply))
rr = QDBusReply(reply)
if not rr.isValid(): return False
qDebug(str(rr.value()) + ',' + str(type(rr.value())))
if rr.value() is False:
return False
return True
def getConnState(self):
reply = self.sysiface.call('connstate', 'a0', 123, 'a1')
qDebug(str(reply))
rr = QDBusReply(reply)
qDebug(str(rr.value()) + ',' + str(type(rr.value())))
return rr.value()
def sendQQNum(self, num):
reply = self.sysiface.call('inputqqnum', num, 'a0', 123, 'a1')
qDebug(str(reply))
rr = QDBusReply(reply)
qDebug(str(rr.value()) + ',' + str(type(rr.value())))
return
def sendPasswordAndVerify(self, password, verify_code):
reply = self.sysiface.call('inputverify', password, verify_code, 'a0', 123, 'a1')
qDebug(str(reply))
rr = QDBusReply(reply)
qDebug(str(rr.value()) + ',' + str(type(rr.value())))
return
def getGroupsFromDBus(self):
reply = self.sysiface.call('getgroups', 123, 'a1', 456)
rr = QDBusReply(reply)
# TODO check reply valid
qDebug(str(len(rr.value())) + ',' + str(type(rr.value())))
GroupNames = json.JSONDecoder().decode(rr.value())
return GroupNames
def onGetContactDone(self, watcher):
pendReply = QDBusPendingReply(watcher)
qDebug(str(watcher))
qDebug(str(pendReply.isValid()))
if pendReply.isValid():
hcc = pendReply.argumentAt(0)
qDebug(str(type(hcc)))
else:
hcc = pendReply.argumentAt(0)
qDebug(str(len(hcc)))
qDebug(str(hcc))
return
message = pendReply.reply()
args = message.arguments()
qDebug(str(args))
extrainfo = self.asyncWatchers[watcher]
self.saveContent('dr.'+extrainfo+'.json', args[0])
######
hcc = args[0] # QByteArray
strhcc = self.hcc2str(hcc)
qDebug(strhcc.encode())
hccjs = json.JSONDecoder().decode(strhcc)
print(extrainfo, ':::', strhcc)
if extrainfo == 'getuserfriends':
self.txses.setUserFriends(hcc)
if extrainfo == 'getgroupnamelist':
self.txses.setGroupList(hcc)
for um in hccjs['result']['gnamelist']:
gcode = um['code']
gname = um['name']
qDebug(b'get group detail...' + str(um).encode())
pcall = self.sysiface.asyncCall('get_group_detail', gcode, 'a0', 123, 'a1')
twatcher = QDBusPendingCallWatcher(pcall)
twatcher.finished.connect(self.onGetGroupOrDiscusDetailDone, Qt.QueuedConnection)
self.asyncWatchers[twatcher] = 'get_group_detail'
qDebug(b'get group detail...' + str(um).encode() + str(twatcher).encode())
if extrainfo == 'getdiscuslist':
self.txses.setDiscusList(hcc)
for um in hccjs['result']['dnamelist']:
did = um['did']
dname = um['name']
qDebug(b'get discus detail...' + str(um).encode())
pcall = self.sysiface.asyncCall('get_discus_detail', did, 'a0', 123, 'a1')
twatcher = QDBusPendingCallWatcher(pcall)
twatcher.finished.connect(self.onGetGroupOrDiscusDetailDone, Qt.QueuedConnection)
self.asyncWatchers[twatcher] = 'get_discus_detail'
qDebug(b'get discus detail...' + str(um).encode() + str(twatcher).encode())
self.asyncWatchers.pop(watcher)
return
# TODO delay dbus 请求响应合并处理
def onGetGroupOrDiscusDetailDone(self, watcher):
pendReply = QDBusPendingReply(watcher)
qDebug(str(watcher))
qDebug(str(pendReply.isValid()))
if pendReply.isValid():
hcc = pendReply.argumentAt(0)
qDebug(str(type(hcc)))
else:
hcc = pendReply.argumentAt(0)
qDebug(str(len(hcc)))
qDebug(str(hcc))
return
message = pendReply.reply()
args = message.arguments()
qDebug(str(args))
extrainfo = self.asyncWatchers[watcher]
self.saveContent('dr.'+extrainfo+'.json', args[0])
if len(args[0].data()) == 0:
qDebug('can not get group or discus list.')
sys.exit()
######
hcc = args[0] # QByteArray
strhcc = self.hcc2str(hcc)
hccjs = json.JSONDecoder().decode(strhcc)
print(extrainfo, ':::', strhcc)
if extrainfo == 'get_group_detail':
qDebug('gooooooooot')
self.txses.setGroupDetail(hcc)
pass
if extrainfo == 'get_discus_detail':
qDebug('gooooooooot')
self.txses.setDiscusDetail(hcc)
pass
self.asyncWatchers.pop(watcher)
return
def getBatchGroupAll(self):
groups2 = self.getGroupsFromDBus()
self.txses.addGroupNames(groups2)
groups = self.txses.getICGroups()
qDebug(str(groups))
reqcnt = 0
arg0 = []
for grname in groups:
melem = {'UserName': grname, 'ChatRoomId': ''}
arg0.append(melem)
argjs = json.JSONEncoder().encode(arg0)
pcall = self.sysiface.asyncCall('getbatchcontact', argjs)
watcher = QDBusPendingCallWatcher(pcall)
# watcher.finished.connect(self.onGetBatchContactDone)
watcher.finished.connect(self.onGetBatchGroupDone)
self.asyncWatchers[watcher] = arg0
reqcnt += 1
qDebug('async reqcnt: ' + str(reqcnt))
return
# @param message QDBusPengindCallWatcher
def onGetBatchGroupDone(self, watcher):
pendReply = QDBusPendingReply(watcher)
qDebug(str(watcher))
qDebug(str(pendReply.isValid()))
if pendReply.isValid():
hcc = pendReply.argumentAt(0)
qDebug(str(type(hcc)))
else:
hcc = pendReply.argumentAt(0)
qDebug(str(len(hcc)))
qDebug(str(hcc))
return
message = pendReply.reply()
args = message.arguments()
# qDebug(str(len(args)))
hcc = args[0] # QByteArray
strhcc = self.hcc2str(hcc)
hccjs = json.JSONDecoder().decode(strhcc)
# print(strhcc)
memcnt = 0
for contact in hccjs['ContactList']:
memcnt += 1
# print(contact)
# self.txses.addMember(contact)
grname = contact['UserName']
if not QQUser.isGroup(grname): continue
print('uid=%s,un=%s,nn=%s\n' % (contact['Uin'], contact['UserName'], contact['NickName']))
self.txses.addGroupUser(grname, contact)
if grname in self.pendingGroupMessages and len(self.pendingGroupMessages[grname]) > 0:
while len(self.pendingGroupMessages[grname]) > 0:
msgobj = self.pendingGroupMessages[grname].pop()
GroupUser = self.txses.getGroupByName(grname)
self.dispatchWXGroupChatToTox2(msgobj[0], msgobj[1], GroupUser)
qDebug('got memcnt: %s/%s' % (memcnt, len(self.txses.ICGroups)))
### flow next
# QTimer.singleShot(12, self.getBatchContactAll)
return
def getBatchContactAll(self):
groups = self.txses.getICGroups()
qDebug(str(groups))
reqcnt = 0
for grname in groups:
members = self.txses.getGroupMembers(grname)
arg0 = []
for member in members:
melem = {'UserName': member, 'EncryChatRoomId': group.UserName}
arg0.append(melem)
cntpertime = 50
while len(arg0) > 0:
subarg = arg0[0:cntpertime]
subargjs = json.JSONEncoder().encode(subarg)
pcall = self.sysiface.asyncCall('getbatchcontact', subargjs)
watcher = QDBusPendingCallWatcher(pcall)
watcher.finished.connect(self.onGetBatchContactDone)
self.asyncWatchers[watcher] = subarg
arg0 = arg0[cntpertime:]
reqcnt += 1
break
break
qDebug('async reqcnt: ' + str(reqcnt))
return
# @param message QDBusPengindCallWatcher
def onGetBatchContactDone(self, watcher):
pendReply = QDBusPendingReply(watcher)
qDebug(str(watcher))
qDebug(str(pendReply.isValid()))
if pendReply.isValid():
hcc = pendReply.argumentAt(0)
qDebug(str(type(hcc)))
else:
return
message = pendReply.reply()
args = message.arguments()
# qDebug(str(len(args)))
hcc = args[0] # QByteArray
strhcc = self.hcc2str(hcc)
hccjs = json.JSONDecoder().decode(strhcc)
# qDebug(str(self.txses.getGroups()))
print(strhcc)
memcnt = 0
for contact in hccjs['ContactList']:
memcnt += 1
# print(contact)
self.txses.addMember(contact)
qDebug('got memcnt: %s/%s' % (memcnt, len(self.txses.ICUsers)))
return
def onGetFriendInfoDone(self, watcher):
pendReply = QDBusPendingReply(watcher)
qDebug(str(watcher))
qDebug(str(pendReply.isValid()))
if pendReply.isValid():
hcc = pendReply.argumentAt(0)
qDebug(str(type(hcc)))
else:
hcc = pendReply.argumentAt(0)
qDebug(str(len(hcc)))
qDebug(str(hcc))
return
message = pendReply.reply()
args = message.arguments()
qDebug(str(args))
msg, fmtcc = self.asyncWatchers[watcher]
######
hcc = args[0] # QByteArray
strhcc = self.hcc2str(hcc)
hccjs = json.JSONDecoder().decode(strhcc)
print(':::', strhcc)
self.txses.addFriendInfo(hcc)
if msg.FromUser is None:
msg.FromUser = self.txses.getUserByName(msg.FromUserName)
elif msg.ToUser is None:
msg.ToUser = self.txses.getUserByName(msg.ToUserName)
else:
pass
assert(msg.FromUser is not None)
assert(msg.ToUser is not None)
self.dispatchQQSessChatToTox(msg, fmtcc)
self.asyncWatchers.pop(watcher)
return
# @param cb(data)
def getMsgImgCallback(self, msg, imgcb=None):
# 还有可能超时,dbus默认timeout=25,而实现有可能达到45秒。WTF!!!
args = [msg.offpic, msg.FromUserName]
offpic_file_path = msg.offpic.replace('/', '%2F')
args = [offpic_file_path, msg.FromUserName]
self.asyncGetRpc('get_msg_img', args, imgcb)
return
# @param cb(data)
def getMsgFileCallback(self, msg, imgcb=None):
# 还有可能超时,dbus默认timeout=25,而实现有可能达到45秒。WTF!!!
# TODO, msg.FileName maybe need urlencoded
args = [msg.MsgId, msg.FileName, msg.ToUserName]
self.asyncGetRpc('get_msg_file', args, imgcb)
return
# hot fix
g_w2t = None
def on_app_about_close():
qDebug('hereee')
global g_w2t
g_w2t.peerRelay.disconnectIt()
return
def main():
app = QCoreApplication(sys.argv)
import wxagent.qtutil as qtutil
qtutil.pyctrl()
w2t = WX2Tox()
global g_w2t
g_w2t = w2t
app.aboutToQuit.connect(on_app_about_close)
app.exec_()
return
if __name__ == '__main__': main()
| [
"drswinghead@163.com"
] | drswinghead@163.com |
9fcf17827dd72f3f73d72719ceb73bb8a9a41fd1 | 873f4bc537db2162de5cc9c4009d773d589c95f9 | /flask/app.py | 3cab1c1142510a33fdeeff004c2ece4b18b93634 | [] | no_license | jeong-jinuk/kisti_finalproject | 51e44f2f6ad42258f20b7ce9319f88b8a257b9ae | 8e0241e5d354e78ca977c9c0a1b50d7e9bd942ab | refs/heads/master | 2022-12-15T19:16:43.891721 | 2020-03-29T07:26:41 | 2020-03-29T07:26:41 | 241,000,825 | 0 | 0 | null | 2022-12-05T16:48:59 | 2020-02-17T02:07:35 | Jupyter Notebook | UTF-8 | Python | false | false | 2,020 | py | from flask import Flask, render_template, request
# modules 폴더 안의 speech_to_text.py와 text_analysis.py를 import해서 사용하겠다!
from modules import speech_to_text, text_analysis, Wave_analysis
import os
app = Flask(__name__)
# Main Page
@app.route('/')
def index() :
return render_template('index.html')
# Upload Page
#@app.route('/save_speech')
#def save() :
# return render_template('save_speech.html')
# Upload Page에서 올린 파일을 분석하고 결과를 반환해주는 곳
@app.route('/saving', methods=['POST']) # POST, GET 형식 둘 다 받을 수 있다는 뜻
def file_save():
f = request.files['recorder']
# 사용자가 file을 엽로드하게 되면 server컴퓨터에 저장하고 그 file을 다시 가져오는 방식으로 구현
f.save('./static/audio_files/'+ f.filename)
# STT를 이용하기 위해 local_file_upload module 내 class를 불러온다.
stt = speech_to_text.Speech()
stt_result = stt.sample_recognize('./static/audio_files/'+ f.filename)
# wave class 불러오기
wave = Wave_analysis.Wave_analysis()
feature_wave = wave.file_load('./static/audio_files/'+ f.filename)
# 감정분석을 위해 text_module 내 class를 불러온다.
tmodule = text_analysis.Tmodule()
emo, review, percent = tmodule.predict_pos_neg(stt_result)
emo_w,percent_w = wave.result_wave(feature_wave)
cross_result,cross_img = wave.emo_cross(emo,emo_w,percent,percent_w)
percent = '%.2f'%percent
percent_w = '%.2f'%percent_w
cross_result = '%.2f'%cross_result
## 체크모듈 만들기
#img_scr = wave.save_wave_form('./static/audio_files/'+ f.filename)
#return render_template('result.html', emo=emo,review=review,percent=percent,emo_w=emo_w,percent_w=percent_w,img_scr=img_scr)
return render_template('result.html', emo=emo,review=review,percent=percent,emo_w=emo_w,percent_w=percent_w,cross_result=cross_result,cross_img=cross_img)
# Finished Code
if __name__ == '__main__' :
app.run()
| [
"56141866+jeong-jinuk@users.noreply.github.com"
] | 56141866+jeong-jinuk@users.noreply.github.com |
1c91a2fc3a6916161290add69f89e3106525c0b4 | 0495e5b46c5674f4e8faece4a18e699279166dd2 | /contextext/__init__.py | 7193d2f0630b97b920609aeacb6d893c36c5570c | [
"MIT"
] | permissive | luketurner/contextext.py | d334ae04175a9975eb91c03fda178675071bc9a2 | fbed054d4c3ea43a78ec117e08ebb997efe45224 | refs/heads/master | 2021-01-10T21:10:09.111058 | 2015-07-08T18:23:43 | 2015-07-08T18:23:43 | 29,504,279 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 169 | py | from .api import *
from .models import ContextEntry
__version__ = "0.1.0a2"
__author__ = "Luke Turner"
__license__ = "MIT"
__copyright__ = "Copyright 2015 Luke Turner"
| [
"github@luketurner.org"
] | github@luketurner.org |
9112a8d3de06671acf5e9fded056dc27c0c8b4a3 | 55726b4940cec0e9df9ba90ab69b27b81c283740 | /DjangoBlog/admin_site.py | d90ec5e4ee94b395af46df4d557eb97ac712a51a | [
"MIT"
] | permissive | zlaiyyf/DjangoBlog | fe655c62f74e929cd874d095cc2f8bf48739bd0d | ccb67c9f08a9b6b8ca65828fece34cda89135187 | refs/heads/master | 2022-12-27T05:06:27.578712 | 2020-10-11T07:47:46 | 2020-10-11T07:47:46 | 264,558,604 | 1 | 0 | MIT | 2020-05-17T01:09:08 | 2020-05-17T01:09:07 | null | UTF-8 | Python | false | false | 2,014 | py | #!/usr/bin/env python
# encoding: utf-8
"""
@version: ??
@author: liangliangyy
@license: MIT Licence
@contact: liangliangyy@gmail.com
@site: https://www.lylinux.net/
@software: PyCharm
@file: admin_site.py
@time: 2018/1/7 上午2:21
"""
from django.contrib.admin import AdminSite
from DjangoBlog.utils import get_current_site
from django.contrib.sites.admin import SiteAdmin
from django.contrib.admin.models import LogEntry
from django.contrib.sites.models import Site
from DjangoBlog.logentryadmin import LogEntryAdmin
from blog.admin import *
from accounts.admin import *
from oauth.admin import *
from servermanager.admin import *
from comments.admin import *
from owntracks.admin import *
class DjangoBlogAdminSite(AdminSite):
site_header = 'DjangoBlog administration'
site_title = 'DjangoBlog site admin'
def __init__(self, name='admin'):
super().__init__(name)
def has_permission(self, request):
return request.user.is_superuser
# def get_urls(self):
# urls = super().get_urls()
# from django.urls import path
# from blog.views import refresh_memcache
#
# my_urls = [
# path('refresh/', self.admin_view(refresh_memcache), name="refresh"),
# ]
# return urls + my_urls
admin_site = DjangoBlogAdminSite(name='admin')
admin_site.register(Article, ArticlelAdmin)
admin_site.register(Category, CategoryAdmin)
admin_site.register(Tag, TagAdmin)
admin_site.register(Links, LinksAdmin)
admin_site.register(SideBar, SideBarAdmin)
admin_site.register(BlogSettings, BlogSettingsAdmin)
admin_site.register(commands, CommandsAdmin)
admin_site.register(EmailSendLog, EmailSendLogAdmin)
admin_site.register(BlogUser, BlogUserAdmin)
admin_site.register(Comment, CommentAdmin)
admin_site.register(OAuthUser, OAuthUserAdmin)
admin_site.register(OAuthConfig, OAuthConfigAdmin)
admin_site.register(OwnTrackLog, OwnTrackLogsAdmin)
admin_site.register(Site, SiteAdmin)
admin_site.register(LogEntry, LogEntryAdmin)
| [
"liangliangyy@gmail.com"
] | liangliangyy@gmail.com |
3ecb1f5f3ec4c2e5ce2a71a98e9fe46cea17d818 | 9130bdbd90b7a70ac4ae491ddd0d6564c1c733e0 | /venv/lib/python3.8/site-packages/cryptography/hazmat/primitives/keywrap.py | 8ca935cafd0f6662b8152910cd075ef54b4b9ba2 | [] | no_license | baruwaa12/Projects | 6ca92561fb440c63eb48c9d1114b3fc8fa43f593 | 0d9a7b833f24729095308332b28c1cde63e9414d | refs/heads/main | 2022-10-21T14:13:47.551218 | 2022-10-09T11:03:49 | 2022-10-09T11:03:49 | 160,078,601 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 96 | py | /home/runner/.cache/pip/pool/2f/84/6a/ccb5454b00837ef6351bc65055c9fc4ab3ccb02f3c73ed14ffceb09910 | [
"45532744+baruwaa12@users.noreply.github.com"
] | 45532744+baruwaa12@users.noreply.github.com |
496115c65865fd718f1fe7b20f050e3d0b91253c | 9b766bdfb9142f1bd2a83462a0f7ffe09c14de04 | /bddtests/peer/query_pb2.py | 45478e2a195bd60e16e941644e4e5c45e5107420 | [
"CC-BY-4.0",
"Apache-2.0"
] | permissive | a20351766/mchain | e850adddc1efb8c7c0d21d6a6906f570c39e6fc1 | 159b9aebb53257d98528070c2863897e2e610643 | refs/heads/master | 2020-03-21T17:52:47.193325 | 2018-06-27T09:35:20 | 2018-06-27T09:35:20 | 137,871,738 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | true | 8,250 | py | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: peer/query.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='peer/query.proto',
package='protos',
syntax='proto3',
serialized_pb=_b('\n\x10peer/query.proto\x12\x06protos\"C\n\x16\x43haincodeQueryResponse\x12)\n\nchaincodes\x18\x01 \x03(\x0b\x32\x15.protos.ChaincodeInfo\"g\n\rChaincodeInfo\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0f\n\x07version\x18\x02 \x01(\t\x12\x0c\n\x04path\x18\x03 \x01(\t\x12\r\n\x05input\x18\x04 \x01(\t\x12\x0c\n\x04\x65scc\x18\x05 \x01(\t\x12\x0c\n\x04vscc\x18\x06 \x01(\t\"=\n\x14\x43hannelQueryResponse\x12%\n\x08\x63hannels\x18\x01 \x03(\x0b\x32\x13.protos.ChannelInfo\"!\n\x0b\x43hannelInfo\x12\x12\n\nchannel_id\x18\x01 \x01(\tBO\n\"org.hyperledger.mchain.protos.peerZ)github.com/hyperledger/mchain/protos/peerb\x06proto3')
)
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
_CHAINCODEQUERYRESPONSE = _descriptor.Descriptor(
name='ChaincodeQueryResponse',
full_name='protos.ChaincodeQueryResponse',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='chaincodes', full_name='protos.ChaincodeQueryResponse.chaincodes', index=0,
number=1, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=28,
serialized_end=95,
)
_CHAINCODEINFO = _descriptor.Descriptor(
name='ChaincodeInfo',
full_name='protos.ChaincodeInfo',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='name', full_name='protos.ChaincodeInfo.name', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='version', full_name='protos.ChaincodeInfo.version', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='path', full_name='protos.ChaincodeInfo.path', index=2,
number=3, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='input', full_name='protos.ChaincodeInfo.input', index=3,
number=4, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='escc', full_name='protos.ChaincodeInfo.escc', index=4,
number=5, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='vscc', full_name='protos.ChaincodeInfo.vscc', index=5,
number=6, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=97,
serialized_end=200,
)
_CHANNELQUERYRESPONSE = _descriptor.Descriptor(
name='ChannelQueryResponse',
full_name='protos.ChannelQueryResponse',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='channels', full_name='protos.ChannelQueryResponse.channels', index=0,
number=1, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=202,
serialized_end=263,
)
_CHANNELINFO = _descriptor.Descriptor(
name='ChannelInfo',
full_name='protos.ChannelInfo',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='channel_id', full_name='protos.ChannelInfo.channel_id', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=265,
serialized_end=298,
)
_CHAINCODEQUERYRESPONSE.fields_by_name['chaincodes'].message_type = _CHAINCODEINFO
_CHANNELQUERYRESPONSE.fields_by_name['channels'].message_type = _CHANNELINFO
DESCRIPTOR.message_types_by_name['ChaincodeQueryResponse'] = _CHAINCODEQUERYRESPONSE
DESCRIPTOR.message_types_by_name['ChaincodeInfo'] = _CHAINCODEINFO
DESCRIPTOR.message_types_by_name['ChannelQueryResponse'] = _CHANNELQUERYRESPONSE
DESCRIPTOR.message_types_by_name['ChannelInfo'] = _CHANNELINFO
ChaincodeQueryResponse = _reflection.GeneratedProtocolMessageType('ChaincodeQueryResponse', (_message.Message,), dict(
DESCRIPTOR = _CHAINCODEQUERYRESPONSE,
__module__ = 'peer.query_pb2'
# @@protoc_insertion_point(class_scope:protos.ChaincodeQueryResponse)
))
_sym_db.RegisterMessage(ChaincodeQueryResponse)
ChaincodeInfo = _reflection.GeneratedProtocolMessageType('ChaincodeInfo', (_message.Message,), dict(
DESCRIPTOR = _CHAINCODEINFO,
__module__ = 'peer.query_pb2'
# @@protoc_insertion_point(class_scope:protos.ChaincodeInfo)
))
_sym_db.RegisterMessage(ChaincodeInfo)
ChannelQueryResponse = _reflection.GeneratedProtocolMessageType('ChannelQueryResponse', (_message.Message,), dict(
DESCRIPTOR = _CHANNELQUERYRESPONSE,
__module__ = 'peer.query_pb2'
# @@protoc_insertion_point(class_scope:protos.ChannelQueryResponse)
))
_sym_db.RegisterMessage(ChannelQueryResponse)
ChannelInfo = _reflection.GeneratedProtocolMessageType('ChannelInfo', (_message.Message,), dict(
DESCRIPTOR = _CHANNELINFO,
__module__ = 'peer.query_pb2'
# @@protoc_insertion_point(class_scope:protos.ChannelInfo)
))
_sym_db.RegisterMessage(ChannelInfo)
DESCRIPTOR.has_options = True
DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n\"org.hyperledger.mchain.protos.peerZ)github.com/hyperledger/mchain/protos/peer'))
try:
# THESE ELEMENTS WILL BE DEPRECATED.
# Please use the generated *_pb2_grpc.py files instead.
import grpc
from grpc.framework.common import cardinality
from grpc.framework.interfaces.face import utilities as face_utilities
from grpc.beta import implementations as beta_implementations
from grpc.beta import interfaces as beta_interfaces
except ImportError:
pass
# @@protoc_insertion_point(module_scope)
| [
"zhangtao@m-chain.com"
] | zhangtao@m-chain.com |
dfa2bc0f3ef0554c7d6e9d0b691233ce1bededf1 | bbadc0354f5a6c1fd6174ccc92c237a573e80948 | /Python scripts/Rookie/Pig-latin.py | 627818c7a9dff4313ea557c20608867cfa277744 | [
"MIT"
] | permissive | shartrooper/My-python-scripts | fcc6e7d8d0d3da4aebc0bffc63b462d802545ba7 | 5c3a8db4ed9a75bd9ab4b29153a788d9e6c5d28c | refs/heads/main | 2023-04-03T22:12:16.872554 | 2021-04-10T14:54:40 | 2021-04-10T14:54:40 | 302,179,382 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,621 | py | # English to Pig Latin
print('Enter the English message to translate into Pig Latin:')
message = input()
VOWELS = ('a', 'e', 'i', 'o', 'u', 'y')
pigLatin = [] # A list of the words in Pig Latin.
for word in message.split():
# Separate the non-letters at the start of this word:
prefixNonLetters = ''
while len(word) > 0 and not word[0].isalpha():
prefixNonLetters += word[0]
word = word[1:]
if len(word) == 0:
pigLatin.append(prefixNonLetters)
continue
# Separate the non-letters at the end of this word:
suffixNonLetters = ''
while not word[-1].isalpha():
suffixNonLetters += word[-1]
word = word[:-1]
# Remember if the word was in uppercase or title case.
wasUpper = word.isupper()
wasTitle = word.istitle()
word = word.lower() # Make the word lowercase for translation.
# Separate the consonants at the start of this word:
prefixConsonants = ''
while len(word) > 0 and not word[0] in VOWELS:
prefixConsonants += word[0]
word = word[1:]
# Add the Pig Latin ending to the word:
if prefixConsonants != '':
word += prefixConsonants + 'ay'
else:
word += 'yay'
# Set the word back to uppercase or title case:
if wasUpper:
word = word.upper()
if wasTitle:
word = word.title()
# Add the non-letters back to the start or end of the word.
pigLatin.append(prefixNonLetters + word + suffixNonLetters)
# Join all the words back together into a single string:
print(' '.join(pigLatin))
| [
"noreply@github.com"
] | shartrooper.noreply@github.com |
86b80df09d09f685086e3d92c9de57efd8433e2a | 61654b43a37b4ac48e6b67779258a95068b47741 | /cadenas_ejemplos.py | 51d7576f825a1895498762163e4e9d114ca2bffb | [] | no_license | katiavega/CS1100_S06 | cbd991fd744d330e5e6d855e3577d8d4764147d0 | ec518f648265b4bbe49227e692c7dbc7b184e626 | refs/heads/master | 2021-01-20T00:11:09.473646 | 2017-04-22T18:41:05 | 2017-04-22T18:41:05 | 89,091,241 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 714 | py | s = 'Monty Python'
print (s[2]) ## n
print (s[-2] )## o
print (s[:6] + s[6:8] + s[8:]) ## Monty Python
##operador%
print ("%d tigres comen %.1f porción de %s en un %s" % (3, 0.5, 'trigo', 'trigal'))
##Unicode
ustring = u'Hola en chino \u4F60 \u597D ' # ñ \xf1'
## (ustring from above contains a unicode string)
s = ustring.encode('utf-8')
print (s) #equivalente de unicode en UTF8
t = s.decode('utf-8', "strict") ## Convert bytes back to a unicode string
print(t) ## It's the same as the original, yay!
##len
print(len('La vida es mucho mejor con Python.'))
print("La vida es mucho mejor con Pyhon.".find("Python"))
print('Mejor con Python'.replace('Python', 'Jython'))
| [
"katia.canepa@gmail.com"
] | katia.canepa@gmail.com |
01edfba8e488262d2f811bdd70a88655bbc29857 | 3144e3f159ddf9f5e0c923ce5addedc9144dbb8c | /app.py | 0aaf101303b0939c321c190a014a4569a89bb841 | [] | no_license | davidrhodus/nft-checker-tool | 75ce38b82fd80c19913cc38e90121d47732d449c | 55531d98f4a56cddbace63e35ed845ad407a1550 | refs/heads/main | 2023-08-30T21:19:03.949476 | 2021-10-11T13:25:43 | 2021-10-11T13:25:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 344 | py | from flask import Flask, request, render_template, redirect, url_for
from owning_check import nft_checker
import json
app = Flask(__name__)
@app.route('/', methods = ['GET'])
def search_api():
query = request.args.get('address')
return nft_checker(query, 'collection-scraper.json')
if __name__ == '__main__':
app.run(port=5000)
| [
"noreply@github.com"
] | davidrhodus.noreply@github.com |
5356a4e10bbb075353b889376259dbe1807e0ccf | 9059c79a4dc289bc00a7315d746907911a59b7f6 | /project/signed_networks/structural_balance/plots/main-negatives-vs-positives.py | cdd88132dcfd9f09f0506480a4da8f7c9f379497 | [] | no_license | abinesh/world-trade-flow-analytics | 1b942b2f2e5a0f38ea1a8c3ef8f92bcfbc996bb3 | dbe53c7d22e540bf4d0b9f1bcabc454b596d5de9 | refs/heads/master | 2021-01-16T00:28:47.781035 | 2013-06-03T08:27:52 | 2013-06-03T08:27:52 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,921 | py | import json
from project import countries
from project.config import WORLD_TRADE_FLOW_DATA_FILE_ORIGINAL
from project.export_data.exportdata import ExportData
from project.signed_networks.definitions import NEGATIVE_LINK, POSITIVE_LINK, args_for_definition_C, definition_C3
from project.signed_networks.structural_balance.plots.config import OUT_DIR
def positives_and_negatives_data_d3(data, definition, def_args, out_dir):
# countries_list = ["USA","UK","Turkey"]
countries_list = countries.countries
class NationData:
def __init__(self, country_name):
self.name = country_name
self.region = country_name
self.positive_links_count = []
self.negative_links_count = []
self.export_quantity = []
def add_data(self, year, p, n, ex):
self.positive_links_count.append([year, p])
self.negative_links_count.append([year, n])
self.export_quantity.append([year, ex])
all_nations_dict = []
json_file = open(out_dir + 'nations_gen.json', 'w')
for A in countries_list:
nation = NationData(A)
for year in data.all_years:
positive = 0
negative = 0
for B in countries_list:
if A == B: continue
link_type = definition(data, year, A, B, def_args)
if link_type == NEGATIVE_LINK: negative += 1
elif link_type == POSITIVE_LINK: positive += 1
nation.add_data(year, positive, negative, data.total_exports(A, year))
all_nations_dict.append(nation.__dict__)
json_file.write(json.dumps(all_nations_dict))
json_file.close()
data = ExportData()
data.load_file('../../' + WORLD_TRADE_FLOW_DATA_FILE_ORIGINAL, should_read_world_datapoints=True)
positives_and_negatives_data_d3(data, definition_C3, args_for_definition_C(10,1000), OUT_DIR.POSITIVES_AND_NEGATIVES) | [
"td.abinesh@gmail.com"
] | td.abinesh@gmail.com |
3fef40d4618b4b77b18d01040efc212adcf8cc64 | 51f5534892933829494afef6eed6829dfb169d43 | /main.py | 15c393d7a88c404a2b10224856f82084b42d9843 | [
"MIT"
] | permissive | Prime-Networks/PNServer | 2b54c734d00462e4c06403ec532fa223fc4e8387 | 4a6095dd3bea3efb04b4d511de5f309b20547ac5 | refs/heads/master | 2022-12-10T18:40:33.236602 | 2020-09-05T06:30:12 | 2020-09-05T06:30:12 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,025 | py | from flask import Flask, render_template, request, session, escape, redirect, flash, url_for
from os import path,walk
# from scripts.get_ip import get_ip
from get_ip import get_ip
from scan import load_services, check_local_services, check_network_machines
from flask_sqlalchemy import sqlalchemy,SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
# from dbmodel import Users
import os
dbdir = "sqlite:///"+ os.path.abspath(os.getcwd()) + "/database.db"
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = dbdir
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.secret_key = '1232314341rdfamkpsva3k1fksapanwp3np3pma'
# app.config["extend_existing"] = True
db = SQLAlchemy(app)
access = {
'guest':0,
'user':1,
'admin':2,
'super admin':3
}
class Users(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), unique=True, nullable=False)
pwd = db.Column(db.String(80), nullable=False)
access_code = db.Column(db.String(5), nullable=False)
access_name = db.Column(db.String(10), nullable=False)
class Services(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), unique=True, nullable=False)
port = db.Column(db.String(5), unique=True, nullable=False)
access_code = db.Column(db.String(5), nullable=False)
access_name = db.Column(db.String(10), nullable=False)
class Properties(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), unique=True, nullable=False)
access_code = db.Column(db.String(5), nullable=False)
access_name = db.Column(db.String(10), nullable=False)
def get_services():
services = []
services_db = Services.query.all()
columns = Services.__table__.columns
final_list = []
for i in services_db:
final_list.append(i.name)
for cp,dir,files in walk('static/img/services'):
for i in files:
if i[:i.find('.')] in final_list:
path_pic =path.join(cp,i)
if not path.exists(path_pic):
path_pic = 'static/img/services/PNCmdr.png'
services.append((i[:i.find('.')],path_pic))
# print(services)
# print(final_list)
return services
def get_data(property):
if property == 'users':
users = Users.query.all()
columns = Users.__table__.columns
final_list = []
for i in users:
final_list.append([i.id, i.name])
return final_list
if property == 'services':
services = Services.query.all()
columns = Services.__table__.columns
final_list = []
for i in services:
final_list.append([i.id, i.name, i.port])
return final_list
else:
pass
return [[ 'emby', '8096'], ['PNCmdr', '2357']]
def check_session():
print(session)
if 'username' in session:
return escape(session['username'])
else:
return None
@app.route('/debug')
def debug():
if 'username' in session:
user = escape(session['username'])
else:
user = None
return render_template('server_up.html',title='Debug', content='Server is Up!', paragraph='The Server is Up and running ('+get_ip()+')', user=user ,services=get_services(), header_title='Prime Networks Server')
@app.route('/')
def root():
if 'username' in session:
user = escape(session['username'])
else:
user = None
return render_template('home.html', user=user, machines=scan_network()['PNCmdr'], header_title='Prime Networks Commander', services=scan_network().keys())
#TODO return only the info corresponding to the acces of the User
@app.route('/scan')
def scan_network():
return check_network_machines(db)
@app.route('/services')
def return_active_services():
return check_local_services()
@app.route('/login', methods=['GET', 'POST'])
@app.route('/register', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
if request.form['submit'] == 'Login':
user = Users.query.filter_by(name=request.form['username']).first()
if user and not user.name == '' and check_password_hash( user.pwd, request.form['password']):
session['username'] = user.name
# print(session)
# return str("Wellcome "+str(user.name))
return redirect('/')
else:
flash('Wrong Credentials', 'warning')
return render_template('login.html')
else:
# print(request.form["username"])
try:
ciphered_pwd = generate_password_hash(request.form["password"], method='sha256')
new_user = Users(name=request.form["username"], pwd=ciphered_pwd, access_name='guest', access_code=0)
db.session.add(new_user)
db.session.commit()
flash('User Registered Succesfully', 'success')
except:
flash('Registration Failed', 'error')
return render_template('login.html')
# if request.method == 'GET':
return render_template('login.html')
#TODO Check user access
@app.route('/manage', methods=['GET', 'POST'])
@app.route('/manage/users' , methods=['GET', 'POST'])
def manage_page_users():
if request.method == 'POST':
if request.form['submit-user'] == 'Create':
try:
ciphered_pwd = generate_password_hash(request.form["password"], method='sha256')
new_user = Users(name=request.form["name"], pwd=ciphered_pwd, access_name=request.form['access_name'], access_code=access[request.form['access_name']])
db.session.add(new_user)
db.session.commit()
except:
pass
# return render_template('login.html', warning=True)
return render_template('manage.html', header_title='Manage Users', login='True', user='test', property='users', data=get_data('users'))
@app.route('/manage/services', methods=['GET', 'POST'])
def manage_page_services():
if request.method == 'POST':
if request.form['submit-service'] == 'Create':
try:
# ciphered_pwd = generate_password_hash(request.form["password"], method='sha256')
new_service = Services(name=request.form["name"], port=request.form['port'], access_name=request.form['access_name'], access_code=access[request.form['access_name']])
db.session.add(new_service)
db.session.commit()
except:
pass
return render_template('manage.html', header_title='Manage Services', login='True', user='test', property='services', data=get_data('services'))
if __name__ == '__main__':
db.create_all()
os.popen("sass static/scss/style.scss:static/css/style.css")
app.run(debug=True,host=get_ip(), port=2357) | [
"javiale2000@gmail.com"
] | javiale2000@gmail.com |
d6ae857b950288a40f300ca27e242e60df1df9a0 | 4f807eb45da63a633f32425908a4acf19462d96f | /python/src/yatzy/YatzyTest.py | 0b2bf06d8f872a60d16e9e5cdc496e24a2794c6a | [] | no_license | mebusw/Test-Driven-Development | 580c3f31ee0f406afa8d7761bf82acd67cfcd166 | 7a49f2615a78a1cedbb909e60e0232e5e1467287 | refs/heads/master | 2021-01-22T06:32:07.448971 | 2017-02-02T04:56:40 | 2017-02-02T04:56:40 | 5,836,643 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,756 | py | """
The game of yatzy is a simple dice game. Each player
rolls five six-sided dice. The player places the roll in
a category, such as ones, twos, fives, pair, two pairs
etc (see below).
If the roll is compatible with the category, the player
gets a score for the roll according to the rules. If the
roll is not compatible with the category, the player scores
zero for the roll.
For example, if a player rolls 5,6,5,5,2 and scores the
dice in the fives category they would score 15 (three fives).
Your task is to score a GIVEN roll in a GIVEN category.
You do NOT have to program the random dice rolling.
You do NOT have to program re-rolls (as in the real game).
You do NOT play by letting the computer choose the highest
scoring category for a given roll.
Yatzy Categories and Scoring Rules
==================================
Chance:
The player scores the sum of all dice,
no matter what they read.
For example,
1,1,3,3,6 placed on "chance" scores 14 (1+1+3+3+6)
4,5,5,6,1 placed on "chance" scores 21 (4+5+5+6+1)
Yatzy:
If all dice have the same number,
the player scores 50 points.
For example,
1,1,1,1,1 placed on "yatzy" scores 50
5,5,5,5,5 placed on "yatzy" scores 50
1,1,1,2,1 placed on "yatzy" scores 0
Ones, Twos, Threes, Fours, Fives, Sixes:
The player scores the sum of the dice that reads one,
two, three, four, five or six, respectively.
For example,
1,1,2,4,4 placed on "fours" scores 8 (4+4)
2,3,2,5,1 placed on "twos" scores 4 (2+2)
3,3,3,4,5 placed on "ones" scores 0
Pair:
If exactly two dice have the same value then
the player scores the sum of the two highest matching dice.
For example, when placed on "pair"
3,3,3,4,4 scores 8 (4+4)
1,1,6,2,6 scores 12 (6+6)
3,3,3,4,1 scores 0
3,3,3,3,1 scores 0
Two pairs:
If exactly two dice have the same value and exactly
two dice have a different value then the
player scores the sum of these four dice.
For example, when placed on "two pairs"
1,1,2,3,3 scores 8 (1+1+3+3)
1,1,2,3,4 scores 0
1,1,2,2,2 scores 0
Three of a kind:
If there are exactly three dice with the same number
then the player scores the sum of these dice.
For example, when placed on "three of a kind"
3,3,3,4,5 scores 9 (3+3+3)
3,3,4,5,6 scores 0
3,3,3,3,1 scores 0
Four of a kind:
If there are exactly four dice with the same number
then the player scores the sum of these dice.
For example, when placed on "four of a kind"
2,2,2,2,5 scores 8 (2+2+2+2)
2,2,2,5,5 scores 0
2,2,2,2,2 scores 0
Small straight:
When placed on "small straight", if the dice read
1,2,3,4,5, the player scores 15 (the sum of all the dice).
Large straight:
When placed on "large straight", if the dice read
2,3,4,5,6, the player scores 20 (the sum of all the dice).
Full house:
If the dice are two of a kind and three of a different kind
then the player scores the sum of all five dice.
For example, when placed on "full house"
1,1,2,2,2 scores 8 (1+1+2+2+2)
2,2,3,3,4 scores 0
4,4,4,4,4 scores 0
"""
import unittest
from itertools import groupby
class Game(object):
@staticmethod
def chance(*dice):
return sum(dice)
@staticmethod
def yatzy(*dice):
return 50 if all(d == dice[0] for d in dice) else 0
@staticmethod
def _single(n):
return lambda *dice: n * dice.count(n)
def __init__(self):
self.sixes = Game._single(6)
self.fives = Game._single(5)
self.fours = Game._single(4)
self.threes = Game._single(3)
self.twos = Game._single(2)
self.ones = Game._single(1)
def pair(self, *dice):
for b in self._buckets(dice):
if b[1] == 2:
return b[0] * 2
return 0
def _buckets(self, dice):
g = groupby(sorted(dice, reverse=True), lambda x: x)
buckets = [(m, len(list(n))) for m, n in g]
buckets = sorted(buckets, key=lambda x: x[1], reverse=True)
return buckets
def three_kind(self, *dice):
b = self._buckets(dice)
if b[0][1] == 3:
return b[0][0] * 3
return 0
def four_kind(self, *dice):
b = self._buckets(dice)
if b[0][1] == 4:
return b[0][0] * 4
return 0
def two_pairs(self, *dice):
b = self._buckets(dice)
if b[0][1] == 2 and b[1][1] == 2:
return b[0][0] * 2 + b[1][0] * 2
return 0
def straight(self, *dice):
if all(z[0] == z[1] + 1 for z in zip(dice[1:], dice[:-1])):
return sum(dice)
return 0
def full_house(self, *dice):
b = self._buckets(dice)
if b[0][1] == 3 and b[1][1] == 2:
return sum(dice)
return 0
class YatzyTest(unittest.TestCase):
def setUp(self):
pass
def test_chance(self):
self.assertEquals(1 + 1 + 3 + 3 + 6, Game.chance(1, 1, 3, 3, 6))
self.assertEquals(4 + 5 + 5 + 6 + 1, Game.chance(4, 5, 5, 6, 1))
def test_yatzy(self):
self.assertEquals(50, Game.yatzy(1, 1, 1, 1, 1))
self.assertEquals(50, Game.yatzy(5, 5, 5, 5, 5))
self.assertEquals(0, Game.yatzy(1, 1, 1, 2, 1))
def test_ones(self):
self.assertEquals(4 + 4, Game().fours(1, 1, 2, 4, 4))
self.assertEquals(2 + 2, Game().twos(2, 3, 2, 5, 1))
self.assertEquals(0, Game().ones(3, 3, 3, 4, 5))
def test_pair(self):
self.assertEquals(4 + 4, Game().pair(3, 3, 3, 4, 4))
self.assertEquals(6 + 6, Game().pair(1, 1, 6, 2, 6))
self.assertEquals(0, Game().pair(3, 3, 3, 4, 1))
self.assertEquals(0, Game().pair(3, 3, 3, 3, 1))
def test_two_pairs(self):
self.assertEquals(1 + 1 + 3 + 3, Game().two_pairs(1, 1, 2, 3, 3))
self.assertEquals(0, Game().two_pairs(1, 1, 2, 3, 4))
self.assertEquals(0, Game().two_pairs(1, 1, 2, 2, 2))
def test_three_of_a_kind(self):
self.assertEquals(3 + 3 + 3, Game().three_kind(3, 3, 3, 4, 5))
self.assertEquals(0, Game().three_kind(3, 3, 4, 5, 6))
self.assertEquals(0, Game().three_kind(3, 3, 3, 3, 1))
def test_four_of_a_kind(self):
self.assertEquals(2 + 2 + 2 + 2, Game().four_kind(2, 2, 2, 2, 5))
self.assertEquals(0, Game().four_kind(2, 2, 2, 5, 5))
self.assertEquals(0, Game().four_kind(2, 2, 2, 2, 2))
def test_straight(self):
self.assertEquals(1 + 2 + 3 + 4 + 5, Game().straight(1, 2, 3, 4, 5))
self.assertEquals(2 + 3 + 4 + 5 + 6, Game().straight(2, 3, 4, 5, 6))
def test_full_house(self):
self.assertEquals(1 + 1 + 2 + 2 + 2, Game().full_house(1, 1, 2, 2, 2))
if __name__ == "__main__":
# import sys;sys.argv = ['', 'Test.testName']
unittest.main()
| [
"mebusw@163.com"
] | mebusw@163.com |
10c2d3b327dc40f33c3ce744411f740e17521caa | 928114757a9d6f36cd5ae14d3ba0173e7d068496 | /test/functional/bumpfee.py | 9107f5ec20986fc7328eb1d2f1e8beb6e57cb6bf | [
"MIT"
] | permissive | ilafaf/kori | 65969ff2f9947f581f25f988a1180c731558312c | f77aeb4d19b66a3617d3a029c5c6ba2896ecf7b4 | refs/heads/master | 2021-05-06T13:32:59.180598 | 2017-12-05T20:48:28 | 2017-12-05T20:48:28 | 113,225,495 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 13,437 | py | #!/usr/bin/env python3
# Copyright (c) 2016 The Kori Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the bumpfee RPC.
Verifies that the bumpfee RPC creates replacement transactions successfully when
its preconditions are met, and returns appropriate errors in other cases.
This module consists of around a dozen individual test cases implemented in the
top-level functions named as test_<test_case_description>. The test functions
can be disabled or reordered if needed for debugging. If new test cases are
added in the future, they should try to follow the same convention and not
make assumptions about execution order.
"""
from segwit import send_to_witness
from test_framework.test_framework import KoriTestFramework
from test_framework import blocktools
from test_framework.mininode import CTransaction
from test_framework.util import *
import io
# Sequence number that is BIP 125 opt-in and BIP 68-compliant
BIP125_SEQUENCE_NUMBER = 0xfffffffd
WALLET_PASSPHRASE = "test"
WALLET_PASSPHRASE_TIMEOUT = 3600
class BumpFeeTest(KoriTestFramework):
def set_test_params(self):
self.num_nodes = 2
self.setup_clean_chain = True
self.extra_args = [["-prematurewitness", "-walletprematurewitness", "-walletrbf={}".format(i)]
for i in range(self.num_nodes)]
def run_test(self):
# Encrypt wallet for test_locked_wallet_fails test
self.nodes[1].node_encrypt_wallet(WALLET_PASSPHRASE)
self.start_node(1)
self.nodes[1].walletpassphrase(WALLET_PASSPHRASE, WALLET_PASSPHRASE_TIMEOUT)
connect_nodes_bi(self.nodes, 0, 1)
self.sync_all()
peer_node, rbf_node = self.nodes
rbf_node_address = rbf_node.getnewaddress()
# fund rbf node with 10 coins of 0.001 btc (100,000 satoshis)
self.log.info("Mining blocks...")
peer_node.generate(110)
self.sync_all()
for i in range(25):
peer_node.sendtoaddress(rbf_node_address, 0.001)
self.sync_all()
peer_node.generate(1)
self.sync_all()
assert_equal(rbf_node.getbalance(), Decimal("0.025"))
self.log.info("Running tests")
dest_address = peer_node.getnewaddress()
test_simple_bumpfee_succeeds(rbf_node, peer_node, dest_address)
test_segwit_bumpfee_succeeds(rbf_node, dest_address)
test_nonrbf_bumpfee_fails(peer_node, dest_address)
test_notmine_bumpfee_fails(rbf_node, peer_node, dest_address)
test_bumpfee_with_descendant_fails(rbf_node, rbf_node_address, dest_address)
test_small_output_fails(rbf_node, dest_address)
test_dust_to_fee(rbf_node, dest_address)
test_settxfee(rbf_node, dest_address)
test_rebumping(rbf_node, dest_address)
test_rebumping_not_replaceable(rbf_node, dest_address)
test_unconfirmed_not_spendable(rbf_node, rbf_node_address)
test_bumpfee_metadata(rbf_node, dest_address)
test_locked_wallet_fails(rbf_node, dest_address)
self.log.info("Success")
def test_simple_bumpfee_succeeds(rbf_node, peer_node, dest_address):
rbfid = spend_one_input(rbf_node, dest_address)
rbftx = rbf_node.gettransaction(rbfid)
sync_mempools((rbf_node, peer_node))
assert rbfid in rbf_node.getrawmempool() and rbfid in peer_node.getrawmempool()
bumped_tx = rbf_node.bumpfee(rbfid)
assert_equal(bumped_tx["errors"], [])
assert bumped_tx["fee"] - abs(rbftx["fee"]) > 0
# check that bumped_tx propagates, original tx was evicted and has a wallet conflict
sync_mempools((rbf_node, peer_node))
assert bumped_tx["txid"] in rbf_node.getrawmempool()
assert bumped_tx["txid"] in peer_node.getrawmempool()
assert rbfid not in rbf_node.getrawmempool()
assert rbfid not in peer_node.getrawmempool()
oldwtx = rbf_node.gettransaction(rbfid)
assert len(oldwtx["walletconflicts"]) > 0
# check wallet transaction replaces and replaced_by values
bumpedwtx = rbf_node.gettransaction(bumped_tx["txid"])
assert_equal(oldwtx["replaced_by_txid"], bumped_tx["txid"])
assert_equal(bumpedwtx["replaces_txid"], rbfid)
def test_segwit_bumpfee_succeeds(rbf_node, dest_address):
# Create a transaction with segwit output, then create an RBF transaction
# which spends it, and make sure bumpfee can be called on it.
segwit_in = next(u for u in rbf_node.listunspent() if u["amount"] == Decimal("0.001"))
segwit_out = rbf_node.validateaddress(rbf_node.getnewaddress())
rbf_node.addwitnessaddress(segwit_out["address"])
segwitid = send_to_witness(
use_p2wsh=False,
node=rbf_node,
utxo=segwit_in,
pubkey=segwit_out["pubkey"],
encode_p2sh=False,
amount=Decimal("0.0009"),
sign=True)
rbfraw = rbf_node.createrawtransaction([{
'txid': segwitid,
'vout': 0,
"sequence": BIP125_SEQUENCE_NUMBER
}], {dest_address: Decimal("0.0005"),
rbf_node.getrawchangeaddress(): Decimal("0.0003")})
rbfsigned = rbf_node.signrawtransaction(rbfraw)
rbfid = rbf_node.sendrawtransaction(rbfsigned["hex"])
assert rbfid in rbf_node.getrawmempool()
bumped_tx = rbf_node.bumpfee(rbfid)
assert bumped_tx["txid"] in rbf_node.getrawmempool()
assert rbfid not in rbf_node.getrawmempool()
def test_nonrbf_bumpfee_fails(peer_node, dest_address):
# cannot replace a non RBF transaction (from node which did not enable RBF)
not_rbfid = peer_node.sendtoaddress(dest_address, Decimal("0.00090000"))
assert_raises_rpc_error(-4, "not BIP 125 replaceable", peer_node.bumpfee, not_rbfid)
def test_notmine_bumpfee_fails(rbf_node, peer_node, dest_address):
# cannot bump fee unless the tx has only inputs that we own.
# here, the rbftx has a peer_node coin and then adds a rbf_node input
# Note that this test depends upon the RPC code checking input ownership prior to change outputs
# (since it can't use fundrawtransaction, it lacks a proper change output)
utxos = [node.listunspent()[-1] for node in (rbf_node, peer_node)]
inputs = [{
"txid": utxo["txid"],
"vout": utxo["vout"],
"address": utxo["address"],
"sequence": BIP125_SEQUENCE_NUMBER
} for utxo in utxos]
output_val = sum(utxo["amount"] for utxo in utxos) - Decimal("0.001")
rawtx = rbf_node.createrawtransaction(inputs, {dest_address: output_val})
signedtx = rbf_node.signrawtransaction(rawtx)
signedtx = peer_node.signrawtransaction(signedtx["hex"])
rbfid = rbf_node.sendrawtransaction(signedtx["hex"])
assert_raises_rpc_error(-4, "Transaction contains inputs that don't belong to this wallet",
rbf_node.bumpfee, rbfid)
def test_bumpfee_with_descendant_fails(rbf_node, rbf_node_address, dest_address):
# cannot bump fee if the transaction has a descendant
# parent is send-to-self, so we don't have to check which output is change when creating the child tx
parent_id = spend_one_input(rbf_node, rbf_node_address)
tx = rbf_node.createrawtransaction([{"txid": parent_id, "vout": 0}], {dest_address: 0.00020000})
tx = rbf_node.signrawtransaction(tx)
rbf_node.sendrawtransaction(tx["hex"])
assert_raises_rpc_error(-8, "Transaction has descendants in the wallet", rbf_node.bumpfee, parent_id)
def test_small_output_fails(rbf_node, dest_address):
# cannot bump fee with a too-small output
rbfid = spend_one_input(rbf_node, dest_address)
rbf_node.bumpfee(rbfid, {"totalFee": 50000})
rbfid = spend_one_input(rbf_node, dest_address)
assert_raises_rpc_error(-4, "Change output is too small", rbf_node.bumpfee, rbfid, {"totalFee": 50001})
def test_dust_to_fee(rbf_node, dest_address):
# check that if output is reduced to dust, it will be converted to fee
# the bumped tx sets fee=49,900, but it converts to 50,000
rbfid = spend_one_input(rbf_node, dest_address)
fulltx = rbf_node.getrawtransaction(rbfid, 1)
bumped_tx = rbf_node.bumpfee(rbfid, {"totalFee": 49900})
full_bumped_tx = rbf_node.getrawtransaction(bumped_tx["txid"], 1)
assert_equal(bumped_tx["fee"], Decimal("0.00050000"))
assert_equal(len(fulltx["vout"]), 2)
assert_equal(len(full_bumped_tx["vout"]), 1) #change output is eliminated
def test_settxfee(rbf_node, dest_address):
# check that bumpfee reacts correctly to the use of settxfee (paytxfee)
rbfid = spend_one_input(rbf_node, dest_address)
requested_feerate = Decimal("0.00025000")
rbf_node.settxfee(requested_feerate)
bumped_tx = rbf_node.bumpfee(rbfid)
actual_feerate = bumped_tx["fee"] * 1000 / rbf_node.getrawtransaction(bumped_tx["txid"], True)["size"]
# Assert that the difference between the requested feerate and the actual
# feerate of the bumped transaction is small.
assert_greater_than(Decimal("0.00001000"), abs(requested_feerate - actual_feerate))
rbf_node.settxfee(Decimal("0.00000000")) # unset paytxfee
def test_rebumping(rbf_node, dest_address):
# check that re-bumping the original tx fails, but bumping the bumper succeeds
rbfid = spend_one_input(rbf_node, dest_address)
bumped = rbf_node.bumpfee(rbfid, {"totalFee": 2000})
assert_raises_rpc_error(-4, "already bumped", rbf_node.bumpfee, rbfid, {"totalFee": 3000})
rbf_node.bumpfee(bumped["txid"], {"totalFee": 3000})
def test_rebumping_not_replaceable(rbf_node, dest_address):
# check that re-bumping a non-replaceable bump tx fails
rbfid = spend_one_input(rbf_node, dest_address)
bumped = rbf_node.bumpfee(rbfid, {"totalFee": 10000, "replaceable": False})
assert_raises_rpc_error(-4, "Transaction is not BIP 125 replaceable", rbf_node.bumpfee, bumped["txid"],
{"totalFee": 20000})
def test_unconfirmed_not_spendable(rbf_node, rbf_node_address):
# check that unconfirmed outputs from bumped transactions are not spendable
rbfid = spend_one_input(rbf_node, rbf_node_address)
rbftx = rbf_node.gettransaction(rbfid)["hex"]
assert rbfid in rbf_node.getrawmempool()
bumpid = rbf_node.bumpfee(rbfid)["txid"]
assert bumpid in rbf_node.getrawmempool()
assert rbfid not in rbf_node.getrawmempool()
# check that outputs from the bump transaction are not spendable
# due to the replaces_txid check in CWallet::AvailableCoins
assert_equal([t for t in rbf_node.listunspent(minconf=0, include_unsafe=False) if t["txid"] == bumpid], [])
# submit a block with the rbf tx to clear the bump tx out of the mempool,
# then call abandon to make sure the wallet doesn't attempt to resubmit the
# bump tx, then invalidate the block so the rbf tx will be put back in the
# mempool. this makes it possible to check whether the rbf tx outputs are
# spendable before the rbf tx is confirmed.
block = submit_block_with_tx(rbf_node, rbftx)
rbf_node.abandontransaction(bumpid)
rbf_node.invalidateblock(block.hash)
assert bumpid not in rbf_node.getrawmempool()
assert rbfid in rbf_node.getrawmempool()
# check that outputs from the rbf tx are not spendable before the
# transaction is confirmed, due to the replaced_by_txid check in
# CWallet::AvailableCoins
assert_equal([t for t in rbf_node.listunspent(minconf=0, include_unsafe=False) if t["txid"] == rbfid], [])
# check that the main output from the rbf tx is spendable after confirmed
rbf_node.generate(1)
assert_equal(
sum(1 for t in rbf_node.listunspent(minconf=0, include_unsafe=False)
if t["txid"] == rbfid and t["address"] == rbf_node_address and t["spendable"]), 1)
def test_bumpfee_metadata(rbf_node, dest_address):
rbfid = rbf_node.sendtoaddress(dest_address, Decimal("0.00100000"), "comment value", "to value")
bumped_tx = rbf_node.bumpfee(rbfid)
bumped_wtx = rbf_node.gettransaction(bumped_tx["txid"])
assert_equal(bumped_wtx["comment"], "comment value")
assert_equal(bumped_wtx["to"], "to value")
def test_locked_wallet_fails(rbf_node, dest_address):
rbfid = spend_one_input(rbf_node, dest_address)
rbf_node.walletlock()
assert_raises_rpc_error(-13, "Please enter the wallet passphrase with walletpassphrase first.",
rbf_node.bumpfee, rbfid)
def spend_one_input(node, dest_address):
tx_input = dict(
sequence=BIP125_SEQUENCE_NUMBER, **next(u for u in node.listunspent() if u["amount"] == Decimal("0.00100000")))
rawtx = node.createrawtransaction(
[tx_input], {dest_address: Decimal("0.00050000"),
node.getrawchangeaddress(): Decimal("0.00049000")})
signedtx = node.signrawtransaction(rawtx)
txid = node.sendrawtransaction(signedtx["hex"])
return txid
def submit_block_with_tx(node, tx):
ctx = CTransaction()
ctx.deserialize(io.BytesIO(hex_str_to_bytes(tx)))
tip = node.getbestblockhash()
height = node.getblockcount() + 1
block_time = node.getblockheader(tip)["mediantime"] + 1
block = blocktools.create_block(int(tip, 16), blocktools.create_coinbase(height), block_time)
block.vtx.append(ctx)
block.rehash()
block.hashMerkleRoot = block.calc_merkle_root()
block.solve()
node.submitblock(bytes_to_hex_str(block.serialize(True)))
return block
if __name__ == "__main__":
BumpFeeTest().main()
| [
"patrick.agbokou@globaleagle.com"
] | patrick.agbokou@globaleagle.com |
83f17e862e437fd1c095d9085de2535ea88bd8bb | ff4641cc193b461564e416deb6dfa29167335b69 | /2/solution/Section2/hello/hello/settings.py | f59064b84da3225df30e5a77ad0a55e3d82997ee | [
"MIT"
] | permissive | cristina-sirbu/CSCI33A-Section | a18c18db3c845e0c5104a2b59cfb17356b6501b6 | c7733eebe9de1a966179fc6734f3eb030571d69a | refs/heads/master | 2022-12-09T11:40:14.016387 | 2020-09-17T12:55:14 | 2020-09-17T12:55:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,077 | py | """
Django settings for hello project.
Generated by 'django-admin startproject' using Django 3.1.1.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ')fbl5bh$y(6wo!ie%z!$=7ur-&4r$#%wb8ukuiq%fzji2w2uj8'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'helloworld',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'hello.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'hello.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
| [
"23kilpatrick23@gmail.com"
] | 23kilpatrick23@gmail.com |
55abf4ab5e4dc9aeb45fffba3cc0b5771cfe3040 | 666cc5c9e7def28b8f0cd9b7d391d7e47503af42 | /Task14_part2.py | ad44f91a20c19a838d9999b5dc584a15659e1a01 | [] | no_license | Hejmat/AdventOfCode | bae04ee75e5cae294c256c71055e0d9b0a43f104 | 57238ecee14c448f408483ec4d63b8145da7ec4b | refs/heads/main | 2023-02-10T13:39:37.756797 | 2021-01-13T18:53:14 | 2021-01-13T18:53:14 | 317,991,042 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,236 | py | ## https://adventofcode.com/2020/day/14
import itertools
import re
file = 'No14_input.txt'
with open(file,'r') as f:
lines = f.read()
inp = ['mask' + e.strip() for e in lines.split('mask') if e]
f.close()
tar = [] #Create target list for filling with the memory and address values
def replacenth(string, substr, repl, n): #Function for replace nth occurrence of substring with replacement string in target string
place = [m.start() for m in re.finditer(substr, string)][n-1] #Find index of the nth occurrence
b = string[:place] #String before the nth occurrence
a = string[place:] #String after the nth occurrence
a = a.replace(substr, str(repl), 1) #Replace the first occurrence in string 'after' the nth occurrence
string = b + a #Concatenate before string and new string
return(string) #return new string
for i in inp: #Loop for each task in input
ii = i.split('\n') #Split task to lines
mask = ii[0].split('=')[1].strip() #First line is mask
nums = [o for o in ii[1:]] #All other lines
for n in nums:
mem = int(n.split('[')[1].split(']')[0].strip()) #Get the memory value from input
x = int(n.split('=')[1].strip()) #Get the number from input
xn = '{:036b}'.format(mem) #Transform integer to string of 36bits
ml = [y for y in mask] #List of each mask position value
xnl = [y for y in xn] #List of each input number position value
z = zip(ml,xnl) # Zip mask values and input values for transformation
new = []
for b in z: #Mask transformations
if b[0] == 'X' and b[1] == '0':
new.append('X')
elif b[0] == 'X' and b[1] == '1':
new.append('X')
elif b[0] == '1' and b[1] == '1':
new.append('1')
elif b[0] == '1' and b[1] == '0':
new.append('1')
elif b[0] == '0' and b[1] == '0':
new.append('0')
elif b[0] == '0' and b[1] == '1':
new.append('1')
c = new.count('X') #Get number of occurrence of 'X' symbol in transformed value
new_string = ''.join(new) #Build string from the transformed list
lst = list(itertools.product([0, 1], repeat=c)) #Find all combinations of 0,1 values (length of the combination is count of X occurrences in transformed value
for ele in lst: #Loop for each combination
temp_tar = []
new_string = ''.join(new) #Rebuild again string from transformed list
for e in ele: #Loop for replacing X symbols with symbols from the actual combination
new_string = replacenth(new_string,'X',e,0)
temp_tar.append(int(new_string, 2)) #Transform binary address to integer and append to first position of actual w index
temp_tar.append(x) #Append the value to second position of actual w index
tar.append(temp_tar)
xx = []
xxx = []
tar.reverse() #Reverse target list to loop from the latest values
for t in tar: #Append only the latest value of the same address
if t[0] not in xx:
xx.append(t[0])
xxx.append(t[1])
print('Part2 result:', sum(xxx))
| [
"noreply@github.com"
] | Hejmat.noreply@github.com |
8627096d1ad2cd95f12f93a46b943c323583a65c | a691d144c127a2e12b13f0eefe661787af06d382 | /backend/Trigonometry.py | 4d9945990977efa66f851b3b6901ef679fd3f3e5 | [] | no_license | alireza561/Calculator | 3e77b3ee387655a2189e9de60e341b72c6de5d21 | 051aecd95cdf843fcab68bf3d82d5e3417b390a1 | refs/heads/master | 2023-06-13T01:32:19.998721 | 2021-07-01T08:40:38 | 2021-07-01T08:40:38 | 381,967,381 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,115 | py | from tkinter import *
import math
class Trigonometry:
def trigonometry(self, method):
try:
my_number = self.entry_box.get()
if method == 'cos':
my_method = math.cos(float(my_number))
if method == 'cosh':
my_method = math.cosh(float(my_number))
if method == 'acosh':
my_method = math.acosh(float(my_number))
if method == 'sin':
my_method = math.sin(float(my_number))
if method == 'sinh':
my_method = math.sinh(float(my_number))
if method == 'asinh':
my_method = math.asinh(float(my_number))
if method == 'tan':
my_method = math.tan(float(my_number))
if method == 'tanh':
my_method = math.tanh(float(my_number))
self.entry_box.delete(0, END)
self.entry_box.insert(0, str(my_method))
self.func_scientific = True
self.g3 = self.entry_box.get()
self.g0 = self.g1
except Exception as e:
pass | [
"aazizi508@gmail.com"
] | aazizi508@gmail.com |
0887c9ddd19bfcac0842bcd6561700fa17136996 | 66c65f78c90c3776b591d1cece5641ff43c33950 | /methods.py | 2d5e4cf77576669b91ced4551b723954b29eff23 | [] | no_license | RaviC19/Dictionaries_Python | e2a6628467978cd18a70903478a5d4245048a870 | 424e8282c74e4a26fbd2e85940d1e6e83af3384b | refs/heads/main | 2023-04-01T03:56:23.149452 | 2021-04-09T06:06:34 | 2021-04-09T06:06:34 | 356,061,482 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 893 | py | # clear
user = {
"name": "Ravi",
"location": "UK",
"age": 30
}
user.clear()
print(user) # returns {}
# copy
numbers = dict(a=1, b=2, c=3)
dupe = numbers.copy()
print(dupe) # {'a': 1, 'b': 2, 'c': 3}
dupe == numbers # True
dupe is numbers # returns False because they are unique objects in memory and not stored in the same place
# fromkeys - creates key-value pairs from comma separated values and is only used on an item object {}
player = {}.fromkeys(["name", "score", "age", "location"], "unknown")
# would return dict {'name': 'unknown', 'score': 'unknown', 'age': 'unknown', 'location': 'unknown'}
print(player)
# get - if a key is in a dictionary it will return the value, if it doesn't exist it will return as None
me = {
"name": "Ravi",
"location": "UK",
"age": 30
}
me.get("name") # Ravi
me.get("phone number") # Wouldn't return anything but is None
| [
"ravic1919@gmail.com"
] | ravic1919@gmail.com |
4d023d32739979e54949f9bde02fbf2db38002e9 | 1c0509a06cec726735048f00f63d2529f5e43ce6 | /code_gasoline_france/functions/panel_regressions/grouputils.py | 23cc67c916d6a1f2fc0095b882ea3baf83e92eb4 | [] | no_license | etiennecha/master_code | e99c62e93aa052a66d4cdd3f3e3aa25a3aec4880 | 48821f6c854a1c6aa05cf81b653b3b757212b6f8 | refs/heads/master | 2021-01-23T14:35:45.904595 | 2018-03-11T18:57:38 | 2018-03-11T18:57:38 | 16,312,906 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 18,072 | py | # -*- coding: utf-8 -*-
"""Tools for working with groups
This provides several functions to work with groups and a Group class that
keeps track of the different representations and has methods to work more
easily with groups.
Author: Josef Perktold,
Author: Nathaniel Smith, recipe for sparse_dummies on scipy user mailing list
Created on Tue Nov 29 15:44:53 2011 : sparse_dummies
Created on Wed Nov 30 14:28:24 2011 : combine_indices
changes: add Group class
Notes
~~~~~
This reverses the class I used before, where the class was for the data and
the group was auxiliary. Here, it is only the group, no data is kept.
sparse_dummies needs checking for corner cases, e.g.
what if a category level has zero elements? This can happen with subset
selection even if the original groups where defined as arange.
Not all methods and options have been tried out yet after refactoring
need more efficient loop if groups are sorted -> see GroupSorted.group_iter
"""
import numpy as np
from statsmodels.compatnp.np_compat import npc_unique
def combine_indices(groups, prefix='', sep='.', return_labels=False):
'''use np.unique to get integer group indices for product, intersection
'''
if isinstance(groups, tuple):
groups = np.column_stack(groups)
else:
groups = np.asarray(groups)
dt = groups.dtype
#print dt
is2d = (groups.ndim == 2) #need to store
if is2d:
ncols = groups.shape[1]
if not groups.flags.c_contiguous:
groups = np.array(groups, order='C')
groups_ = groups.view([('',groups.dtype)]*groups.shape[1])
else:
groups_ = groups
uni, uni_idx, uni_inv = npc_unique(groups_, return_index=True,
return_inverse=True)
if is2d:
uni = uni.view(dt).reshape(-1, ncols)
#avoiding a view would be
# for t in uni.dtype.fields.values():
# assert (t[0] == dt)
#
# uni.dtype = dt
# uni.shape = (uni.size//ncols, ncols)
if return_labels:
label = [(prefix+sep.join(['%s']*len(uni[0]))) % tuple(ii)
for ii in uni]
return uni_inv, uni_idx, uni, label
else:
return uni_inv, uni_idx, uni
#written for and used in try_covariance_grouploop.py
def group_sums(x, group, use_bincount=True):
'''simple bincount version, again
group : array, integer
assumed to be consecutive integers
no dtype checking because I want to raise in that case
uses loop over columns of x
for comparison, simple python loop
'''
x = np.asarray(x)
if x.ndim == 1:
x = x[:,None]
elif x.ndim > 2 and use_bincount:
raise ValueError('not implemented yet')
if use_bincount:
return np.array([np.bincount(group, weights=x[:,col])
for col in range(x.shape[1])])
else:
uniques = np.unique(group)
result = np.zeros([len(uniques)] + list(x.shape[1:]))
for ii, cat in enumerate(uniques):
result[ii] = x[g==cat].sum(0)
return result
def group_sums_dummy(x, group_dummy):
'''sum by groups given group dummy variable
group_dummy can be either ndarray or sparse matrix
'''
if type(group_dummy) is np.ndarray:
return np.dot(x.T, group_dummy)
else: #check for sparse
return x.T * group_dummy
def dummy_sparse(groups):
'''create a sparse indicator from a group array with integer labels
Parameters
----------
groups: ndarray, int, 1d (nobs,)
an array of group indicators for each observation. Group levels are assumed
to be defined as consecutive integers, i.e. range(n_groups) where
n_groups is the number of group levels. A group level with no
observations for it will still produce a column of zeros.
Returns
-------
indi : ndarray, int8, 2d (nobs, n_groups)
an indicator array with one row per observation, that has 1 in the
column of the group level for that observation
Examples
--------
>>> g = np.array([0, 0, 2, 1, 1, 2, 0])
>>> indi = dummy_sparse(g)
>>> indi
<7x3 sparse matrix of type '<type 'numpy.int8'>'
with 7 stored elements in Compressed Sparse Row format>
>>> indi.todense()
matrix([[1, 0, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 0],
[0, 1, 0],
[0, 0, 1],
[1, 0, 0]], dtype=int8)
current behavior with missing groups
>>> g = np.array([0, 0, 2, 0, 2, 0])
>>> indi = dummy_sparse(g)
>>> indi.todense()
matrix([[1, 0, 0],
[1, 0, 0],
[0, 0, 1],
[1, 0, 0],
[0, 0, 1],
[1, 0, 0]], dtype=int8)
'''
from scipy import sparse
indptr = np.arange(len(groups)+1)
data = np.ones(len(groups), dtype=np.int8)
indi = sparse.csr_matrix((data, g, indptr))
return indi
class Group(object):
def __init__(self, group, name=''):
#self.group = np.asarray(group) #TODO: use checks in combine_indices
self.name = name
uni, uni_idx, uni_inv = combine_indices(group)
#TODO: rename these to something easier to remember
self.group_int, self.uni_idx, self.uni = uni, uni_idx, uni_inv
self.n_groups = len(self.uni)
#put this here so they can be overwritten before calling labels
self.separator = '.'
self.prefix = self.name
if self.prefix:
self.prefix = self.prefix + '='
#cache decorator
def counts(self):
return np.bincount(self.group_int)
#cache_decorator
def labels(self):
#is this only needed for product of groups (intersection)?
prefix = self.prefix
uni = self.uni
sep = self.separator
if uni.ndim > 1:
label = [(prefix+sep.join(['%s']*len(uni[0]))) % tuple(ii)
for ii in uni]
else:
label = [prefix + '%s' % ii for ii in uni]
return label
def dummy(self, drop_idx=None, sparse=False, dtype=int):
'''
drop_idx is only available if sparse=False
drop_idx is supposed to index into uni
'''
uni = self.uni
if drop_idx is not None:
idx = range(len(uni))
del idx[drop_idx]
uni = uni[idx]
group = self.group
if not sparse:
return (group[:,None] == uni[None,:]).astype(dtype)
else:
return dummy_sparse(self.group_int)
def interaction(self, other):
if isinstance(other, self.__class__):
other = other.group
return self.__class__((self, other))
def group_sums(self, x, use_bincount=True):
return group_sums(x, self.group_int, use_bincount=use_bincount)
def group_demean(self, x, use_bincount=True):
means_g = group_demean(x/float(nobs), self.group_int,
use_bincount=use_bincount)
x_demeaned = x - means_g[self.group_int] #check reverse_index?
return x_demeaned, means_g
class GroupSorted(Group):
def __init__(self, group, name=''):
super(self.__class__, self).__init__(group, name=name)
idx = (np.nonzero(np.diff(group))[0]+1).tolist()
self.groupidx = groupidx = zip([0]+idx, idx+[len(group)])
ngroups = len(groupidx)
def group_iter(self):
for low, upp in self.groupidx:
yield slice(low, upp)
def lag_indices(self, lag):
'''return the index array for lagged values
Warning: if k is larger then the number of observations for an
individual, then no values for that individual are returned.
TODO: for the unbalanced case, I should get the same truncation for
the array with lag=0. From the return of lag_idx we wouldn't know
which individual is missing.
TODO: do I want the full equivalent of lagmat in tsa?
maxlag or lag or lags.
not tested yet
'''
lag_idx = np.asarray(self.groupidx)[:,1] - lag #asarray or already?
mask_ok = (low <= lag_idx)
#still an observation that belongs to the same individual
return lag_idx[mask_ok]
import pandas as pd
class Grouping():
def __init__(self, index_pandas=None, index_list=None):
'''
index_pandas pandas (multi-)index
index_list list of numpy arrays, pandas series or lists, all of which are
of length nobs
'''
if index_list != None:
try:
index_list = [np.array(x) for x in index_list]
tup = zip(*index_list)
self.index = pd.MultiIndex.from_tuples(tup)
except:
raise Exception("index_list must be a list of lists, pandas series, \
or numpy arrays, each of identitcal length nobs.")
else:
self.index = index_pandas
self.nobs = len(self.index)
self.slices = None
self.index_shape = self.index.levshape
self.index_int = self.index.labels
def reindex(self, index_pandas=None):
if type(index_pandas) in [pd.core.index.MultiIndex, pd.core.index.Index]:
self.index = index_pandas
self.index_shape = self.index.levshape
self.index_int = self.index.labels
else:
raise Exception('index_pandas must be Pandas index')
def get_slices(self):
'''Only works on first index level'''
groups = self.index.get_level_values(0).unique()
self.slices = [self.index.get_loc(x) for x in groups]
def count_categories(self, level=0):
self.counts = np.bincount(self.index_int[level])
def check_index(self, sorted=True, unique=True, index=None):
'''Sanity checks'''
if not index:
index = self.index
if sorted:
test = pd.DataFrame(range(len(index)), index=index)
test_sorted = test.sort()
if any(test.index != test_sorted.index):
raise Exception('Index suggests that data may not be sorted')
if unique:
if len(index) != len(index.unique()):
raise Exception('Duplicate index entries')
def sort(self, data, index=None):
'''Applies a (potentially hierarchical) sort operation on a numpy array
or pandas series/dataframe based on the grouping index or a
user-suplied index. Returns an object of the same type as the original
data as well as the matching (sorted) Pandas index.
'''
if not index:
index = self.index
if type(data) == np.ndarray:
out = pd.DataFrame(data, index=index)
out = out.sort()
return np.array(out), index
elif type(data) in [pd.core.series.Series, pd.core.frame.DataFrame]:
out = data
out.index = index
out = out.sort()
return out, index
else:
msg = 'data must be a Numpy array or a Pandas Series/DataFrame'
raise Exception(msg)
def transform_dataframe(self, dataframe, function, level=0):
'''Apply function to each column, by group
Assumes that the dataframe already has a proper index'''
if dataframe.shape[0] != self.nobs:
raise Exception('dataframe does not have the same shape as index')
out = dataframe.groupby(level=level).apply(function)
if 1 in out.shape:
return np.ravel(out)
else:
return np.array(out)
def transform_array(self, array, function, level=0):
'''Apply function to each column, by group'''
if array.shape[0] != self.nobs:
raise Exception('array does not have the same shape as index')
dataframe = pd.DataFrame(array, index=self.index)
return self.transform_dataframe(dataframe, function, level=level)
def transform_slices(self, array, function, **kwargs):
'''Assumes array is a 1D or 2D numpy array'''
if array.shape[0] != self.nobs:
raise Exception('array does not have the same shape as index')
if self.slices == None:
self.get_slices()
processed = []
for s in self.slices:
if array.ndim == 2:
subset = array[s,:]
elif array.ndim == 1:
subset = array[s]
processed.append(function(subset, s, **kwargs))
return np.concatenate(processed)
def dummy_sparse(self, level=0):
'''create a sparse indicator from a group array with integer labels
Parameters
----------
groups: ndarray, int, 1d (nobs,) an array of group indicators for each
observation. Group levels are assumed to be defined as consecutive
integers, i.e. range(n_groups) where n_groups is the number of
group levels. A group level with no observations for it will still
produce a column of zeros.
Returns
-------
indi : ndarray, int8, 2d (nobs, n_groups)
an indicator array with one row per observation, that has 1 in the
column of the group level for that observation
Examples
--------
>>> g = np.array([0, 0, 2, 1, 1, 2, 0])
>>> indi = dummy_sparse(g)
>>> indi
<7x3 sparse matrix of type '<type 'numpy.int8'>'
with 7 stored elements in Compressed Sparse Row format>
>>> indi.todense()
matrix([[1, 0, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 0],
[0, 1, 0],
[0, 0, 1],
[1, 0, 0]], dtype=int8)
current behavior with missing groups
>>> g = np.array([0, 0, 2, 0, 2, 0])
>>> indi = dummy_sparse(g)
>>> indi.todense()
matrix([[1, 0, 0],
[1, 0, 0],
[0, 0, 1],
[1, 0, 0],
[0, 0, 1],
[1, 0, 0]], dtype=int8)
'''
groups = self.index.labels[level]
indptr = np.arange(len(groups)+1)
data = np.ones(len(groups), dtype=np.int8)
self.dummies = scipy.sparse.csr_matrix((data, groups, indptr))
if __name__ == '__main__':
#---------- examples combine_indices
from numpy.testing import assert_equal
np.random.seed(985367)
groups = np.random.randint(0,2,size=(10,2))
uv, ux, u, label = combine_indices(groups, return_labels=True)
uv, ux, u, label = combine_indices(groups, prefix='g1,g2=', sep=',',
return_labels=True)
group0 = np.array(['sector0', 'sector1'])[groups[:,0]]
group1 = np.array(['region0', 'region1'])[groups[:,1]]
uv, ux, u, label = combine_indices((group0, group1),
prefix='sector,region=',
sep=',',
return_labels=True)
uv, ux, u, label = combine_indices((group0, group1), prefix='', sep='.',
return_labels=True)
group_joint = np.array(label)[uv]
group_joint_expected = np.array(
['sector1.region0', 'sector0.region1', 'sector0.region0',
'sector0.region1', 'sector1.region1', 'sector0.region0',
'sector1.region0', 'sector1.region0', 'sector0.region1',
'sector0.region0'],
dtype='|S15')
assert_equal(group_joint, group_joint_expected)
'''
>>> uv
array([2, 1, 0, 0, 1, 0, 2, 0, 1, 0])
>>> label
['sector0.region0', 'sector1.region0', 'sector1.region1']
>>> np.array(label)[uv]
array(['sector1.region1', 'sector1.region0', 'sector0.region0',
'sector0.region0', 'sector1.region0', 'sector0.region0',
'sector1.region1', 'sector0.region0', 'sector1.region0',
'sector0.region0'],
dtype='|S15')
>>> np.column_stack((group0, group1))
array([['sector1', 'region1'],
['sector1', 'region0'],
['sector0', 'region0'],
['sector0', 'region0'],
['sector1', 'region0'],
['sector0', 'region0'],
['sector1', 'region1'],
['sector0', 'region0'],
['sector1', 'region0'],
['sector0', 'region0']],
dtype='|S7')
'''
#------------- examples sparse_dummies
from scipy import sparse
g = np.array([0, 0, 1, 2, 1, 1, 2, 0])
u = range(3)
indptr = np.arange(len(g)+1)
data = np.ones(len(g), dtype=np.int8)
a = sparse.csr_matrix((data, g, indptr))
print a.todense()
print np.all(a.todense() == (g[:,None] == np.arange(3)).astype(int))
x = np.arange(len(g)*3).reshape(len(g), 3, order='F')
print 'group means'
print x.T * a
print np.dot(x.T, g[:,None] == np.arange(3))
print np.array([np.bincount(g, weights=x[:,col]) for col in range(3)])
for cat in u:
print x[g==cat].sum(0)
for cat in u: x[g==cat].sum(0)
cc = sparse.csr_matrix([[0, 1, 0, 1, 0, 0, 0, 0, 0],
[1, 0, 1, 0, 1, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 1, 0, 0, 0],
[1, 0, 0, 0, 1, 0, 1, 0, 0],
[0, 1, 0, 1, 0, 1, 0, 1, 0],
[0, 0, 1, 0, 1, 0, 0, 0, 1],
[0, 0, 0, 1, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 1, 0, 1, 0, 1],
[0, 0, 0, 0, 0, 1, 0, 1, 0]])
#------------- groupsums
print group_sums(np.arange(len(g)*3*2).reshape(len(g),3,2), g,
use_bincount=False).T
print group_sums(np.arange(len(g)*3*2).reshape(len(g),3,2)[:,:,0], g)
print group_sums(np.arange(len(g)*3*2).reshape(len(g),3,2)[:,:,1], g)
#------------- examples class
x = np.arange(len(g)*3).reshape(len(g), 3, order='F')
mygroup = Group(g)
print mygroup.group_int
print mygroup.group_sums(x)
print mygroup.labels() | [
"echamayou@PC619BND75J.ensae.fr"
] | echamayou@PC619BND75J.ensae.fr |
9828ec4f425f84b9c315512f6de7c6edd7be72a2 | 964017448ad3856bcf2edc4192366cdd29d4840d | /dash-test.py | 3a547875f64df91a4eb14328187191d8a9b6f06a | [] | no_license | haohangxu/morning-dash | 1d25af9f0ca2a677c3d044574a296d4aee8d7de6 | 2f2b4f03a480c09a4e51964859052cbba294e1dd | refs/heads/master | 2021-01-20T20:10:58.628319 | 2018-12-02T22:13:02 | 2018-12-02T22:13:02 | 60,052,209 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 916 | py | #!/usr/bin/env python
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Name: Haohang Xu
# File: dash-tests.py
#
# Listens for Amazon dash button on network.
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
###########################################
### IMPORTS ###
###########################################
from scapy.all import *
###########################################
### FUNCTION DEFS ###
###########################################
def arp_display(pkt):
if pkt[ARP].op == 1: #who-has (request)
if pkt[ARP].psrc == '0.0.0.0': # ARP Probe
print "ARP Probe from: " + pkt[ARP].hwsrc
###########################################
### MAIN FUNCTION ###
###########################################
print sniff(prn=arp_display, filter="arp", store=0, count=10)
| [
"haohang@fb.com"
] | haohang@fb.com |
c1e56baf1648ada2efc3a1536a48b3c997341901 | a83f6a9358c77360ca49edfee476f8fd890a9a35 | /services/waste_stats_processor.py | b7c3a56334b1e94f155540f44e05c5c02ee70724 | [] | no_license | peterkabz/statsApp | d49cacfdb059542bd813398df758a38a516c6339 | 0138a8f6d974ab135cbaeb5c3838c7cbb9e9522d | refs/heads/master | 2023-07-02T18:21:04.883173 | 2021-08-08T08:43:28 | 2021-08-08T08:43:28 | 391,462,032 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,329 | py | """
This method will fetch data from the
"""
from classes.file_column_processor import get_waste_type_labels
from classes.waste_type import WasteType
from common import file_names
from common import values
import services.energy_saved_processor as energy_processor
import pandas as pd
def get_energy_saved():
df = pd.read_csv(file_names.WASTE_STATS)
'''
Get the relevant row within the target years
'''
df = df[(df['year'] >= values.MIN_TARGET_YEAR) & (df['year'] <= values.MAX_TARGET_YEAR)]
result = {}
'''For each year DO:
Sum up all the energy saved for each waste type and set it as the year's total
Add the year to the results dict
'''
for year in range(values.MIN_TARGET_YEAR, values.MAX_TARGET_YEAR + 1):
# Get all records for the current year
current_year_df = df[df["year"] == year]
# Initialize the current year total
year_total = 0
'''
For each waste type
'''
for enum_name, waste_type_enum in WasteType.__members__.items():
waste_type_labels = get_waste_type_labels(enum_name)
# Get the target row for current waste type
target_rows = current_year_df[current_year_df["waste_type"].isin(waste_type_labels)]
print(f"=========START===={waste_type_labels} IN {year}")
print(target_rows)
print(f"=========END===={waste_type_labels} IN {year}")
print("\t\t\t\t")
# Check if row is not empty
if len(target_rows) > 0:
total_recycled = target_rows["total_waste_recycled_tonne"].sum()
print(f"\nTotal recycled for {waste_type_labels} is {total_recycled}")
total_recycled = float(total_recycled)
# Fetch the conversion factor
# Conversion factor is the number of KwH that one metric tonne can produces
conversion_factor = energy_processor.get_conversion_factor(enum_name)
conversion_factor = float(conversion_factor)
energy_saved = \
total_recycled * conversion_factor
year_total += energy_saved
print(energy_saved)
result[year] = year_total
print(result.items())
return result
| [
"50104012+peterkabz@users.noreply.github.com"
] | 50104012+peterkabz@users.noreply.github.com |
8daee683ea662078236cd56c7a9a3836f80635dc | 0b718ad7011b735f88d69cc6ce588952f7e0f72c | /main_app/admin.py | 719851e2268dfbc371e29ae40641ef1db57ca9fa | [] | no_license | Priyanshi-Srivastava1611/Health-App | 9b82e80f92aa2d9c5039823003db458549fd527e | 15004d1ca4761e3308712f2fee6aff4be7c92957 | refs/heads/main | 2023-02-12T16:50:39.435996 | 2021-01-15T14:07:09 | 2021-01-15T14:07:09 | 329,922,189 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 313 | py | from django.contrib import admin
from .models import patient , doctor , diseaseinfo , consultation,rating_review
# Register your models here.
admin.site.register(patient)
admin.site.register(doctor)
admin.site.register(diseaseinfo)
admin.site.register(consultation)
admin.site.register(rating_review)
| [
"noreply@github.com"
] | Priyanshi-Srivastava1611.noreply@github.com |
1f97745f69658ae0f150ad5b83e13d3102374a6d | 85a48b5b46d6cd5a6daa66c31bef9839b1159738 | /disciplinaWebScrapingAv1/spiders/PegarCotacaoDolarUol.py | c12c4947188bfa0701d92d354a75296df0c0decd | [] | no_license | JeanLobo/disciplinaWebScrapingAv1 | 752fcf18005af1a208df7604764879a5055e4294 | e1dcf0a2db7c6267e0a91fb910271620a596b8e5 | refs/heads/master | 2020-12-03T11:30:50.803324 | 2020-01-16T12:04:21 | 2020-01-16T12:04:21 | 231,298,780 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 790 | py | # Avaliação 1 Questão 1
# Implemente um programa que entre no site do UOL e imprima apenas a seguinte
# mensagem: A cotação atual do dólar é: <cotação>, onde <cotação> vai ser o valor
# capturado do site no momento. Procure uma forma de omitir as mensagens de log na
# execução do seu programa para aparecer apenas essa mensagem como saída.
# scrapy crawl PegarCotacaoDolarUol -s LOG_ENABLED=False
import scrapy
class PegarcotacaodolaruolSpider(scrapy.Spider):
name = 'PegarCotacaoDolarUol'
start_urls = ['https://www.uol.com.br/']
def parse(self, response):
dolarCotacaoAtual = response.css(
".HU_currency__quote.HU_currency__quote-up::text"
).extract_first()
print('A cotação atual do dólar é:', dolarCotacaoAtual)
| [
"jeanlobocd@gmail.com"
] | jeanlobocd@gmail.com |
f587962e952b6c5baa41ba213adf385ce62dca0a | 6758529a47e1f379789ddbc487f463e99632afb3 | /provider-node-manager/test-server.py | 32da111eabe8debc9e789494b4d7b6ebecb089c1 | [] | no_license | borisgk98/kubedom | 9a4df4c73fb80d7fd150c73308981bf6b543be31 | 5e6a2e2dd358f108b19c2778355395b9f612ad52 | refs/heads/master | 2023-06-02T20:08:09.926201 | 2021-06-16T10:14:49 | 2021-06-16T10:14:49 | 375,998,590 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,203 | py | import argparse
from http.server import HTTPServer, BaseHTTPRequestHandler
class S(BaseHTTPRequestHandler):
def _set_headers(self):
self.send_response(200)
self.send_header("Content-type", "text/text")
self.end_headers()
def _text(self, message):
"""This just generates an HTML document that includes `message`
in the body. Override, or re-write this do do more interesting stuff.
"""
content = f"{message}"
return content.encode("utf8") # NOTE: must return a bytes object!
def do_GET(self):
self._set_headers()
self.wfile.write(self._text("test"))
def run(server_class=HTTPServer, handler_class=S, port=8000):
server_address = ('', port)
httpd = server_class(server_address, handler_class)
print(f"Starting httpd server on port = {port}")
httpd.serve_forever()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Run a simple HTTP server")
parser.add_argument(
"-p",
"--port",
type=int,
default=8000,
help="Specify the port on which the server listens",
)
args = parser.parse_args()
run(port=args.port) | [
"borisgk98@ya.ru"
] | borisgk98@ya.ru |
98c5ddde89fd231b4f4ad6f4a543e56c8259c2e6 | be5c8b6ed5c0be2bcf5b741095b2bac655bebdac | /api/urls.py | 1bc86182df57051f111a7c101e4a925030022387 | [] | no_license | pavel-piatetskii/game_portal | e28241fd5b997f32ddae315e52c6bbd8f353892a | 20ac41cd95f7381645acc262e8b76b1cfb7d8f58 | refs/heads/master | 2023-06-23T05:32:55.079233 | 2021-07-20T20:40:33 | 2021-07-20T20:40:33 | 380,122,040 | 0 | 0 | null | 2021-07-20T20:04:40 | 2021-06-25T04:18:10 | Python | UTF-8 | Python | false | false | 135 | py | from django.conf.urls import url
from .views import UserView
urlpatterns = [
url('user', UserView.as_view()),
#url('', main)
] | [
"pavel.piatetskii@gmail.com"
] | pavel.piatetskii@gmail.com |
4c5e15fd9822cbc0c71851e74db43be6f4bfc722 | 1626e16760c9c5b5dc9bd7c345871c716d5ffd99 | /Problems/2400_2499/2475_Number_of_Unequal_Triplets_in_Array/Project_Python3/Number_of_Unequal_Triplets_in_Array.py | 4242af6250379a0c5a304c43d89f7b0342a51492 | [] | no_license | NobuyukiInoue/LeetCode | 94ddb19e63cb8d0775cdc13f311fe90c87a1d718 | 3f0ffd519404165fd1a735441b212c801fd1ad1e | refs/heads/master | 2023-09-01T07:38:50.939942 | 2023-08-23T09:51:17 | 2023-08-23T09:51:17 | 158,100,912 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,432 | py | # coding: utf-8
import collections
import os
import sys
import time
from typing import List, Dict, Tuple
class Solution:
def unequalTriplets(self, nums: List[int]) -> int:
# 35ms - 71ms
trips = pairs = 0
cnts = collections.Counter()
for i, num in enumerate(nums):
trips += pairs - cnts[num] * (i - cnts[num])
pairs += i - cnts[num]
cnts[num] += 1
return trips
def main():
argv = sys.argv
argc = len(argv)
if argc < 2:
print("Usage: python {0} <testdata.txt>".format(argv[0]))
exit(0)
if not os.path.exists(argv[1]):
print("{0} not found...".format(argv[1]))
exit(0)
testDataFile = open(argv[1], "r")
lines = testDataFile.readlines()
for temp in lines:
temp = temp.strip()
if temp == "":
continue
print("args = {0}".format(temp))
loop_main(temp)
# print("Hit Return to continue...")
# input()
def loop_main(temp):
flds = temp.replace("[","").replace("]","").replace(", ",",").rstrip()
nums = [int(n) for n in flds.split(",")]
print("nums = {0}".format(nums))
sl = Solution()
time0 = time.time()
result = sl.unequalTriplets(nums)
time1 = time.time()
print("result = {0:d}".format(result))
print("Execute time ... : {0:f}[s]\n".format(time1 - time0))
if __name__ == "__main__":
main()
| [
"spring555@gmail.com"
] | spring555@gmail.com |
7ef87f2840aac39b20362954bbcc1bfdaf8f6e62 | 4fbd0d7c0c42166d9c3c2c7f822b2f0bf57f68d1 | /Python A-level/SH1/Worksheet 2/Set 2/14.prime.py | f31ec109a43cb414175c80084940c905b99815dc | [] | no_license | japnitahuja/Programming-Practice | bf96a800dfc348084cb55efb7968cc68b5626324 | c05de81a84b7df1453e00a774c4a1836ebcecaeb | refs/heads/master | 2022-02-19T07:08:30.300158 | 2019-09-12T06:21:14 | 2019-09-12T06:21:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 538 | py | n = int(input("Enter the number: "))
def prime_iter(n):
for i in range(2,int(pow(n,.5))+1):
if n%i == 0:
return False
return True
def prime_recur(n,k=3):
if n==2:
return True
elif n%k == 0 or n%2==0:
return False
elif k >= int(pow(n,.5)):
return True
return prime_recur(n,k+1)
print("Iteratively: ")
if prime_iter(n):
print("Prime")
else:
print("Composite")
print("Recursively: ")
if prime_recur(n)==True:
print("Prime")
else:
print("Composite")
| [
"japnit.ahuja@gmail.com"
] | japnit.ahuja@gmail.com |
0fd0f2a43c0418b7a5f78ce2185ab12cc49b5b31 | 62a2e25e04d28192117c6c4d5d6cabb10096f55b | /100Liked/Easy/SaleStock.py | 7464cd9af2334aef35bbf9b943fe3387346a6736 | [] | no_license | liujiahuan94/LeetCode | 381b6c4fc28917f6d039fcd5020fd26034024e09 | 8ece3d9495cb08e0cd1aa0276e9c84d53f9e39a9 | refs/heads/main | 2023-08-04T05:53:51.983737 | 2021-09-13T14:16:50 | 2021-09-13T14:16:50 | 343,422,985 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 270 | py | def maxProfit(sprices: List[int]) -> int:
if len(prices) < 2:
return 0
min_price = prices[0]
max_profit = 0
for i in prices:
min_price = min(i, min_price)
max_profit = max(max_profit, i - min_price)
return max_profit | [
"740988959@qq.com"
] | 740988959@qq.com |
142d7634bc571164ed28dbfa46f1b970ed2a6839 | d6bbd5f30a11aad10adac188cb45bf08fc529834 | /Fibonacci.py | 1ad4c07dfd9867d1e481ca1c6294709521c5db18 | [] | no_license | jeyaprakash1/python_programs | aecd0c9dfeb14d4c0d94066a5b813846bab14d1a | 18378bd71a14b158d789ef377179cfa90da22f4b | refs/heads/master | 2023-03-27T11:52:35.027165 | 2021-03-30T12:18:04 | 2021-03-30T12:18:04 | 352,088,245 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 131 | py | # fibbonaci series
f,s=0,1
i=0
print(f,s,end=" ")
while i<5:
t=f+s
print(t ,end=" ")
f=s
s=t
i+=1
| [
"jpofficial1232@gmail.com"
] | jpofficial1232@gmail.com |
d2ffb8597a0d04e3ae245321f7dce967753eb0a2 | 35580ddab92d76862240649bbb91b8e45f330fb0 | /src/srctools/vpk.py | 84789b56fd842cb84326bbf8ea05220628e469d0 | [
"MIT"
] | permissive | TeamSpen210/srctools | 954328566e3ea25e1b88e73c55c93036b133cd76 | 3969e869673e3c76b4bc663d1f73c56a3585f228 | refs/heads/master | 2023-08-28T23:04:28.849165 | 2023-08-26T06:48:44 | 2023-08-26T06:48:44 | 60,130,807 | 44 | 18 | NOASSERTION | 2023-06-18T22:28:05 | 2016-05-31T23:36:26 | Python | UTF-8 | Python | false | false | 25,735 | py | """Classes for reading and writing Valve's VPK format, version 1."""
from typing import IO, Dict, Final, Iterable, Iterator, List, Optional, Tuple, Type, Union
from enum import Enum
from types import TracebackType
import operator
import os
import struct
import attrs
from srctools.binformat import EMPTY_CHECKSUM, checksum, struct_read
__all__ = [
'VPK_SIG', 'DIR_ARCH_INDEX', 'OpenModes',
'script_write', 'get_arch_filename',
'FileInfo', 'VPK',
]
VPK_SIG: Final = 0x55aa1234 #: The first byte of VPK files.
DIR_ARCH_INDEX: Final = 0x7fff #: The file index used for the ``_dir`` file.
FileName = Union[str, Tuple[str, str], Tuple[str, str, str]]
class OpenModes(Enum):
"""Modes for opening VPK files."""
READ = 'r'
WRITE = 'w'
APPEND = 'a'
@property
def writable(self) -> bool:
"""Check if this mode allows modifying the VPK."""
return self.value in 'wa'
def iter_nullstr(file: IO[bytes]) -> Iterator[str]:
"""Read a null-terminated ASCII string from the file.
This continuously yields strings, with empty strings
indicting the end of a section.
"""
chars = bytearray()
while True:
char = file.read(1)
if char == b'\x00':
string = chars.decode('ascii', 'surrogateescape')
chars.clear()
if string == ' ': # Blank strings are saved as ' '
yield ''
elif string == '':
return # Actual blanks end the array.
else:
yield string
elif char == b'':
raise Exception(f'Reached EOF without null-terminator in {bytes(chars)!r}!')
else:
chars.extend(char)
def _write_nullstring(file: IO[bytes], string: str) -> None:
"""Write a null-terminated ASCII string back to the file."""
if string:
file.write(string.encode('ascii', 'surrogateescape') + b'\x00')
else:
# Empty strings are written as a space.
file.write(b' \x00')
def get_arch_filename(prefix: str = 'pak01', index: Optional[int] = None) -> str:
"""Generate the name for a VPK file.
Prefix is the name of the file, usually 'pak01'.
index is the index of the data file, or None for the directory.
"""
if index is None:
return prefix + '_dir.vpk'
else:
return f'{prefix}_{index:>03}.vpk'
def _get_file_parts(value: FileName, relative_to: str = '') -> Tuple[str, str, str]:
"""Get folder, name, ext parts from a string/tuple.
Possible arguments:
'fold/ers/name.ext'
('fold/ers', 'name.ext')
('fold/ers', 'name', 'ext')
"""
path: str
filename: str
ext: str
if isinstance(value, str):
path, filename = os.path.split(value)
ext = ''
elif len(value) == 2:
path, filename = value # type: ignore # len() can't narrow.
ext = ''
else:
path, filename, ext = value # type: ignore # len() can't narrow.
if not ext and '.' in filename:
filename, ext = filename.rsplit('.', 1)
if relative_to:
path = os.path.relpath(path, relative_to)
# Strip '/' off the end, and './' from the beginning.
path = os.path.normpath(path).replace('\\', '/').rstrip('/')
# Special case - empty path gets returned as '.'...
if path == '.':
path = ''
return path, filename, ext
def _join_file_parts(path: str, filename: str, ext: str) -> str:
"""Join together path components to the full path.
Any of the segments can be blank, to skip them.
"""
return f"{path}{'/' if path else ''}{filename}{'.' if ext else ''}{ext}"
def _check_is_ascii(value: str) -> bool:
"""VPK filenames must be ascii, it doesn't store or care about encoding.
Allow the surrogateescape bytes also, so roundtripping existing VPKs is
allowed.
"""
for char in value:
# Do straightforward string comparison, only call ord for the surrogate-escape bytes
# which can't be direct constants.
if char >= '\x80' and not (0xDC80 <= ord(char) <= 0xDCFF):
return False
return True
@attrs.define(eq=False)
class FileInfo:
"""Represents a file stored inside a VPK.
Do not call the constructor, it is only meant for VPK's use.
"""
vpk: 'VPK'
dir: str = attrs.field(on_setattr=attrs.setters.frozen)
_filename: str = attrs.field(on_setattr=attrs.setters.frozen)
ext: str = attrs.field(on_setattr=attrs.setters.frozen)
crc: int
arch_index: Optional[int] # pack_01_000.vpk file to use, or None for _dir.
offset: int # Offset into the archive file, including directory data if in _dir
arch_len: int # Number of bytes in archive files
start_data: bytes # The bytes saved into the directory header
@property
def filename(self) -> str:
"""The full filename for this file."""
return _join_file_parts(self.dir, self._filename, self.ext)
name = filename
def __repr__(self) -> str:
return f'<VPK File: "{_join_file_parts(self.dir, self._filename, self.ext)}">'
@property
def size(self) -> int:
"""The total size of this file."""
return self.arch_len + len(self.start_data)
def read(self) -> bytes:
"""Return the contents for this file."""
if self.arch_len:
if self.arch_index is None:
return self.start_data + self.vpk.footer_data[self.offset: self.offset + self.arch_len]
else:
arch_file = get_arch_filename(self.vpk.file_prefix, self.arch_index)
with open(os.path.join(self.vpk.folder, arch_file), 'rb') as data:
data.seek(self.offset)
return self.start_data + data.read(self.arch_len)
else:
return self.start_data
def verify(self) -> bool:
"""Check this file matches the checksum."""
chk = checksum(self.start_data)
if self.arch_len:
if self.arch_index is None:
chk = checksum(
self.vpk.footer_data[self.offset: self.offset + self.arch_len],
chk
)
else:
arch_file = get_arch_filename(self.vpk.file_prefix, self.arch_index)
with open(os.path.join(self.vpk.folder, arch_file), 'rb') as data:
data.seek(self.offset)
chk = checksum(
data.read(self.arch_len),
chk,
)
return chk == self.crc
def write(self, data: bytes, arch_index: Optional[int] = None) -> None:
"""Replace this file with the given byte data.
arch_index is the pak_01_000 file to put data into (or None for _dir).
If this file already exists in the VPK, the old data is not removed.
For this reason VPK writes should be done once per file if possible.
"""
if not self.vpk.mode.writable:
raise ValueError(f"VPK mode {self.vpk.mode.name} does not allow writing!")
# Split the file based on a certain limit.
new_checksum = checksum(data)
if new_checksum == self.crc:
return # Same data, don't do anything.
self.crc = new_checksum
self.start_data = data[:self.vpk.dir_limit]
arch_data = data[self.vpk.dir_limit:]
self.arch_len = len(arch_data)
if self.arch_len:
self.arch_index = arch_index
arch_file = get_arch_filename(self.vpk.file_prefix, arch_index)
with open(os.path.join(self.vpk.folder, arch_file), 'ab') as file:
self.offset = file.seek(0, os.SEEK_END)
file.write(arch_data)
else:
# Only stored in the main index
self.arch_index = None
self.offset = 0
class VPK:
"""Represents a VPK file set in a directory."""
folder: str
"""The directory the VPK is located in, used to find the numeric files."""
file_prefix: str
"""The VPK filename, without ``_dir.vpk``."""
# fileinfo[extension][directory][filename]
_fileinfo: Dict[str, Dict[str, Dict[str, FileInfo]]]
mode: OpenModes
"""How the file was opened.
- Read mode, the file will not be modified and it must already exist.
- Write mode will create the directory if needed.
- Append mode will also create the directory, but not wipe the file.
"""
dir_limit: Optional[int]
"""
The maximum amount of data for files saved to the dir file.
- :external:py:data:`None`: No limit.
- ``0``: Save all to a data file.
"""
footer_data: bytes
"""
The block of data after the header, which contains the file data for files stored in the
``_dir`` file, not numeric files.
"""
version: int
"""The VPK version, 1 or 2."""
def __init__(
self,
dir_file: Union[str, 'os.PathLike[str]'],
*,
mode: Union[OpenModes, str] = 'r',
dir_data_limit: Optional[int] = 1024,
version: int = 1,
) -> None:
"""Create a VPK file.
:param dir_file: The path to the directory file. This must end in ``_dir.vpk``.
:param mode: The (r)ead, (w)rite or (a)ppend mode.
:param dir_data_limit: The maximum amount of data to save in the dir file.
:param version: The desired version if the file is not read.
"""
if version not in (1, 2):
raise ValueError(f"Invalid version ({version}) - must be 1 or 2!")
self.folder = self.file_prefix = ''
# Calls the property which sets the above correctly and checks the type.
self.path = dir_file
# fileinfo[extension][directory][filename]
self._fileinfo = {}
self.mode = OpenModes(mode)
self.dir_limit = dir_data_limit
self.footer_data = b''
self.version = version
self.load_dirfile()
def _check_writable(self) -> None:
"""Verify that this is writable."""
if not self.mode.writable:
raise ValueError(f"VPK mode {self.mode.name} does not allow writing!")
@property
def path(self) -> Union[str, 'os.PathLike[str]']: # TODO: Incorrect, Mypy doesn't have 2-type properties.
"""The filename of the directory VPK file.
This can be assigned to set :py:attr:`folder` and :py:attr:`file_prefix`.
"""
return os.path.join(self.folder, self.file_prefix + '_dir.vpk')
@path.setter
def path(self, path: Union[str, 'os.PathLike[str]']) -> None:
"""Set the location and folder from the directory VPK file."""
folder, filename = os.path.split(path)
if not filename.endswith('_dir.vpk'):
raise Exception('Must create with a _dir VPK file!')
self.folder = folder
self.file_prefix = filename[:-8]
def load_dirfile(self) -> None:
"""Read in the directory file to get all filenames. This erases all changes in the file."""
if self.mode is OpenModes.WRITE:
# Erase the directory file, we ignore current contents.
open(self.path, 'wb').close()
self.version = 1
return
try:
dirfile = open(self.path, 'rb')
except FileNotFoundError:
if self.mode is OpenModes.APPEND:
# No directory file - generate a blank file.
open(self.path, 'wb').close()
self.version = 1
return
else:
raise # In read mode, don't overwrite and error when reading.
with dirfile:
vpk_sig, version, tree_length = struct_read('<III', dirfile)
if vpk_sig != VPK_SIG:
raise ValueError('Bad VPK directory signature!')
if version not in (1, 2):
raise ValueError(f"Bad VPK version {self.version}!")
self.version = version
if version >= 2:
(
data_size,
ext_md5_size,
dir_md5_size,
sig_size,
) = struct_read('<4I', dirfile)
header_len = dirfile.tell() + tree_length
self._fileinfo.clear()
entry = struct.Struct('<IHHIIH')
# Read directory contents
# These are in a tree of extension, directory, file. '' terminates a part.
for ext in iter_nullstr(dirfile):
try:
ext_dict = self._fileinfo[ext]
except KeyError:
ext_dict = self._fileinfo[ext] = {}
for directory in iter_nullstr(dirfile):
try:
dir_dict = ext_dict[directory]
except KeyError:
dir_dict = ext_dict[directory] = {}
for file in iter_nullstr(dirfile):
crc, index_len, arch_ind, offset, arch_len, end = entry.unpack(dirfile.read(entry.size))
if arch_ind == DIR_ARCH_INDEX:
arch_ind = None
if arch_len == 0:
offset = 0
if end != 0xffff:
raise Exception(
f'"{_join_file_parts(directory, file, ext)}" has bad terminator! '
f'{(crc, index_len, arch_ind, offset, arch_len, end)}'
)
dir_dict[file] = FileInfo(
self,
directory,
file,
ext,
crc,
arch_ind,
offset,
arch_len,
dirfile.read(index_len),
)
# 1 for the ending b'' section
if dirfile.tell() + 1 == header_len:
dirfile.read(1) # Skip null byte.
break
self.footer_data = dirfile.read()
def write_dirfile(self) -> None:
"""Write the directory file with the changes. This must be performed after writing to the VPK."""
self._check_writable()
if self.version > 1:
raise NotImplementedError("Can't write V2 VPKs!")
# We don't know how big the directory section is, so we first write the directory,
# then come back and overwrite the length value.
with open(self.path, 'wb') as file:
file.write(struct.pack('<III', VPK_SIG, self.version, 0))
header_len = file.tell()
key_getter = operator.itemgetter(0)
# Write in sorted order - not required, but this ensures multiple
# saves are deterministic.
for ext, folders in sorted(self._fileinfo.items(), key=key_getter):
if not folders:
continue
_write_nullstring(file, ext)
for folder, files in sorted(folders.items(), key=key_getter):
if not files:
continue
_write_nullstring(file, folder)
for filename, info in sorted(files.items(), key=key_getter):
_write_nullstring(file, filename)
if info.arch_index is None:
arch_ind = DIR_ARCH_INDEX
else:
arch_ind = info.arch_index
file.write(struct.pack(
'<IHHIIH',
info.crc,
len(info.start_data),
arch_ind,
info.offset,
info.arch_len,
0xffff,
))
file.write(info.start_data)
# Each block is terminated by an empty null-terminated
# string -> one null byte.
file.write(b'\x00')
file.write(b'\x00')
file.write(b'\x00')
# Calculate the length of the header..
dir_len = file.tell() - header_len
file.write(self.footer_data)
# Write the directory size now we know it.
file.seek(struct.calcsize('<II')) # Skip signature and version
file.write(struct.pack('<I', dir_len))
def __enter__(self) -> 'VPK':
return self
def __exit__(
self,
exc_type: Optional[Type[BaseException]],
exc_value: Optional[BaseException],
exc_trace: Optional[TracebackType],
) -> None:
"""When exiting a context sucessfully, the index will be saved."""
if exc_type is None and self.mode.writable:
self.write_dirfile()
def __getitem__(self, item: FileName) -> FileInfo:
"""Get the FileInfo object for a file.
Possible arguments:
vpk['folders/name.ext']
vpk['folders', 'name.ext']
vpk['folders', 'name', 'ext']
"""
path, filename, ext = _get_file_parts(item)
try:
return self._fileinfo[ext][path][filename]
except KeyError:
raise KeyError(
f'No file "{_join_file_parts(path, filename, ext)}"!'
) from None
def __delitem__(self, item: FileName) -> None:
"""Delete a file.
Possible arguments:
del vpk['folders/name.ext']
del vpk['folders', 'name.ext']
del vpk['folders', 'name', 'ext']
"""
self._check_writable()
path, filename, ext = _get_file_parts(item)
try:
folders = self._fileinfo[ext]
files = folders[path]
files.pop(filename)
except KeyError:
raise KeyError(
f'No file "{_join_file_parts(path, filename, ext)}"!'
) from None
if not files:
# Clear this folder.
folders.pop(path)
if not folders:
# Clear extension too.
self._fileinfo.pop(ext)
def __iter__(self) -> Iterator[FileInfo]:
"""Yield all FileInfo objects."""
for folders in self._fileinfo.values():
for files in folders.values():
yield from files.values()
def filenames(self, ext: str = '', folder: str = '') -> Iterator[str]:
"""Yield filenames from this VPK.
If an extension or folder is specified, only files with this extension
or in this folder are returned.
"""
all_folders: Iterable[Dict[str, Dict[str, FileInfo]]]
if ext:
all_folders = [self._fileinfo.get(ext, {})]
else:
all_folders = self._fileinfo.values()
for folders in all_folders:
for subfolder, files in folders.items():
if not subfolder.startswith(folder):
continue
for info in files.values():
yield info.filename
def fileinfos(self, ext: str = '', folder: str = '') -> Iterator[FileInfo]:
"""Yield file info objects from this VPK.
If an extension or folder is specified, only files with this extension
or in this folder are returned.
"""
all_folders: Iterable[Dict[str, Dict[str, FileInfo]]]
if ext:
all_folders = [self._fileinfo.get(ext, {})]
else:
all_folders = self._fileinfo.values()
for folders in all_folders:
for subfolder, files in folders.items():
if not subfolder.startswith(folder):
continue
yield from files.values()
def __len__(self) -> int:
"""Returns the number of files we have."""
count = 0
for folders in self._fileinfo.values():
for files in folders.values():
count += len(files)
return count
def __contains__(self, item: FileName) -> bool:
"""Check if the specified filename is present in the VPK."""
path, filename, ext = _get_file_parts(item)
try:
return filename in self._fileinfo[ext][path]
except KeyError:
return False
def extract_all(self, dest_dir: str) -> None:
"""Extract the contents of this VPK to a directory."""
for folders in self._fileinfo.values():
for folder, files in folders.items():
os.makedirs(os.path.join(dest_dir, folder), exist_ok=True)
for info in files.values():
with open(os.path.join(dest_dir, info.filename), 'wb') as f:
f.write(info.read())
def new_file(self, filename: FileName, root: str = '') -> FileInfo:
"""Create the given file, making it empty by default.
If root is set, files are treated as relative to there,
otherwise the filename must be relative.
FileExistsError will be raised if the file is already present.
"""
self._check_writable()
path, name, ext = _get_file_parts(filename, root)
if not _check_is_ascii(path) or not _check_is_ascii(name) or not _check_is_ascii(ext):
raise ValueError(f'VPK filename {filename!r} must be ASCII format!')
try:
ext_infos = self._fileinfo[ext]
except KeyError:
ext_infos = self._fileinfo[ext] = {}
try:
dir_infos = ext_infos[path]
except KeyError:
dir_infos = ext_infos[path] = {}
if name in dir_infos:
raise FileExistsError(
f'Filename already exists! ({_join_file_parts(path, name, ext)!r})'
)
dir_infos[name] = info = FileInfo(
self,
path,
name,
ext,
EMPTY_CHECKSUM,
None, 0, 0, b'',
)
return info
def add_file(
self,
filename: FileName,
data: bytes,
root: str = '',
arch_index: Optional[int] = 0,
) -> None:
"""Add the given data to the VPK.
If root is set, files are treated as relative to there,
otherwise the filename must be relative.
arch_index is the pak01_xxx file to copy this to, if the length
is larger than self.dir_limit. If None it's written to the _dir file.
FileExistsError will be raised if the file is already present.
"""
self.new_file(filename, root).write(data, arch_index)
def add_folder(self, folder: str, prefix: str = '') -> None:
"""Write all files in a folder to the VPK.
If prefix is set, the folders will be written to that subfolder.
"""
self._check_writable()
if prefix:
prefix = prefix.replace('\\', '/')
for subfolder, _, filenames, in os.walk(folder):
# Prefix + subfolder relative to the folder.
# normpath removes '.' and similar values from the beginning
vpk_path = os.path.normpath(
os.path.join(
prefix,
os.path.relpath(subfolder, folder)
)
)
for filename in filenames:
with open(os.path.join(subfolder, filename), 'rb') as f:
self.add_file((vpk_path, filename), f.read())
def verify_all(self) -> bool:
"""Check all files have a correct checksum."""
return all(file.verify() for file in self)
def script_write(args: List[str]) -> None:
"""Create a VPK archive."""
if len(args) not in (1, 2):
raise ValueError("Usage: make_vpk.py [max_arch_mb] <folder>")
folder = args[-1]
vpk_name_base = folder.rstrip('\\/_dir')
if len(args) > 1:
arch_len = int(args[0]) * 1024 * 1024
else:
arch_len = 100 * 1024 * 1024
current_arch = 1
vpk_folder, vpk_name = os.path.split(vpk_name_base)
for filename in os.listdir(vpk_folder):
if filename.startswith(vpk_name + '_'):
print(f'removing existing "{filename}"')
os.remove(os.path.join(vpk_folder, filename))
with VPK(vpk_name_base + '_dir.vpk', mode='w') as vpk:
arch_filename = get_arch_filename(vpk_name_base, current_arch)
for subfolder, _, filenames, in os.walk(folder):
# normpath removes '.' and similar values from the beginning
vpk_path = os.path.normpath(os.path.relpath(subfolder, folder))
print(vpk_path + '/')
for filename in filenames:
print('\t' + filename)
with open(os.path.join(subfolder, filename), 'rb') as f:
vpk.add_file(
(vpk_path, filename),
f.read(),
arch_index=current_arch,
)
if os.path.exists(arch_filename) and os.stat(arch_filename).st_size > arch_len:
current_arch += 1
arch_filename = get_arch_filename(vpk_name_base, current_arch)
# This function requires accumulating a character at a time, parsing the VPK
# is very slow without a speedup.
_Py_iter_nullstr = _Cy_iter_nullstr = iter_nullstr
try:
from srctools._tokenizer import _VPK_IterNullstr as _Cy_iter_nullstr # type: ignore # noqa
iter_nullstr = _Cy_iter_nullstr
except ImportError:
pass
if __name__ == '__main__':
import sys
script_write(sys.argv[1:])
| [
"spencerb21@live.com"
] | spencerb21@live.com |
7a051dc777292d44f2d667785fbaf2ffb27928b2 | 4bda6944230003e3976f3ba2c92fe302ea167293 | /src/day22/solution.py | 874756da68b96e2d4e5430c66a0f899226593a7c | [
"MIT"
] | permissive | justinhsg/AoC2020 | 3ba67458cd4d65b8bbc07aaf1bf90f8f16505c90 | 31ede3397eb62c26c2dc78b010f5ee9f0cd919a7 | refs/heads/master | 2023-02-06T01:49:37.519680 | 2020-12-26T17:33:12 | 2020-12-26T17:33:12 | 317,487,500 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,994 | py | import sys
import os
import re
from collections import deque
day_number = sys.path[0].split('\\')[-1]
if len(sys.argv)==1:
path_to_source = os.path.join("\\".join(sys.path[0].split("\\")[:-2]), f"input\\{day_number}")
else:
path_to_source = os.path.join("\\".join(sys.path[0].split("\\")[:-2]), f"sample\\{day_number}")
with open(path_to_source, "r") as infile:
players = infile.read().split("\n\n")
player1 = deque(map(int, players[0].split("\n")[1:]))
player2 = deque(map(int, players[1].split("\n")[1:]))
while(len(player1) * len(player2) != 0):
top1 = player1.popleft()
top2 = player2.popleft()
if(top1 > top2):
player1.append(top1)
player1.append(top2)
else:
player2.append(top2)
player2.append(top1)
winner = player1 if len(player2) == 0 else player2
i = len(winner)
part1 = 0
while(len(winner)!=0):
part1 += i*winner.popleft()
i-=1
with open(os.path.join(sys.path[0], 'input' if len(sys.argv)==1 else 'sample'), "r") as infile:
players = infile.read().split("\n\n")
player1 = deque(map(int, players[0].split("\n")[1:]))
player2 = deque(map(int, players[1].split("\n")[1:]))
def sub_game(p1, p2):
prev_rounds = set()
while(len(p1)*len(p2) != 0):
if (tuple(p1), tuple(p2)) in prev_rounds:
return (True, None)
prev_rounds.add((tuple(p1), tuple(p2)))
t1 = p1.popleft()
t2 = p2.popleft()
if(t1 <= len(p1) and t2 <= len(p2)):
winner, _ = sub_game(deque(list(p1)[:t1]), deque(list(p2)[:t2]))
else:
winner = t1 > t2
if(winner):
p1.append(t1)
p1.append(t2)
else:
p2.append(t2)
p2.append(t1)
if(len(p1) == 0):
return (False, p2.copy())
else:
return (True, p1.copy())
_, winner = sub_game(player1, player2)
i = len(winner)
part2 = 0
while(len(winner)!=0):
part2 += i*winner.popleft()
i-=1
print(part1)
print(part2) | [
"justinhsg@gmail.com"
] | justinhsg@gmail.com |
1e3cbeeaf63e86a69afa809dea93d51e0f8637d7 | 1ecacf92ff7ed5476dc5d88ce2a96f8bc34c642a | /py4e-Ch3Part2.py | 6ada8d030776ec71fbfe9ef0809a9d40cca5a476 | [] | no_license | singclare/py-py4e | 8d4057606b8728951ad46bd901681fabb02d9024 | 43dcf23b4b0ec781429df1a7ac93eba5bfa1ec1a | refs/heads/master | 2020-05-30T22:23:23.408580 | 2019-06-04T07:15:04 | 2019-06-04T07:15:04 | 189,992,826 | 0 | 0 | null | 2019-06-04T07:15:05 | 2019-06-03T11:32:33 | Python | UTF-8 | Python | false | false | 1,102 | py | #Conditionals#
##Multi-way
#elif: 'if' condtion is false >> elif do condtion
if x < 2 :
print('small')
elif x < 10 :
print('Medium')
else :
print('LARGE')
print('All done')
# if x=5, it print 'Medium' / if x=0, it print 'small'
# 'else' activate when all condition is false.
# When you use 'elif', you attend order
##The try / except Structure
# You surround a dangerous section of code with 'try' and 'except'
# If the code in the try works - the except is skipped
# If the code in the try fails - it jumps to the except section
astr = 'Hello Bob'
try:
istr = int(astr)
except:
istr = -1 # except code activates
print('First', istr)
astr = '123'
try:
istr = int(astr) # try code activates
except:
istr = -1
print('Second', istr)
#But you don't abuse 'try' sentence
astr = 'Bob'
try:
print('Hello')
istr = int(astr)
print('There')
except:
istr = -1
print('Done', istr)
##Sample try / except
rawstr = input('Enter a number: ')
try:
ival = int(rawstr)
except:
ival = -1
if ival > 0 :
print('Nice work')
else :
print('Not a Number')
| [
"grochi1995@gmail.com"
] | grochi1995@gmail.com |
a0734bf095a97365a24c7c0c3a07de02f71561a0 | a838d4bed14d5df5314000b41f8318c4ebe0974e | /sdk/automanage/azure-mgmt-automanage/azure/mgmt/automanage/models/_models.py | 4a02132654d4953ef71138b04fa109e55841e150 | [
"MIT",
"LicenseRef-scancode-generic-cla",
"LGPL-2.1-or-later"
] | permissive | scbedd/azure-sdk-for-python | ee7cbd6a8725ddd4a6edfde5f40a2a589808daea | cc8bdfceb23e5ae9f78323edc2a4e66e348bb17a | refs/heads/master | 2023-09-01T08:38:56.188954 | 2021-06-17T22:52:28 | 2021-06-17T22:52:28 | 159,568,218 | 2 | 0 | MIT | 2019-08-11T21:16:01 | 2018-11-28T21:34:49 | Python | UTF-8 | Python | false | false | 26,908 | py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from azure.core.exceptions import HttpResponseError
import msrest.serialization
class Resource(msrest.serialization.Model):
"""Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Fully qualified resource Id for the resource. Ex -
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.
:vartype id: str
:ivar name: The name of the resource.
:vartype name: str
:ivar type: The type of the resource. Ex- Microsoft.Compute/virtualMachines or
Microsoft.Storage/storageAccounts.
:vartype type: str
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(Resource, self).__init__(**kwargs)
self.id = None
self.name = None
self.type = None
class TrackedResource(Resource):
"""The resource model definition for a ARM tracked top level resource.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar id: Fully qualified resource Id for the resource. Ex -
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.
:vartype id: str
:ivar name: The name of the resource.
:vartype name: str
:ivar type: The type of the resource. Ex- Microsoft.Compute/virtualMachines or
Microsoft.Storage/storageAccounts.
:vartype type: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param location: Required. The geo-location where the resource lives.
:type location: str
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
'location': {'required': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'location': {'key': 'location', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(TrackedResource, self).__init__(**kwargs)
self.tags = kwargs.get('tags', None)
self.location = kwargs['location']
class Account(TrackedResource):
"""Definition of the Automanage account.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar id: Fully qualified resource Id for the resource. Ex -
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.
:vartype id: str
:ivar name: The name of the resource.
:vartype name: str
:ivar type: The type of the resource. Ex- Microsoft.Compute/virtualMachines or
Microsoft.Storage/storageAccounts.
:vartype type: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param location: Required. The geo-location where the resource lives.
:type location: str
:param identity: The identity of the Automanage account.
:type identity: ~automanage_client.models.AccountIdentity
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
'location': {'required': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'location': {'key': 'location', 'type': 'str'},
'identity': {'key': 'identity', 'type': 'AccountIdentity'},
}
def __init__(
self,
**kwargs
):
super(Account, self).__init__(**kwargs)
self.identity = kwargs.get('identity', None)
class AccountIdentity(msrest.serialization.Model):
"""Identity for the Automanage account.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar principal_id: The principal id of Automanage account identity.
:vartype principal_id: str
:ivar tenant_id: The tenant id associated with the Automanage account.
:vartype tenant_id: str
:param type: The type of identity used for the Automanage account. Currently, the only
supported type is 'SystemAssigned', which implicitly creates an identity. Possible values
include: "SystemAssigned", "None".
:type type: str or ~automanage_client.models.ResourceIdentityType
"""
_validation = {
'principal_id': {'readonly': True},
'tenant_id': {'readonly': True},
}
_attribute_map = {
'principal_id': {'key': 'principalId', 'type': 'str'},
'tenant_id': {'key': 'tenantId', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AccountIdentity, self).__init__(**kwargs)
self.principal_id = None
self.tenant_id = None
self.type = kwargs.get('type', None)
class AccountList(msrest.serialization.Model):
"""The response of the list Account operation.
:param value: Result of the list Account operation.
:type value: list[~automanage_client.models.Account]
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[Account]'},
}
def __init__(
self,
**kwargs
):
super(AccountList, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
class UpdateResource(msrest.serialization.Model):
"""Represents an update resource.
:param tags: A set of tags. The tags of the resource.
:type tags: dict[str, str]
"""
_attribute_map = {
'tags': {'key': 'tags', 'type': '{str}'},
}
def __init__(
self,
**kwargs
):
super(UpdateResource, self).__init__(**kwargs)
self.tags = kwargs.get('tags', None)
class AccountUpdate(UpdateResource):
"""Definition of the Automanage account.
:param tags: A set of tags. The tags of the resource.
:type tags: dict[str, str]
:param identity: The identity of the Automanage account.
:type identity: ~automanage_client.models.AccountIdentity
"""
_attribute_map = {
'tags': {'key': 'tags', 'type': '{str}'},
'identity': {'key': 'identity', 'type': 'AccountIdentity'},
}
def __init__(
self,
**kwargs
):
super(AccountUpdate, self).__init__(**kwargs)
self.identity = kwargs.get('identity', None)
class ConfigurationProfileAssignment(Resource):
"""Configuration profile assignment is an association between a VM and automanage profile configuration.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Fully qualified resource Id for the resource. Ex -
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.
:vartype id: str
:ivar name: The name of the resource.
:vartype name: str
:ivar type: The type of the resource. Ex- Microsoft.Compute/virtualMachines or
Microsoft.Storage/storageAccounts.
:vartype type: str
:param properties: Properties of the configuration profile assignment.
:type properties: ~automanage_client.models.ConfigurationProfileAssignmentProperties
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'properties': {'key': 'properties', 'type': 'ConfigurationProfileAssignmentProperties'},
}
def __init__(
self,
**kwargs
):
super(ConfigurationProfileAssignment, self).__init__(**kwargs)
self.properties = kwargs.get('properties', None)
class ConfigurationProfileAssignmentCompliance(msrest.serialization.Model):
"""The compliance status for the configuration profile assignment.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar update_status: The state of compliance, which only appears in the response. Possible
values include: "Succeeded", "Failed", "Created".
:vartype update_status: str or ~automanage_client.models.UpdateStatus
"""
_validation = {
'update_status': {'readonly': True},
}
_attribute_map = {
'update_status': {'key': 'updateStatus', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ConfigurationProfileAssignmentCompliance, self).__init__(**kwargs)
self.update_status = None
class ConfigurationProfileAssignmentList(msrest.serialization.Model):
"""The response of the list configuration profile assignment operation.
:param value: Result of the list configuration profile assignment operation.
:type value: list[~automanage_client.models.ConfigurationProfileAssignment]
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ConfigurationProfileAssignment]'},
}
def __init__(
self,
**kwargs
):
super(ConfigurationProfileAssignmentList, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
class ConfigurationProfileAssignmentProperties(msrest.serialization.Model):
"""Automanage configuration profile assignment properties.
Variables are only populated by the server, and will be ignored when sending a request.
:param configuration_profile: A value indicating configuration profile. Possible values
include: "Azure virtual machine best practices – Dev/Test", "Azure virtual machine best
practices – Production".
:type configuration_profile: str or ~automanage_client.models.ConfigurationProfile
:param target_id: The target VM resource URI.
:type target_id: str
:param account_id: The Automanage account ARM Resource URI.
:type account_id: str
:param configuration_profile_preference_id: The configuration profile custom preferences ARM
resource URI.
:type configuration_profile_preference_id: str
:ivar provisioning_status: The state of onboarding, which only appears in the response.
Possible values include: "Succeeded", "Failed", "Created".
:vartype provisioning_status: str or ~automanage_client.models.ProvisioningStatus
:param compliance: The configuration setting for the configuration profile.
:type compliance: ~automanage_client.models.ConfigurationProfileAssignmentCompliance
"""
_validation = {
'provisioning_status': {'readonly': True},
}
_attribute_map = {
'configuration_profile': {'key': 'configurationProfile', 'type': 'str'},
'target_id': {'key': 'targetId', 'type': 'str'},
'account_id': {'key': 'accountId', 'type': 'str'},
'configuration_profile_preference_id': {'key': 'configurationProfilePreferenceId', 'type': 'str'},
'provisioning_status': {'key': 'provisioningStatus', 'type': 'str'},
'compliance': {'key': 'compliance', 'type': 'ConfigurationProfileAssignmentCompliance'},
}
def __init__(
self,
**kwargs
):
super(ConfigurationProfileAssignmentProperties, self).__init__(**kwargs)
self.configuration_profile = kwargs.get('configuration_profile', None)
self.target_id = kwargs.get('target_id', None)
self.account_id = kwargs.get('account_id', None)
self.configuration_profile_preference_id = kwargs.get('configuration_profile_preference_id', None)
self.provisioning_status = None
self.compliance = kwargs.get('compliance', None)
class ConfigurationProfilePreference(TrackedResource):
"""Definition of the configuration profile preference.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar id: Fully qualified resource Id for the resource. Ex -
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.
:vartype id: str
:ivar name: The name of the resource.
:vartype name: str
:ivar type: The type of the resource. Ex- Microsoft.Compute/virtualMachines or
Microsoft.Storage/storageAccounts.
:vartype type: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param location: Required. The geo-location where the resource lives.
:type location: str
:param properties: Properties of the configuration profile preference.
:type properties: ~automanage_client.models.ConfigurationProfilePreferenceProperties
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
'location': {'required': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'location': {'key': 'location', 'type': 'str'},
'properties': {'key': 'properties', 'type': 'ConfigurationProfilePreferenceProperties'},
}
def __init__(
self,
**kwargs
):
super(ConfigurationProfilePreference, self).__init__(**kwargs)
self.properties = kwargs.get('properties', None)
class ConfigurationProfilePreferenceAntiMalware(msrest.serialization.Model):
"""Automanage configuration profile Antimalware preferences.
:param enable_real_time_protection: Enables or disables Real Time Protection. Possible values
include: "True", "False".
:type enable_real_time_protection: str or ~automanage_client.models.EnableRealTimeProtection
:param exclusions: Extensions, Paths and Processes that must be excluded from scan.
:type exclusions: object
:param run_scheduled_scan: Enables or disables a periodic scan for antimalware. Possible values
include: "True", "False".
:type run_scheduled_scan: str or ~automanage_client.models.RunScheduledScan
:param scan_type: Type of scheduled scan. Possible values include: "Quick", "Full".
:type scan_type: str or ~automanage_client.models.ScanType
:param scan_day: Schedule scan settings day.
:type scan_day: str
:param scan_time_in_minutes: Schedule scan settings time.
:type scan_time_in_minutes: str
"""
_attribute_map = {
'enable_real_time_protection': {'key': 'enableRealTimeProtection', 'type': 'str'},
'exclusions': {'key': 'exclusions', 'type': 'object'},
'run_scheduled_scan': {'key': 'runScheduledScan', 'type': 'str'},
'scan_type': {'key': 'scanType', 'type': 'str'},
'scan_day': {'key': 'scanDay', 'type': 'str'},
'scan_time_in_minutes': {'key': 'scanTimeInMinutes', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ConfigurationProfilePreferenceAntiMalware, self).__init__(**kwargs)
self.enable_real_time_protection = kwargs.get('enable_real_time_protection', None)
self.exclusions = kwargs.get('exclusions', None)
self.run_scheduled_scan = kwargs.get('run_scheduled_scan', None)
self.scan_type = kwargs.get('scan_type', None)
self.scan_day = kwargs.get('scan_day', None)
self.scan_time_in_minutes = kwargs.get('scan_time_in_minutes', None)
class ConfigurationProfilePreferenceList(msrest.serialization.Model):
"""The response of the list ConfigurationProfilePreference operation.
:param value: Result of the list ConfigurationProfilePreference operation.
:type value: list[~automanage_client.models.ConfigurationProfilePreference]
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ConfigurationProfilePreference]'},
}
def __init__(
self,
**kwargs
):
super(ConfigurationProfilePreferenceList, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
class ConfigurationProfilePreferenceProperties(msrest.serialization.Model):
"""Automanage configuration profile preference properties.
:param vm_backup: The custom preferences for Azure VM Backup.
:type vm_backup: ~automanage_client.models.ConfigurationProfilePreferenceVmBackup
:param anti_malware: The custom preferences for Azure Antimalware.
:type anti_malware: ~automanage_client.models.ConfigurationProfilePreferenceAntiMalware
"""
_attribute_map = {
'vm_backup': {'key': 'vmBackup', 'type': 'ConfigurationProfilePreferenceVmBackup'},
'anti_malware': {'key': 'antiMalware', 'type': 'ConfigurationProfilePreferenceAntiMalware'},
}
def __init__(
self,
**kwargs
):
super(ConfigurationProfilePreferenceProperties, self).__init__(**kwargs)
self.vm_backup = kwargs.get('vm_backup', None)
self.anti_malware = kwargs.get('anti_malware', None)
class ConfigurationProfilePreferenceUpdate(UpdateResource):
"""Definition of the configuration profile preference.
:param tags: A set of tags. The tags of the resource.
:type tags: dict[str, str]
:param properties: Properties of the configuration profile preference.
:type properties: ~automanage_client.models.ConfigurationProfilePreferenceProperties
"""
_attribute_map = {
'tags': {'key': 'tags', 'type': '{str}'},
'properties': {'key': 'properties', 'type': 'ConfigurationProfilePreferenceProperties'},
}
def __init__(
self,
**kwargs
):
super(ConfigurationProfilePreferenceUpdate, self).__init__(**kwargs)
self.properties = kwargs.get('properties', None)
class ConfigurationProfilePreferenceVmBackup(msrest.serialization.Model):
"""Automanage configuration profile VM Backup preferences.
:param time_zone: TimeZone optional input as string. For example: Pacific Standard Time.
:type time_zone: str
:param instant_rp_retention_range_in_days: Instant RP retention policy range in days.
:type instant_rp_retention_range_in_days: int
:param retention_policy: Retention policy with the details on backup copy retention ranges.
:type retention_policy: str
:param schedule_policy: Backup schedule specified as part of backup policy.
:type schedule_policy: str
"""
_attribute_map = {
'time_zone': {'key': 'timeZone', 'type': 'str'},
'instant_rp_retention_range_in_days': {'key': 'instantRpRetentionRangeInDays', 'type': 'int'},
'retention_policy': {'key': 'retentionPolicy', 'type': 'str'},
'schedule_policy': {'key': 'schedulePolicy', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ConfigurationProfilePreferenceVmBackup, self).__init__(**kwargs)
self.time_zone = kwargs.get('time_zone', None)
self.instant_rp_retention_range_in_days = kwargs.get('instant_rp_retention_range_in_days', None)
self.retention_policy = kwargs.get('retention_policy', None)
self.schedule_policy = kwargs.get('schedule_policy', None)
class ErrorAdditionalInfo(msrest.serialization.Model):
"""The resource management error additional info.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar type: The additional info type.
:vartype type: str
:ivar info: The additional info.
:vartype info: object
"""
_validation = {
'type': {'readonly': True},
'info': {'readonly': True},
}
_attribute_map = {
'type': {'key': 'type', 'type': 'str'},
'info': {'key': 'info', 'type': 'object'},
}
def __init__(
self,
**kwargs
):
super(ErrorAdditionalInfo, self).__init__(**kwargs)
self.type = None
self.info = None
class ErrorResponse(msrest.serialization.Model):
"""The resource management error response.
:param error: The error object.
:type error: ~automanage_client.models.ErrorResponseError
"""
_attribute_map = {
'error': {'key': 'error', 'type': 'ErrorResponseError'},
}
def __init__(
self,
**kwargs
):
super(ErrorResponse, self).__init__(**kwargs)
self.error = kwargs.get('error', None)
class ErrorResponseError(msrest.serialization.Model):
"""The error object.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar code: The error code.
:vartype code: str
:ivar message: The error message.
:vartype message: str
:ivar target: The error target.
:vartype target: str
:ivar details: The error details.
:vartype details: list[~automanage_client.models.ErrorResponse]
:ivar additional_info: The error additional info.
:vartype additional_info: list[~automanage_client.models.ErrorAdditionalInfo]
"""
_validation = {
'code': {'readonly': True},
'message': {'readonly': True},
'target': {'readonly': True},
'details': {'readonly': True},
'additional_info': {'readonly': True},
}
_attribute_map = {
'code': {'key': 'code', 'type': 'str'},
'message': {'key': 'message', 'type': 'str'},
'target': {'key': 'target', 'type': 'str'},
'details': {'key': 'details', 'type': '[ErrorResponse]'},
'additional_info': {'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'},
}
def __init__(
self,
**kwargs
):
super(ErrorResponseError, self).__init__(**kwargs)
self.code = None
self.message = None
self.target = None
self.details = None
self.additional_info = None
class Operation(msrest.serialization.Model):
"""Automanage REST API operation.
:param name: Operation name: For ex.
providers/Microsoft.Automanage/configurationProfileAssignments/write or read.
:type name: str
:param is_data_action: Indicates whether the operation is a data action.
:type is_data_action: str
:param display: Provider, Resource, Operation and description values.
:type display: ~automanage_client.models.OperationDisplay
:param status_code: Service provider: Microsoft.Automanage.
:type status_code: str
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'is_data_action': {'key': 'isDataAction', 'type': 'str'},
'display': {'key': 'display', 'type': 'OperationDisplay'},
'status_code': {'key': 'properties.statusCode', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(Operation, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.is_data_action = kwargs.get('is_data_action', None)
self.display = kwargs.get('display', None)
self.status_code = kwargs.get('status_code', None)
class OperationDisplay(msrest.serialization.Model):
"""Provider, Resource, Operation and description values.
:param provider: Service provider: Microsoft.Automanage.
:type provider: str
:param resource: Resource on which the operation is performed: For ex.
:type resource: str
:param operation: Operation type: Read, write, delete, etc.
:type operation: str
:param description: Description about operation.
:type description: str
"""
_attribute_map = {
'provider': {'key': 'provider', 'type': 'str'},
'resource': {'key': 'resource', 'type': 'str'},
'operation': {'key': 'operation', 'type': 'str'},
'description': {'key': 'description', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(OperationDisplay, self).__init__(**kwargs)
self.provider = kwargs.get('provider', None)
self.resource = kwargs.get('resource', None)
self.operation = kwargs.get('operation', None)
self.description = kwargs.get('description', None)
class OperationList(msrest.serialization.Model):
"""The response model for the list of Automanage operations.
:param value: List of Automanage operations supported by the Automanage resource provider.
:type value: list[~automanage_client.models.Operation]
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[Operation]'},
}
def __init__(
self,
**kwargs
):
super(OperationList, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
class ProxyResource(Resource):
"""The resource model definition for a ARM proxy resource. It will have everything other than required location and tags.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Fully qualified resource Id for the resource. Ex -
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.
:vartype id: str
:ivar name: The name of the resource.
:vartype name: str
:ivar type: The type of the resource. Ex- Microsoft.Compute/virtualMachines or
Microsoft.Storage/storageAccounts.
:vartype type: str
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ProxyResource, self).__init__(**kwargs)
| [
"noreply@github.com"
] | scbedd.noreply@github.com |
3db28ba37177dbee4bae562371122d8bb4f73e72 | 7027a90b73d774394c309fd7518599dc9364bb10 | /test/functional/proxy_test.py | 6410a5b80b20c525a8d2811a6455a7fd5d615e60 | [
"MIT"
] | permissive | IDC-Group/VHKD | a5a5b1b9b275a9fadbf8b9c714c8358ee8f7c46a | 0256ddf1477439ebc84e97132d3673aa61c39b73 | refs/heads/master | 2020-03-21T09:12:22.738342 | 2018-06-23T09:46:17 | 2018-06-23T09:46:17 | 138,387,759 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,316 | py | #!/usr/bin/env python3
# Copyright (c) 2015-2016 The vhkdCoin Core vhkd
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test vhkdd with different proxy configuration.
Test plan:
- Start vhkdd's with different proxy configurations
- Use addnode to initiate connections
- Verify that proxies are connected to, and the right connection command is given
- Proxy configurations to test on vhkdd side:
- `-proxy` (proxy everything)
- `-onion` (proxy just onions)
- `-proxyrandomize` Circuit randomization
- Proxy configurations to test on proxy side,
- support no authentication (other proxy)
- support no authentication + user/pass authentication (Tor)
- proxy on IPv6
- Create various proxies (as threads)
- Create vhkdds that connect to them
- Manipulate the vhkdds using addnode (onetry) an observe effects
addnode connect to IPv4
addnode connect to IPv6
addnode connect to onion
addnode connect to generic DNS name
"""
import socket
import os
from test_framework.socks5 import Socks5Configuration, Socks5Command, Socks5Server, AddressType
from test_framework.test_framework import vhkdCoinTestFramework
from test_framework.util import (
PORT_MIN,
PORT_RANGE,
assert_equal,
)
from test_framework.netutil import test_ipv6_local
RANGE_BEGIN = PORT_MIN + 2 * PORT_RANGE # Start after p2p and rpc ports
class ProxyTest(vhkdCoinTestFramework):
def set_test_params(self):
self.num_nodes = 4
def setup_nodes(self):
self.have_ipv6 = test_ipv6_local()
# Create two proxies on different ports
# ... one unauthenticated
self.conf1 = Socks5Configuration()
self.conf1.addr = ('127.0.0.1', RANGE_BEGIN + (os.getpid() % 1000))
self.conf1.unauth = True
self.conf1.auth = False
# ... one supporting authenticated and unauthenticated (Tor)
self.conf2 = Socks5Configuration()
self.conf2.addr = ('127.0.0.1', RANGE_BEGIN + 1000 + (os.getpid() % 1000))
self.conf2.unauth = True
self.conf2.auth = True
if self.have_ipv6:
# ... one on IPv6 with similar configuration
self.conf3 = Socks5Configuration()
self.conf3.af = socket.AF_INET6
self.conf3.addr = ('::1', RANGE_BEGIN + 2000 + (os.getpid() % 1000))
self.conf3.unauth = True
self.conf3.auth = True
else:
self.log.warning("Testing without local IPv6 support")
self.serv1 = Socks5Server(self.conf1)
self.serv1.start()
self.serv2 = Socks5Server(self.conf2)
self.serv2.start()
if self.have_ipv6:
self.serv3 = Socks5Server(self.conf3)
self.serv3.start()
# Note: proxies are not used to connect to local nodes
# this is because the proxy to use is based on CService.GetNetwork(), which return NET_UNROUTABLE for localhost
args = [
['-listen', '-proxy=%s:%i' % (self.conf1.addr),'-proxyrandomize=1'],
['-listen', '-proxy=%s:%i' % (self.conf1.addr),'-onion=%s:%i' % (self.conf2.addr),'-proxyrandomize=0'],
['-listen', '-proxy=%s:%i' % (self.conf2.addr),'-proxyrandomize=1'],
[]
]
if self.have_ipv6:
args[3] = ['-listen', '-proxy=[%s]:%i' % (self.conf3.addr),'-proxyrandomize=0', '-noonion']
self.add_nodes(self.num_nodes, extra_args=args)
self.start_nodes()
def node_test(self, node, proxies, auth, test_onion=True):
rv = []
# Test: outgoing IPv4 connection through node
node.addnode("15.61.23.23:1234", "onetry")
cmd = proxies[0].queue.get()
assert(isinstance(cmd, Socks5Command))
# Note: vhkdd's SOCKS5 implementation only sends atyp DOMAINNAME, even if connecting directly to IPv4/IPv6
assert_equal(cmd.atyp, AddressType.DOMAINNAME)
assert_equal(cmd.addr, b"15.61.23.23")
assert_equal(cmd.port, 1234)
if not auth:
assert_equal(cmd.username, None)
assert_equal(cmd.password, None)
rv.append(cmd)
if self.have_ipv6:
# Test: outgoing IPv6 connection through node
node.addnode("[1233:3432:2434:2343:3234:2345:6546:4534]:5443", "onetry")
cmd = proxies[1].queue.get()
assert(isinstance(cmd, Socks5Command))
# Note: vhkdd's SOCKS5 implementation only sends atyp DOMAINNAME, even if connecting directly to IPv4/IPv6
assert_equal(cmd.atyp, AddressType.DOMAINNAME)
assert_equal(cmd.addr, b"1233:3432:2434:2343:3234:2345:6546:4534")
assert_equal(cmd.port, 5443)
if not auth:
assert_equal(cmd.username, None)
assert_equal(cmd.password, None)
rv.append(cmd)
if test_onion:
# Test: outgoing onion connection through node
node.addnode("vhkdostk4e4re.onion:8333", "onetry")
cmd = proxies[2].queue.get()
assert(isinstance(cmd, Socks5Command))
assert_equal(cmd.atyp, AddressType.DOMAINNAME)
assert_equal(cmd.addr, b"vhkdostk4e4re.onion")
assert_equal(cmd.port, 8333)
if not auth:
assert_equal(cmd.username, None)
assert_equal(cmd.password, None)
rv.append(cmd)
# Test: outgoing DNS name connection through node
node.addnode("node.noumenon:8333", "onetry")
cmd = proxies[3].queue.get()
assert(isinstance(cmd, Socks5Command))
assert_equal(cmd.atyp, AddressType.DOMAINNAME)
assert_equal(cmd.addr, b"node.noumenon")
assert_equal(cmd.port, 8333)
if not auth:
assert_equal(cmd.username, None)
assert_equal(cmd.password, None)
rv.append(cmd)
return rv
def run_test(self):
# basic -proxy
self.node_test(self.nodes[0], [self.serv1, self.serv1, self.serv1, self.serv1], False)
# -proxy plus -onion
self.node_test(self.nodes[1], [self.serv1, self.serv1, self.serv2, self.serv1], False)
# -proxy plus -onion, -proxyrandomize
rv = self.node_test(self.nodes[2], [self.serv2, self.serv2, self.serv2, self.serv2], True)
# Check that credentials as used for -proxyrandomize connections are unique
credentials = set((x.username,x.password) for x in rv)
assert_equal(len(credentials), len(rv))
if self.have_ipv6:
# proxy on IPv6 localhost
self.node_test(self.nodes[3], [self.serv3, self.serv3, self.serv3, self.serv3], False, False)
def networks_dict(d):
r = {}
for x in d['networks']:
r[x['name']] = x
return r
# test RPC getnetworkinfo
n0 = networks_dict(self.nodes[0].getnetworkinfo())
for net in ['ipv4','ipv6','onion']:
assert_equal(n0[net]['proxy'], '%s:%i' % (self.conf1.addr))
assert_equal(n0[net]['proxy_randomize_credentials'], True)
assert_equal(n0['onion']['reachable'], True)
n1 = networks_dict(self.nodes[1].getnetworkinfo())
for net in ['ipv4','ipv6']:
assert_equal(n1[net]['proxy'], '%s:%i' % (self.conf1.addr))
assert_equal(n1[net]['proxy_randomize_credentials'], False)
assert_equal(n1['onion']['proxy'], '%s:%i' % (self.conf2.addr))
assert_equal(n1['onion']['proxy_randomize_credentials'], False)
assert_equal(n1['onion']['reachable'], True)
n2 = networks_dict(self.nodes[2].getnetworkinfo())
for net in ['ipv4','ipv6','onion']:
assert_equal(n2[net]['proxy'], '%s:%i' % (self.conf2.addr))
assert_equal(n2[net]['proxy_randomize_credentials'], True)
assert_equal(n2['onion']['reachable'], True)
if self.have_ipv6:
n3 = networks_dict(self.nodes[3].getnetworkinfo())
for net in ['ipv4','ipv6']:
assert_equal(n3[net]['proxy'], '[%s]:%i' % (self.conf3.addr))
assert_equal(n3[net]['proxy_randomize_credentials'], False)
assert_equal(n3['onion']['reachable'], False)
if __name__ == '__main__':
ProxyTest().main()
| [
"support@idcm.io"
] | support@idcm.io |
57cd23f4c8d93d7d59dec9d1b011cedeae27892e | 6989d1f413cab583279f61f6799f2c05dab21840 | /DR/dr/tests.py | 7e9b8e195bbb6cd688ec2abdff49a7abb0844610 | [] | no_license | Qiamxing/gitprogram | f797a67059d5a188bb81576e72de8e5f34239a0d | 03f26f0dd5b72187d78f4283e07742aeacd326da | refs/heads/master | 2020-04-12T14:11:10.854943 | 2019-01-20T13:54:52 | 2019-01-20T13:54:52 | 162,545,094 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,574 | py | import random
import json
from django.test import TestCase
import os
import dr.models
def a():
with open('static/json/goodlist.json','r') as f :
jsondict = json.load(f)
for i in jsondict :
for j in i :
goods = dr.models.Goodslist()
goods.name = j['title']
goods.price = j['price']
goods.price1 = int(j['price1'])
goods.price2 = int(j['price2'])
goods.material2 = j['material2']
goods.com = int(j['com'])
goods.src = j['src']
goods.index = j['index']
goods.discript = j['discript']
goods.material1 = j['material1']
goods.sale = int(j['sale'])
goods.save()
if j.get('img') :
for k in j['img']:
img = dr.models.Goodsimg()
img.src = k['src']
img.goods = goods
img.save()
"""
{'material2': '白18K金',
'img': [{'src': 'images/2016060812454522d7889f26.jpg'},
{'src': 'images/201509301425347b86245a0e.jpg'},
{'src': 'images/201603301519256b9cccee8f.jpg'},
{'src': 'images/20160620101350d2f9fcb5a8.jpg'}],
'id': '1',
'price': '9999',
'com': '756',
'price2': '10008',
'src': 'images/2016060812454522d7889f26.jpg',
'price1': '9898',
'index': '1',
'discript': 'TRUE LOVE系列 典雅 40分 F色',
'title': '黑骑士',
'material1': 'PT950',
'sale': '1341'}
"""
| [
"lh936151172@163.com"
] | lh936151172@163.com |
97f3a20470ff981d68f6ff1cb4a0dca3f29ef69a | 9d106a8001141cfdc00feb0ba01b34eb0cd86726 | /django_blog/blog/migrations/0002_post_image.py | d59bee53bd3806ac240718eddaf444b7a950cff4 | [] | no_license | dingxiao88/Django_Blog | 46cc29f034a17ab5676017f8f9c5125bac6715d4 | 536a0ad282ce0d80b0f7fbbdda87a3c344daf971 | refs/heads/master | 2020-03-22T08:59:30.881495 | 2018-08-15T11:05:17 | 2018-08-15T11:05:17 | 139,806,158 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 397 | py | # Generated by Django 2.0.6 on 2018-07-06 04:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='post',
name='image',
field=models.ImageField(default='default.png', upload_to='images/'),
),
]
| [
"dingxiao88@163.com"
] | dingxiao88@163.com |
9660d16db01a5b2632d6cd135e3fd10c0413d051 | 9ce437f1d890d08949dbfe8a97fe50837664ce3b | /tests/test_doc.py | fd7cac03d4dc78de124cd107a8e93d6499ec6502 | [
"MIT"
] | permissive | MIBlue119/julius | 9f5ea27d57a735f12f0ae9f31d0d6571c0cf0d27 | 2a43ba41b1f5f2914e4dc6ba6d94da63657e701a | refs/heads/main | 2023-08-31T05:39:38.909260 | 2021-10-20T08:28:45 | 2021-10-20T08:28:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 550 | py | from doctest import testmod
import unittest
from julius import resample, fftconv, lowpass, bands, utils
class DocStringTest(unittest.TestCase):
def test_resample(self):
self.assertEqual(testmod(resample).failed, 0)
def test_fftconv(self):
self.assertEqual(testmod(fftconv).failed, 0)
def test_lowpass(self):
self.assertEqual(testmod(lowpass).failed, 0)
def test_bands(self):
self.assertEqual(testmod(bands).failed, 0)
def test_utils(self):
self.assertEqual(testmod(utils).failed, 0)
| [
"alexandre.defossez@gmail.com"
] | alexandre.defossez@gmail.com |
9dbee2fa63070dea1541e33e7b76b442a847314e | 06ad1ab54b4889736960b942bc363de3dbea9b39 | /KCRWscraper_3.py | 61195d912f36d4234ee1beb407a902ba45de0f2c | [] | no_license | authalic/podcaster | b6f6b9516f2782a6db28ce54befac4ea6cf15c50 | db17b6495e6770d83126e0f34d6c42483ae5803c | refs/heads/master | 2022-12-09T06:33:12.514487 | 2019-11-04T23:32:00 | 2019-11-04T23:32:00 | 37,360,232 | 0 | 0 | null | 2022-12-08T01:41:52 | 2015-06-13T06:08:00 | Python | UTF-8 | Python | false | false | 3,063 | py | '''
KCRW program information scraper
Author: Justin Johnson
updated: May 18, 2018
This module extracts a daily program information from KCRW.com
The main method of this module is called at the end of each day's rip.
The host name and playlist are written into the XML file for that day's podcast episode.
'''
import requests
# Extract the program info
# Tracklist API returns a JSON file with show info and track list
def getShowInfo(programName, today):
'''Returns the program summary from the KCRW playlist page'''
# extract the year, month, and day as strings
year = str(today[0])
mon = str(today[1]).zfill(2) # pad single-digit months
day = str(today[2]).zfill(2) # pad single-digit days
starttimes = {
"MBE": "09:00",
"Metropolis": "22:00",
"Rollins": "20:00"
}
# get the program info from the API
# get the complete tracklist from the specified date
# format: http://tracklist-api.kcrw.com/Simulcast/date/2019/01/11
alltracklist = requests.get("http://tracklist-api.kcrw.com/Simulcast/date/" + year + "/" + mon + "/" + day).json()
# filter out the tracks for the program, using the appropriate 'program_start' key value
tracklist = [track for track in alltracklist if track['program_start'] == starttimes[programName]]
# create a playlist containg the start time, artist, and trackname for each track
playlist = ""
for track in tracklist:
if "BREAK" in track['artist']:
playlist += track['time'] + " - BREAK -" + "\n"
elif track['label'] == "KCRW Live":
playlist += track['time'] + " " + track['artist'] + " - " + track['title'] + " [Live @ KCRW]\n"
else:
playlist += track['time'] + " " + track['artist'] + " - " + track['title'] + "\n"
# build the show info string
# example: 'Hosted by Anne Litt' + list of tracks
showText = ""
# get the name of the episode host
if tracklist[0]["host"]:
showText = "Hosted by " + tracklist[0]["host"] + "\n\n"
if playlist:
showText += playlist
# return a generic description if this operation fails to grab something off the web
if (showText == "" and programName == "MBE"):
return "Morning Becomes Eclectic on KCRW"
elif (showText == "" and programName == "Rollins"):
return "Henry Rollins Show on KCRW"
elif (showText == "" and programName == "Metropolis"):
return "Metropolis on KCRW"
# otherwise, return the full description
if showText:
return str(showText) # convert from Unicode string to String
# if you get here, no show info was obtained
return "Unable to obtain show info"
# create a function to extract comments on a track, if present
def printcomments(track):
alltracklist = requests.get(r'http://tracklist-api.kcrw.com/Simulcast/date/2019/01/10').json()
for track in alltracklist:
if track['comments']:
print(track['comments'])
if __name__ == "__main__":
# for testing functions
pass
| [
"authalic@gmail.com"
] | authalic@gmail.com |
e1019cfe92520808aa41d1a7f42aef3ba26f34c1 | 320b7d4199c602800e3faaf747f148b1477bf49c | /Tkinter GUI Program/Label_frame.py | d091573a555cf50405a38ce4d34780983825a571 | [] | no_license | hashmand/Python_Programs | 208fb73d415532eb15f05e89dd5871ea3480fdb3 | b80c5bac6ab29b20982e5371e729c3eeb389f9de | refs/heads/main | 2023-08-28T14:00:44.483931 | 2021-10-20T17:48:48 | 2021-10-20T17:48:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 561 | py | import tkinter as tk
win = tk.Tk()
win.geometry("500x300")
labelframe1 = tk.LabelFrame(win, text="Frame 1")
labelframe1.pack() #fill="both", expand="yes" this is the properties of pack
toplabel = tk.Label(labelframe1, text="First frame")
toplabel.pack()
b1 = tk.Button(labelframe1,text="Click me")
b1.pack()
labelframe2 = tk.LabelFrame(win, text = "Frame 2")
labelframe2.pack()
bottomlabel = tk.Label(labelframe2,text = "Second frame")
bottomlabel.pack()
b2 = tk.Button(labelframe2,text="click me")
b2.pack()
win.mainloop() | [
"ramghumaliya10@gmail.com"
] | ramghumaliya10@gmail.com |
a3a1e64f5807e16bd4520e2cc4130a665ca2d582 | 9c991307e29bdbd573c9d98ecd5c89e2ccaac414 | /bin/vhost_gen.py | ceee30e8546da44219849c8cbb2ea3085806c48c | [
"MIT"
] | permissive | murzindima/vhost-gen | b675e06b31909ca1e2cdbe0a16af33f83d1044f6 | 1835496d0e8694a0eceb1ef0f09d69e264e295f3 | refs/heads/master | 2022-08-28T10:24:47.849638 | 2018-08-04T23:47:24 | 2018-08-04T23:47:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 30,756 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# The MIT License (MIT)
#
# Copyright (c) 2017 cytopia <cytopia@everythingcli.org>
"""
vHost creator for Apache 2.2, Apache 2.4 and Nginx.
"""
############################################################
# Imports
############################################################
from __future__ import print_function
import os
import sys
import time
import re
import getopt
import itertools
import yaml
############################################################
# Globals
############################################################
# Default paths
CONFIG_PATH = '/etc/vhost-gen/conf.yml'
TEMPLATE_DIR = '/etc/vhost-gen/templates'
# stdout/stderr log paths
STDOUT_ACCESS = '/tmp/www-access.log'
STDERR_ERROR = '/tmp/www-error.log'
# Default configuration
DEFAULT_CONFIG = {
'server': 'nginx',
'conf_dir': '/etc/nginx/conf.d',
'custom': '',
'vhost': {
'port': '80',
'ssl_port': '443',
'name': {
'prefix': '',
'suffix': ''
},
'docroot': {
'suffix': ''
},
'index': [
'index.php',
'index.html',
'index.htm'
],
'ssl': {
'path_crt': '',
'path_key': '',
'honor_cipher_order': 'on',
'ciphers': 'HIGH:!aNULL:!MD5',
'protocols': 'TLSv1 TLSv1.1 TLSv1.2'
},
'log': {
'access': {
'prefix': '',
'stdout': False
},
'error': {
'prefix': '',
'stderr': False
},
'dir': {
'create': False,
'path': '/var/log/nginx'
}
},
'php_fpm': {
'enable': False,
'address': '',
'port': 9000,
'timeout': 180
},
'alias': [],
'deny': [],
'server_status': {
'enable': False,
'alias': '/server-status'
}
}
}
# Available templates
TEMPLATES = {
'apache22': 'apache22.yml',
'apache24': 'apache24.yml',
'nginx': 'nginx.yml'
}
############################################################
# System Functions
############################################################
def print_help():
"""Show program help."""
print("""
Usage: vhost_gen.py -p|r <str> -n <str> [-l <str> -c <str> -t <str> -o <str> -d -s -v]
vhost_gen.py --help
vhost_gen.py --version
vhost_gen.py will dynamically generate vhost configuration files
for Nginx, Apache 2.2 or Apache 2.4 depending on what you have set
in /etc/vhot-gen/conf.yml
Required arguments:
-p|r <str> You need to choose one of the mutually exclusive arguments.
-p: Path to document root/
-r: http(s)://Host:Port for reverse proxy.
Depening on the choice, it will either generate a document serving
vhost or a reverse proxy vhost.
Note, when using -p, this can also have a suffix directory to be set
in conf.yml
-l <str> Location path when using reverse proxy.
Note, this is not required for normal document root server (-p)
-n <str> Name of vhost
Note, this can also have a prefix and/or suffix to be set in conf.yml
Optional arguments:
-m <str> Vhost generation mode. Possible values are:
-m plain: Only generate http version (default)
-m ssl: Only generate https version
-m both: Generate http and https version
-m redir: Generate https version and make http redirect to https
-c <str> Path to global configuration file.
If not set, the default location is /etc/vhost-gen/conf.yml
If no config is found, a default is used with all features turned off.
-t <str> Path to global vhost template directory.
If not set, the default location is /etc/vhost-gen/templates/
If vhost template files are not found in this directory, the program will
abort.
-o <str> Path to local vhost template directory.
This is used as a secondary template directory and definitions found here
will be merged with the ones found in the global template directory.
Note, definitions in local vhost teplate directory take precedence over
the ones found in the global template directory.
-d Make this vhost the default virtual host.
Note, this will also change the server_name directive of nginx to '_'
as well as discarding any prefix or suffix specified for the name.
Apache does not have any specialities, the first vhost takes precedence.
-s If specified, the generated vhost will be saved in the location found in
conf.yml. If not specified, vhost will be printed to stdout.
-v Be verbose.
Misc arguments:
--help Show this help.
--version Show version.
""")
def print_version():
"""Show program version."""
print('vhost_gen v0.5 (2018-05-02)')
print('cytopia <cytopia@everythingcli.org>')
print('https://github.com/devilbox/vhost-gen')
print('The MIT License (MIT)')
############################################################
# Wrapper Functions
############################################################
def str_replace(string, replacer):
"""Generic string replace."""
# Replace all 'keys' with 'values'
for key, val in replacer.items():
string = string.replace(key, val)
return string
def str_indent(text, amount, char=' '):
"""Indent every newline inside str by specified value."""
padding = amount * char
return ''.join(padding+line for line in text.splitlines(True))
def to_str(string):
"""Dummy string retriever."""
if string is None:
return ''
return str(string)
def load_yaml(path):
"""Wrapper to load yaml file safely."""
try:
with open(path, 'r') as stream:
try:
data = yaml.safe_load(stream)
if data is None:
data = dict()
return (True, data, '')
except yaml.YAMLError as err:
return (False, dict(), str(err))
except IOError:
return (False, dict(), 'File does not exist: '+path)
def merge_yaml(yaml1, yaml2):
"""Merge two yaml strings. The secondary takes precedence."""
return dict(itertools.chain(yaml1.items(), yaml2.items()))
def symlink(src, dst, force=False):
"""
Wrapper function to create a symlink with the addition of
being able to overwrite an already existing file.
"""
if os.path.isdir(dst):
return (False, '[ERR] destination is a directory: '+dst)
if force and os.path.exists(dst):
try:
os.remove(dst)
except OSError as err:
return (False, '[ERR] Cannot delete: '+dst+': '+str(err))
try:
os.symlink(src, dst)
except OSError as err:
return (False, '[ERR] Cannot create link: '+str(err))
return (True, None)
############################################################
# Argument Functions
############################################################
def parse_args(argv):
"""Parse command line arguments."""
# Config location, can be overwritten with -c
l_config_path = CONFIG_PATH
l_template_dir = TEMPLATE_DIR
o_template_dir = None
save = None
path = None
name = None
proxy = None
mode = None
location = None
default = False
verbose = False
# Define command line options
try:
opts, argv = getopt.getopt(argv, 'vm:c:p:r:l:n:t:o:ds', ['version', 'help'])
except getopt.GetoptError as err:
print('[ERR]', str(err), file=sys.stderr)
print('Type --help for help', file=sys.stderr)
sys.exit(2)
# Get command line options
for opt, arg in opts:
if opt == '--version':
print_version()
sys.exit()
elif opt == '--help':
print_help()
sys.exit()
# Verbose
elif opt == '-v':
verbose = True
# Config file overwrite
elif opt == '-c':
l_config_path = arg
# Vhost document root path
elif opt == '-p':
path = arg
# Vhost reverse proxy (ADDR:PORT)
elif opt == '-r':
proxy = arg
# Mode overwrite
elif opt == '-m':
mode = arg
# Location for reverse proxy
elif opt == '-l':
location = arg
# Vhost name
elif opt == '-n':
name = arg
# Global template dir
elif opt == '-t':
l_template_dir = arg
# Local template dir
elif opt == '-o':
o_template_dir = arg
# Save?
elif opt == '-d':
default = True
elif opt == '-s':
save = True
return (
l_config_path, l_template_dir, o_template_dir, path, proxy, mode,
location, name, default, save, verbose
)
def validate_args_req(name, docroot, proxy, mode, location):
"""Validate required arguments."""
# Validate required command line options are set
if docroot is None and proxy is None:
print('[ERR] -p or -r is required', file=sys.stderr)
print('Type --help for help', file=sys.stderr)
sys.exit(1)
if docroot is not None and proxy is not None:
print('[ERR] -p and -r are mutually exclusive', file=sys.stderr)
print('Type --help for help', file=sys.stderr)
sys.exit(1)
# Check proxy string
if proxy is not None:
if location is None:
print('[ERR] When specifying -r, -l is also required.', file=sys.stderr)
sys.exit(1)
# Regex: HOSTNAME/IP:PORT
regex = re.compile('(^http(s)?://[-_.a-zA-Z0-9]+:[0-9]+$)', re.IGNORECASE)
if not regex.match(proxy):
print('[ERR] Invalid proxy argument string: \'%s\', should be: %s or %s.'
% (proxy, 'http(s)://HOST:PORT', 'http(s)://IP:PORT'), file=sys.stderr)
sys.exit(1)
port = int(re.sub('^.*:', '', proxy))
if port < 1 or port > 65535:
print('[ERR] Invalid reverse proxy port range: \'%d\', should between 1 and 65535'
% (port), file=sys.stderr)
sys.exit(1)
# Check mode string
if mode is not None:
if mode not in ('plain', 'ssl', 'both', 'redir'):
print('[ERR] Invalid -m mode string: \'%s\', should be: %s, %s, %s or %s'
% (mode, 'plain', 'ssl', 'both', 'redir'), file=sys.stderr)
sys.exit(1)
# Check normal server settings
if docroot is not None:
if location is not None:
print('[WARN] -l is ignored when using normal vhost (-p)', file=sys.stderr)
if name is None:
print('[ERR] -n is required', file=sys.stderr)
print('Type --help for help', file=sys.stderr)
sys.exit(1)
regex = re.compile('(^[-_.a-zA-Z0-9]+$)', re.IGNORECASE)
if not regex.match(name):
print('[ERR] Invalid name:', name, file=sys.stderr)
sys.exit(1)
def validate_args_opt(config_path, tpl_dir):
"""Validate optional arguments."""
if not os.path.isfile(config_path):
print('[WARN] Config file not found:', config_path, file=sys.stderr)
if not os.path.isdir(tpl_dir):
print('[ERR] Template path does not exist:', tpl_dir, file=sys.stderr)
print('Type --help for help', file=sys.stderr)
sys.exit(1)
# Validate global templates
tpl_file = os.path.join(tpl_dir, TEMPLATES['apache22'])
if not os.path.isfile(tpl_file):
print('[ERR] Apache 2.2 template file does not exist:', tpl_file, file=sys.stderr)
print('Type --help for help', file=sys.stderr)
sys.exit(1)
tpl_file = os.path.join(tpl_dir, TEMPLATES['apache24'])
if not os.path.isfile(tpl_file):
print('[ERR] Apache 2.4 template file does not exist:', tpl_file, file=sys.stderr)
print('Type --help for help', file=sys.stderr)
sys.exit(1)
tpl_file = os.path.join(tpl_dir, TEMPLATES['nginx'])
if not os.path.isfile(tpl_file):
print('[ERR] Nginx template file does not exist:', tpl_file, file=sys.stderr)
print('Type --help for help', file=sys.stderr)
sys.exit(1)
############################################################
# Config File Functions
############################################################
def validate_config(config):
"""Validate some important keys in config dict."""
# Validate server type
valid_hosts = list(TEMPLATES.keys())
if config['server'] not in valid_hosts:
print('[ERR] httpd.server must be \'apache22\', \'apache24\' or \'nginx\'', file=sys.stderr)
print('[ERR] Your configuration is:', config['server'], file=sys.stderr)
sys.exit(1)
# # Validate if log dir can be created
# log_dir = config['vhost']['log']['dir']['path']
# if config['vhost']['log']['dir']['create']:
# if not os.path.isdir(log_dir):
# if not os.access(os.path.dirname(log_dir), os.W_OK):
# print('[ERR] log directory does not exist and cannot be created:', log_dir,
# file=sys.stderr)
# sys.exit(1)
############################################################
# Get vHost Skeleton placeholders
############################################################
def vhost_get_port(config, ssl):
"""Get listen port."""
if ssl:
if config['server'] == 'nginx':
return to_str(config['vhost']['ssl_port']) + ' ssl'
return to_str(config['vhost']['ssl_port'])
return to_str(config['vhost']['port'])
def vhost_get_default_server(config, default):
"""
Get vhost default directive which makes it the default vhost.
:param dict config: Configuration dictionary
:param bool default: Default vhost
"""
if default:
if config['server'] == 'nginx':
# The leading space is required here for the template to
# separate it from the port directive left to it.
return ' default_server'
if config['server'] in ('apache22', 'apache24'):
return '_default_'
else:
if config['server'] in ('apache22', 'apache24'):
return '*'
return ''
def vhost_get_server_name(config, server_name, default):
"""Get server name."""
# Nginx uses: "server_name _;" as the default
if default and config['server'] == 'nginx':
return '_'
# Apache does not have any specialities. The first one takes precedence.
# The name will be the same as with every other vhost.
prefix = to_str(config['vhost']['name']['prefix'])
suffix = to_str(config['vhost']['name']['suffix'])
return prefix + server_name + suffix
def vhost_get_access_log(config, server_name):
"""Get access log directive."""
if config['vhost']['log']['access']['stdout']:
return STDOUT_ACCESS
prefix = to_str(config['vhost']['log']['access']['prefix'])
name = prefix + server_name + '-access.log'
path = os.path.join(config['vhost']['log']['dir']['path'], name)
return path
def vhost_get_error_log(config, server_name):
"""Get error log directive."""
if config['vhost']['log']['error']['stderr']:
return STDERR_ERROR
prefix = to_str(config['vhost']['log']['error']['prefix'])
name = prefix + server_name + '-error.log'
path = os.path.join(config['vhost']['log']['dir']['path'], name)
return path
############################################################
# Get vHost Type (normal or reverse proxy
############################################################
def vhost_get_vhost_docroot(config, template, docroot, proxy):
"""Get document root directive."""
if proxy is not None:
return ''
return str_replace(template['vhost_type']['docroot'], {
'__DOCUMENT_ROOT__': vhost_get_docroot_path(config, docroot, proxy),
'__INDEX__': vhost_get_index(config)
})
def vhost_get_vhost_rproxy(template, proxy, location):
"""Get reverse proxy definition."""
if proxy is not None:
return str_replace(template['vhost_type']['rproxy'], {
'__LOCATION__': location,
'__PROXY_PROTO__': re.sub('://.*$', '', proxy),
'__PROXY_ADDR__': re.search('^.*://(.+):[0-9]+', proxy).group(1),
'__PROXY_PORT__': re.sub('^.*:', '', proxy)
})
return ''
############################################################
# Get vHost Features
############################################################
def vhost_get_vhost_ssl(config, template, server_name):
"""Get ssl definition."""
return str_replace(template['features']['ssl'], {
'__SSL_PATH_CRT__': to_str(vhost_get_ssl_crt_path(config, server_name)),
'__SSL_PATH_KEY__': to_str(vhost_get_ssl_key_path(config, server_name)),
'__SSL_PROTOCOLS__': to_str(config['vhost']['ssl']['protocols']),
'__SSL_HONOR_CIPHER_ORDER__': to_str(config['vhost']['ssl']['honor_cipher_order']),
'__SSL_CIPHERS__': to_str(config['vhost']['ssl']['ciphers'])
})
def vhost_get_vhost_redir(config, template, server_name):
"""Get redirect to ssl definition."""
return str_replace(template['features']['redirect'], {
'__VHOST_NAME__': server_name,
'__SSL_PORT__': to_str(config['vhost']['ssl_port'])
})
def vhost_get_ssl_crt_path(config, server_name):
"""Get ssl crt path"""
prefix = to_str(config['vhost']['name']['prefix'])
suffix = to_str(config['vhost']['name']['suffix'])
name = prefix + server_name + suffix + '.crt'
path = to_str(config['vhost']['ssl']['dir_crt'])
return os.path.join(path, name)
def vhost_get_ssl_key_path(config, server_name):
"""Get ssl key path"""
prefix = to_str(config['vhost']['name']['prefix'])
suffix = to_str(config['vhost']['name']['suffix'])
name = prefix + server_name + suffix + '.key'
path = to_str(config['vhost']['ssl']['dir_crt'])
return os.path.join(path, name)
def vhost_get_docroot_path(config, docroot, proxy):
"""Get path of document root."""
if proxy is not None:
return ''
suffix = to_str(config['vhost']['docroot']['suffix'])
path = os.path.join(docroot, suffix)
return path
def vhost_get_index(config):
"""Get index."""
if 'index' in config['vhost'] and config['vhost']['index']:
elem = config['vhost']['index']
else:
elem = DEFAULT_CONFIG['vhost']['index']
return ' '.join(elem)
def vhost_get_php_fpm(config, template, docroot, proxy):
"""Get PHP FPM directive. If using reverse proxy, PHP-FPM will be disabled."""
if proxy is not None:
return ''
# Get PHP-FPM
php_fpm = ''
if config['vhost']['php_fpm']['enable']:
php_fpm = str_replace(template['features']['php_fpm'], {
'__PHP_ADDR__': to_str(config['vhost']['php_fpm']['address']),
'__PHP_PORT__': to_str(config['vhost']['php_fpm']['port']),
'__PHP_TIMEOUT__': to_str(config['vhost']['php_fpm']['timeout']),
'__DOCUMENT_ROOT__': vhost_get_docroot_path(config, docroot, proxy)
})
return php_fpm
def vhost_get_aliases(config, template):
"""Get virtual host alias directives."""
aliases = []
for item in config['vhost']['alias']:
# Add optional xdomain request if enabled
xdomain_request = ''
if 'xdomain_request' in item:
if item['xdomain_request']['enable']:
xdomain_request = str_replace(template['features']['xdomain_request'], {
'__REGEX__': to_str(item['xdomain_request']['origin'])
})
# Replace everything
aliases.append(str_replace(template['features']['alias'], {
'__ALIAS__': to_str(item['alias']),
'__PATH__': to_str(item['path']),
'__XDOMAIN_REQ__': str_indent(xdomain_request, 4).rstrip()
}))
# Join by OS independent newlines
return os.linesep.join(aliases)
def vhost_get_denies(config, template):
"""Get virtual host deny alias directives."""
denies = []
for item in config['vhost']['deny']:
denies.append(str_replace(template['features']['deny'], {
'__REGEX__': to_str(item['alias'])
}))
# Join by OS independent newlines
return os.linesep.join(denies)
def vhost_get_server_status(config, template):
"""Get virtual host server status directivs."""
status = ''
if config['vhost']['server_status']['enable']:
status = template['features']['server_status']
return str_replace(status, {
'__REGEX__': to_str(config['vhost']['server_status']['alias'])
})
def vhost_get_custom_section(config):
"""Get virtual host custom directives."""
return to_str(config['custom'])
############################################################
# vHost create
############################################################
def get_vhost_plain(config, tpl, docroot, proxy, location, server_name, default):
"""Get plain vhost"""
return str_replace(tpl['vhost'], {
'__PORT__': vhost_get_port(config, False),
'__DEFAULT_VHOST__': vhost_get_default_server(config, default),
'__DOCUMENT_ROOT__': vhost_get_docroot_path(config, docroot, proxy),
'__VHOST_NAME__': vhost_get_server_name(config, server_name, default),
'__VHOST_DOCROOT__': str_indent(vhost_get_vhost_docroot(config, tpl, docroot, proxy), 4),
'__VHOST_RPROXY__': str_indent(vhost_get_vhost_rproxy(tpl, proxy, location), 4),
'__REDIRECT__': '',
'__SSL__': '',
'__INDEX__': vhost_get_index(config),
'__ACCESS_LOG__': vhost_get_access_log(config, server_name),
'__ERROR_LOG__': vhost_get_error_log(config, server_name),
'__PHP_FPM__': str_indent(vhost_get_php_fpm(config, tpl, docroot, proxy), 4),
'__ALIASES__': str_indent(vhost_get_aliases(config, tpl), 4),
'__DENIES__': str_indent(vhost_get_denies(config, tpl), 4),
'__SERVER_STATUS__': str_indent(vhost_get_server_status(config, tpl), 4),
'__CUSTOM__': str_indent(vhost_get_custom_section(config), 4)
})
def get_vhost_ssl(config, tpl, docroot, proxy, location, server_name, default):
"""Get ssl vhost"""
return str_replace(tpl['vhost'], {
'__PORT__': vhost_get_port(config, True),
'__DEFAULT_VHOST__': vhost_get_default_server(config, default),
'__DOCUMENT_ROOT__': vhost_get_docroot_path(config, docroot, proxy),
'__VHOST_NAME__': vhost_get_server_name(config, server_name, default),
'__VHOST_DOCROOT__': str_indent(vhost_get_vhost_docroot(config, tpl, docroot, proxy), 4),
'__VHOST_RPROXY__': str_indent(vhost_get_vhost_rproxy(tpl, proxy, location), 4),
'__REDIRECT__': '',
'__SSL__': str_indent(vhost_get_vhost_ssl(config, tpl, server_name), 4),
'__INDEX__': vhost_get_index(config),
'__ACCESS_LOG__': vhost_get_access_log(config, server_name + '_ssl'),
'__ERROR_LOG__': vhost_get_error_log(config, server_name + '_ssl'),
'__PHP_FPM__': str_indent(vhost_get_php_fpm(config, tpl, docroot, proxy), 4),
'__ALIASES__': str_indent(vhost_get_aliases(config, tpl), 4),
'__DENIES__': str_indent(vhost_get_denies(config, tpl), 4),
'__SERVER_STATUS__': str_indent(vhost_get_server_status(config, tpl), 4),
'__CUSTOM__': str_indent(vhost_get_custom_section(config), 4)
})
def get_vhost_redir(config, tpl, docroot, proxy, server_name, default):
"""Get redirect to ssl vhost"""
return str_replace(tpl['vhost'], {
'__PORT__': vhost_get_port(config, False),
'__DEFAULT_VHOST__': vhost_get_default_server(config, default),
'__DOCUMENT_ROOT__': vhost_get_docroot_path(config, docroot, proxy),
'__VHOST_NAME__': vhost_get_server_name(config, server_name, default),
'__VHOST_DOCROOT__': '',
'__VHOST_RPROXY__': '',
'__REDIRECT__': str_indent(vhost_get_vhost_redir(config, tpl, server_name), 4),
'__SSL__': '',
'__INDEX__': '',
'__ACCESS_LOG__': vhost_get_access_log(config, server_name),
'__ERROR_LOG__': vhost_get_error_log(config, server_name),
'__PHP_FPM__': '',
'__ALIASES__': '',
'__DENIES__': '',
'__SERVER_STATUS__': '',
'__CUSTOM__': ''
})
def get_vhost(config, tpl, docroot, proxy, mode, location, server_name, default):
"""Create the vhost."""
if mode == 'ssl':
return get_vhost_ssl(config, tpl, docroot, proxy, location,
server_name, default)
if mode == 'both':
return (
get_vhost_ssl(config, tpl, docroot, proxy, location,
server_name, default) +
get_vhost_plain(config, tpl, docroot, proxy, location,
server_name, default)
)
if mode == 'redir':
return (
get_vhost_ssl(config, tpl, docroot, proxy, location,
server_name, default) +
get_vhost_redir(config, tpl, docroot, proxy, server_name, default)
)
return get_vhost_plain(config, tpl, docroot, proxy, location,
server_name, default)
############################################################
# Load configs and templates
############################################################
def load_config(config_path):
"""Load config and merge with defaults in case not found or something is missing."""
# Load configuration file
if os.path.isfile(config_path):
succ, config, err = load_yaml(config_path)
if not succ:
return (False, dict(), err)
else:
print('[WARN] config file not found', config_path, file=sys.stderr)
config = dict()
# Merge config settings with program defaults (config takes precedence over defaults)
config = merge_yaml(DEFAULT_CONFIG, config)
return (True, config, '')
def load_template(template_dir, o_template_dir, server):
"""Load global and optional template file and merge them."""
# Load global template file
succ, template, err = load_yaml(os.path.join(template_dir, TEMPLATES[server]))
if not succ:
return (False, dict(), '[ERR] Error loading template' + err)
# Load optional template file (if specified file and merge it)
if o_template_dir is not None:
succ, template2, err = load_yaml(os.path.join(o_template_dir, TEMPLATES[server]))
template = merge_yaml(template, template2)
return (True, template, '')
############################################################
# Post actions
############################################################
def apply_log_settings(config):
"""
This function will apply various settings for the log defines, including
creating the directory itself as well as handling log file output (access
and error) to stderr/stdout.
"""
# Symlink stdout to access logfile
if config['vhost']['log']['access']['stdout']:
succ, err = symlink('/dev/stdout', STDOUT_ACCESS, force=True)
if not succ:
return (False, err)
# Symlink stderr to error logfile
if config['vhost']['log']['error']['stderr']:
succ, err = symlink('/dev/stderr', STDERR_ERROR, force=True)
if not succ:
return (False, err)
# Create log dir
if config['vhost']['log']['dir']['create']:
if not os.path.isdir(config['vhost']['log']['dir']['path']):
try:
os.makedirs(config['vhost']['log']['dir']['path'])
except OSError as err:
return (False, '[ERR] Cannot create directory: '+str(err))
return (True, None)
############################################################
# Main Function
############################################################
def main(argv):
"""Main entrypoint."""
# Get command line arguments
(config_path, tpl_dir, o_tpl_dir, docroot,
proxy, mode, location, name, default, save, verbose) = parse_args(argv)
# Validate command line arguments This will abort the program on error
# This will abort the program on error
validate_args_req(name, docroot, proxy, mode, location)
validate_args_opt(config_path, tpl_dir)
# Load config
succ, config, err = load_config(config_path)
if not succ:
print('[ERR] Error loading config', err, file=sys.stderr)
sys.exit(1)
# Load template
succ, template, err = load_template(tpl_dir, o_tpl_dir, config['server'])
if not succ:
print('[ERR] Error loading template', err, file=sys.stderr)
sys.exit(1)
# Validate configuration file
# This will abort the program on error
validate_config(config)
# Retrieve fully build vhost
vhost = get_vhost(config, template, docroot, proxy, mode, location, name, default)
if verbose:
print('vhostgen: [%s] Adding: %s' %
(time.strftime("%Y-%m-%d %H:%M:%S"),
to_str(config['vhost']['name']['prefix']) + name +
to_str(config['vhost']['name']['suffix'])))
if save:
if not os.path.isdir(config['conf_dir']):
print('[ERR] output conf_dir does not exist:', config['conf_dir'],
file=sys.stderr)
sys.exit(1)
if not os.access(config['conf_dir'], os.W_OK):
print('[ERR] directory does not have write permissions', config['conf_dir'],
file=sys.stderr)
sys.exit(1)
vhost_path = os.path.join(config['conf_dir'], name+'.conf')
with open(vhost_path, 'w') as outfile:
outfile.write(vhost)
# Apply settings for logging (symlinks, mkdir) only in save mode
succ, err = apply_log_settings(config)
if not succ:
print(err, file=sys.stderr)
sys.exit(1)
else:
print(vhost)
############################################################
# Main Entry Point
############################################################
if __name__ == '__main__':
main(sys.argv[1:])
| [
"cytopia@everythingcli.org"
] | cytopia@everythingcli.org |
38dfd261fde0e0b06f1e7a60f69038ef1a14b995 | 02b1b7fa67959b298812b6316b9ccc8a1a8a9c20 | /assignment1/cs231n/classifiers/softmax.py | 5a0e7525d89988fe71a3ec0781aaebe2baba1c92 | [
"MIT"
] | permissive | gnoparus/cs231n | cf43c15d1df3558b052d31ef57b22c7ea1d1355d | 2deb3863376abd49fc3d6f339c91994791313a6c | refs/heads/master | 2020-03-23T17:50:29.222619 | 2018-08-15T09:31:33 | 2018-08-15T09:31:33 | 141,878,119 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,811 | py | import numpy as np
from random import shuffle
def softmax_loss_naive(W, X, y, reg):
"""
Softmax loss function, naive implementation (with loops)
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples.
Inputs:
- W: A numpy array of shape (D, C) containing weights.
- X: A numpy array of shape (N, D) containing a minibatch of data.
- y: A numpy array of shape (N,) containing training labels; y[i] = c means
that X[i] has label c, where 0 <= c < C.
- reg: (float) regularization strength
Returns a tuple of:
- loss as single float
- gradient with respect to weights W; an array of same shape as W
"""
# Initialize the loss and gradient to zero.
loss = 0.0
dW = np.zeros_like(W)
num_examples = X.shape[0]
num_dimensions = X.shape[1]
num_classes = W.shape[1]
#############################################################################
# TODO: Compute the softmax loss and its gradient using explicit loops. #
# Store the loss in loss and the gradient in dW. If you are not careful #
# here, it is easy to run into numeric instability. Don't forget the #
# regularization! #
#############################################################################
# for i in range(num_examples):
# efy = np.exp(f(W, X[i])[y[i]])
# efj = np.exp(f(W, X[i]))
# sum_efj = np.sum(efj)
# dW[:, y[i]] += efj / sum_efj
# loss += -np.log(efy / sum_efj)
ef = np.exp(f(W, X))
# print(ef.shape)
efy = ef[np.arange(num_examples), y]
efy = efy.reshape(-1, 1)
# print(efy.shape)
efj = np.exp(f(W, X))
# print(efj.shape)
sum_efj = np.sum(efj, axis=1, keepdims=True)
# print(sum_efj.shape)
loss = np.sum(-np.log(efy / sum_efj))
# dW[:, y] = efj / sum_efj
# print(dW[0:5])
efy_ones = np.zeros(ef.shape)
efy_ones[range(num_examples), y] = 1
dW = X.T.dot(ef / sum_efj)
dW -= X.T.dot(efy_ones)
loss /= num_examples
dW /= num_examples
loss += reg * np.sum(W * W)
#############################################################################
# END OF YOUR CODE #
#############################################################################
return loss, dW
def softmax_loss_vectorized(W, X, y, reg):
"""
Softmax loss function, vectorized version.
Inputs and outputs are the same as softmax_loss_naive.
"""
# Initialize the loss and gradient to zero.
loss = 0.0
dW = np.zeros_like(W)
num_examples = X.shape[0]
num_dimensions = X.shape[1]
num_classes = W.shape[1]
# for i in range(num_examples):
# efy = np.exp(f(W, X[i])[y[i]])
# efj = np.exp(f(W, X[i]))
# sum_efj = np.sum(efj)
# dW[:, y[i]] += efj / sum_efj
# loss += -np.log(efy / sum_efj)
ef = np.exp(f(W, X))
# print(ef.shape)
efy = ef[np.arange(num_examples), y]
efy = efy.reshape(-1, 1)
# print(efy.shape)
efj = np.exp(f(W, X))
# print(efj.shape)
sum_efj = np.sum(efj, axis=1, keepdims=True)
# print(sum_efj.shape)
loss = np.sum(-np.log(efy / sum_efj))
# dW[:, y] = efj / sum_efj
# print(dW[0:5])
efy_ones = np.zeros(ef.shape)
efy_ones[range(num_examples), y] = 1
dW = X.T.dot(ef / sum_efj)
dW -= X.T.dot(efy_ones)
loss /= num_examples
dW /= num_examples
loss += reg * np.sum(W * W)
#############################################################################
# END OF YOUR CODE #
#############################################################################
return loss, dW
def f(W, X):
return X.dot(W)
| [
"surapong@gmail.com"
] | surapong@gmail.com |
2313ffe1da046e14b348548dc0e7af8c3c5573a5 | cd1e2d7c95460c176e60b6a6b9b5e6da385f335f | /time_display/times/views.py | 3044ed3869df1956c77e2f6a91d3c177c478804a | [] | no_license | LaunaKay/my_first_blog | 1c5bc37d41c779eccb9d7f4d08aaa8af56ba725f | 8f4d585f10e495ff71d0cb85895828020318868d | refs/heads/master | 2021-01-10T20:11:05.892107 | 2015-07-17T04:36:57 | 2015-07-17T04:36:57 | 39,098,951 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 159 | py | from django.shortcuts import render
from datetime import datetime
def index(request):
return render(request, 'times/index.html', {'now': datetime.now()})
| [
"launabodde@hotmail.com"
] | launabodde@hotmail.com |
c6e7daecf09922fd61497563bd7bcede1fa5c438 | 1ef5aef9654372647dea2e6727fc8b5b2c41e0d5 | /LECTURES/06_8_11_ukoly.py | 8ee3aea2fbe56f9da0663df97830934813c6c0da | [] | no_license | stefkalad/B3B33ALP | fc48753a69c6c21a8b2c3924be23bf539169f711 | 9ac0828b57882b22c8b8feb087c9a9fe6663e64e | refs/heads/master | 2023-03-18T08:29:52.065777 | 2017-07-28T07:47:44 | 2017-07-28T07:47:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,178 | py |
"""Pokud pole o délce N, obsahuje všechna čísla od 0..N-1 právě jednou, pak toto pole kóduje permutaci tak, že první prvek se zobrazí na místo, kde se v poli nachází 0, druhý prvek na místo, kde se v poli nachází 1,
Pole [0, 1, 2, 3], kóduje identickou tzv. jednotkovou permutaci o čtyřech prvcích, pole [3, 2, 1, 0] kóduje otočení prvků v poli.
Napište program, který načtěte z jednoho řádku standardního vstupu vektor reprezentující permutaci a najde a vytiskne inverzní permutaci, tj. permutaci, která převede zadanou permutaci na jednotkovou.
Inverzní permutace k permutaci [2, 0, 1], je permutace [1, 2, 0], neboť první permutace zobrazí 0→2 a druhá permutace 2→0, obdobně 1→0, druhá permutace 0→1; první 2→1 a druhá 1→2."""""
def permutation (a):
b = [0]* len(a)
for i in range (len(a)):
b [a [i]] = i
return b
print (permutation([2,0,1]) )
print(permutation([1,2,0]) )
"Napište funkci multiVecMat(v,m), která vypočte součin vektoru v a matice m."
"Pokud nesouhlasí rozměry matice a vektoru, pak funkce vrací None"
def multiVecMat(v,m):
if (len(v) != len (m [0])):
return None
else :
for i in range (len(m)):
for j in range (len (m [i])):
m [i][j] *=v [j]
print(m [i])
m=[[0,0,1],[0,1,0],[1,0,0]]
v=[2, 4, 6]
multiVecMat (v,m)
""" Napište program, který načte matici a následně permutaci,
která definuje prohození řádků zadané matice.
Na výstup program vytiskne matici s řádky prohozenými podle zadané permutace"""
def prohozz (p,m):
b= [[0] * len(m[0])]*len(m)
for i in range (len(m)):
b [p [i]] = m [i]
print ()
for i in range (len(m)):
print(b [i])
prohozz ([1,2,0], m)
"""--------------------GAUSS ELIMINATION METHOD-------------------"""
#does not work yet
def gauss(matrix):
def findmaxrowincolumn (column):
max,maxrow =0,0
for i in range (column,len(matrix)):
if abs( matrix [i][column]) > max:
maxrow = i
max = abs( matrix [i][column])
return maxrow
def set (column):
maxrow =findmaxrowincolumn(column)
if maxrow !=column:
temp = matrix [column]
matrix [column] = matrix [maxrow]
matrix [maxrow] = temp
def do_line (i):
set (i)
if matrix [i][i] != 0:
for r in range (len (matrix)):
for l in range (len(matrix[r])):
if r!=i:
matrix [r][l] -= (matrix[r][i]*matrix [i][l])
else:
matrix[i][l] = matrix[i][l] / matrix[i][i]
return True
else:
return False
for i in range (len(matrix)):
if not do_line(i):
return False
return True
matrix = [
[12,-7,3, 26],
[4 ,5,-6, -5],
[-7 ,8,9, 21]
]
from fractions import Fraction
mm = [list(map(Fraction, v)) for v in matrix]
result = [list(map(Fraction, v)) for v in mm]
gauss(mm) | [
"stefka885@gmail.com"
] | stefka885@gmail.com |
24a7e0e511a2d8d8023e5a267a26f01231db6504 | bc6492a9a30ac7228caad91643d58653b49ab9e3 | /sympy/parsing/autolev/test-examples/pydy-example-repo/chaos_pendulum.py | 37a8673cd2de946f7185811aa561c209c9982994 | [] | no_license | cosmosZhou/sagemath | 2c54ea04868882340c7ef981b7f499fb205095c9 | 0608b946174e86182c6d35d126cd89d819d1d0b8 | refs/heads/master | 2023-01-06T07:31:37.546716 | 2020-11-12T06:39:22 | 2020-11-12T06:39:22 | 311,177,322 | 1 | 0 | null | 2020-11-12T06:09:11 | 2020-11-08T23:42:40 | Python | UTF-8 | Python | false | false | 2,288 | py | import sympy.physics.mechanics as me
import sympy as sm
import math as m
import numpy as np
g, lb, w, h = sm.symbols('g lb w h', real=True)
theta, phi, omega, alpha = me.dynamicsymbols('theta phi omega alpha')
thetad, phid, omegad, alphad = me.dynamicsymbols('theta phi omega alpha', 1)
thetad2, phid2 = me.dynamicsymbols('theta phi', 2)
frame_n = me.ReferenceFrame('n')
body_a_cm = me.Point('a_cm')
body_a_cm.set_vel(frame_n, 0)
body_a_f = me.ReferenceFrame('a_f')
body_a = me.RigidBody('a', body_a_cm, body_a_f, sm.symbols('m'), (me.outer(body_a_f.x,body_a_f.x),body_a_cm))
body_b_cm = me.Point('b_cm')
body_b_cm.set_vel(frame_n, 0)
body_b_f = me.ReferenceFrame('b_f')
body_b = me.RigidBody('b', body_b_cm, body_b_f, sm.symbols('m'), (me.outer(body_b_f.x,body_b_f.x),body_b_cm))
body_a_f.orient(frame_n, 'Axis', [theta, frame_n.y])
body_b_f.orient(body_a_f, 'Axis', [phi, body_a_f.z])
point_o = me.Point('o')
la = (lb-h/2)/2
body_a_cm.set_pos(point_o, la*body_a_f.z)
body_b_cm.set_pos(point_o, lb*body_a_f.z)
body_a_f.set_ang_vel(frame_n, omega*frame_n.y)
body_b_f.set_ang_vel(body_a_f, alpha*body_a_f.z)
point_o.set_vel(frame_n, 0)
body_a_cm.v2pt_theory(point_o,frame_n,body_a_f)
body_b_cm.v2pt_theory(point_o,frame_n,body_a_f)
ma = sm.symbols('ma')
body_a.mass = ma
mb = sm.symbols('mb')
body_b.mass = mb
iaxx = 1/12*ma*(2*la)**2
iayy = iaxx
iazz = 0
ibxx = 1/12*mb*h**2
ibyy = 1/12*mb*(w**2+h**2)
ibzz = 1/12*mb*w**2
body_a.inertia = (me.inertia(body_a_f, iaxx, iayy, iazz, 0, 0, 0), body_a_cm)
body_b.inertia = (me.inertia(body_b_f, ibxx, ibyy, ibzz, 0, 0, 0), body_b_cm)
force_a = body_a.mass*(g*frame_n.z)
force_b = body_b.mass*(g*frame_n.z)
kd_eqs = [thetad - omega, phid - alpha]
forceList = [(body_a.masscenter,body_a.mass*(g*frame_n.z)), (body_b.masscenter,body_b.mass*(g*frame_n.z))]
kane = me.KanesMethod(frame_n, q_ind=[theta,phi], u_ind=[omega, alpha], kd_eqs = kd_eqs)
fr, frstar = kane.kanes_equations([body_a, body_b], forceList)
zero = fr+frstar
from pydy.system import System
sys = System(kane, constants = {g:9.81, lb:0.2, w:0.2, h:0.1, ma:0.01, mb:0.1},
specifieds={},
initial_conditions={theta:np.deg2rad(90), phi:np.deg2rad(0.5), omega:0, alpha:0},
times = np.linspace(0.0, 10, 10/0.02))
y=sys.integrate()
| [
"74498494@qq.com"
] | 74498494@qq.com |
6d423d6258f05fc1ba8421679354daaa2a7c5ec5 | 778d01630c7f14fbb625f69282bb54f1b3c5b2d2 | /CommandService/Commands/CommandContainer.py | fc4f368dcb015583b2b54f6ba956e6837ef07db1 | [
"MIT"
] | permissive | CommName/WildeLifeWatcher | 9155014ce18d97746d3f141c0fafa038ae1d7cc8 | 3ce3b564d0e6cc81ebc2b607a712580d3c388db6 | refs/heads/master | 2023-01-08T17:11:56.982509 | 2020-10-31T20:24:59 | 2020-10-31T20:24:59 | 264,182,386 | 0 | 0 | MIT | 2020-10-31T20:25:00 | 2020-05-15T12:00:50 | Python | UTF-8 | Python | false | false | 2,117 | py | from Commands import Command
import cherrypy
@cherrypy.expose
class CommandContainer:
activeCommands = { }
def updateCommands(self, commandName, listOfParametars, typeOfParametars, addressOfActuator, listOfParametarsOfActuator):
if commandName in self.activeCommands:
self.activeCommands[commandName].listOfParametars = listOfParametars
self.activeCommands[commandName].addressOfActuator = addressOfActuator
self.activeCommands[commandName].typeOfParametars = typeOfParametars
self.activeCommands[commandName].listOfParametarsOfActuator = listOfParametarsOfActuator
else:
command = Command.Command()
command.address = commandName
command.listOfParametars = listOfParametars
command.addressOfActuator = addressOfActuator
command.typeOfParametars = typeOfParametars
command.listOfParametarsOfActuator = listOfParametarsOfActuator
self.activeCommands[commandName] = command
conf = {
'/': {
'request.dispatch' : cherrypy.dispatch.MethodDispatcher(),
'tools.response_headers.on' : True,
'tools.response_headers.headers' : [('Content-Type', 'text/plain')]
}
}
cherrypy.tree.mount(command,"/"+commandName,conf)
cherrypy.engine.stop()
cherrypy.engine.start()
def PUT(self, commandName, listOfParametars, typeOfParametars, addressOfActuator, listOfParametarsOfActuator):
listOfParametars = listOfParametars.split(",")
typeOfParametars = typeOfParametars.split(",")
print(typeOfParametars)
listOfParametarsOfActuator = listOfParametarsOfActuator.split(",")
self.updateCommands(commandName, listOfParametars, typeOfParametars, addressOfActuator, listOfParametarsOfActuator)
return
def GET(self):
response = ""
for commandName in self.activeCommands:
response += self.activeCommands[commandName].tooString()
return response
| [
"17132081+CommName@users.noreply.github.com"
] | 17132081+CommName@users.noreply.github.com |
1ac4a60f81639fed47a70fc4cdb083acb2b113d3 | 84546b96812b1dabac230d1e3a14f43313617ce3 | /Wetting Transition/Problem 10.py | f227688d063e27e0fb2e98f84e8db46baf6b4eca | [] | no_license | NikitaPoljakov/Nikita-Poljakov | 6a98b23e9bf5fa07c3bb408f8cd622152f559122 | f3d61a1fe8659013e272f9c919f460eb74748d91 | refs/heads/master | 2020-12-27T07:04:44.370531 | 2020-11-21T10:18:43 | 2020-11-21T10:18:43 | 237,806,619 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,536 | py | import scipy as sp
import matplotlib
import matplotlib.pyplot as py
import math
import numpy as np
#Some global settings for matplotlib plots
matplotlib.rcParams['font.size'] = 12
matplotlib.rcParams['font.weight'] = 'bold'
# [Starter code for Problem 8]
# ------------------------------------------------------------
# Solving the bulk with an inhomogeneous iterative method
# ------------------------------------------------------------
#Define some useful objects
class Latticesite:
def __init__(self,siteNumber, epsilon_w):
self.index = siteNumber
self.coordinate = []
self.NNs = []
self.NNNs = []
self.potential = potential(np.floor(siteNumber/Ly), epsilon_w)
self.density_current = 0.0
self.density_previous = 0.0
def update(self):
'''Update the density. Remember to account for divergences under iteration'''
if self.density_current<1.0:
self.density_previous = self.density_current
elif self.density_current>1.0:
self.density_previous = 1.0
else:
self.density_previous = 0.0
def iterate(sites, k, mu, beta, epsilon):
'''Perform a single iteration of eq. 46 for the particle at site k, given the sitelist sites'''
nDens = 0.0
nnDens = 0.0
for neighbor in sites[k].NNs:
nDens = nDens + sites[neighbor].density_previous
for neighbor in sites[k].NNNs:
nnDens = nnDens + sites[neighbor].density_previous
return (1-sites[k].density_previous)*sp.exp(beta*(mu + epsilon * nDens + 0.25 * epsilon * nnDens - sites[k].potential)) #Here we assume T,mu,V are all in units of the interaction strength
def potential(y, epsilon_w):
if y >= 1:
return - epsilon_w * y**(-3)
else:
return 10**10
#The lattice is a (Lx x Ly square lattice)
Lx = 20
Ly = 20
#Initialize the lattice
def initialize(Lx,Ly, epsilon_w):
def getIndex(Lx,nSites):
'''Converts from coordinates (x,y) to lattice index'''
return lambda x,y:(Lx*x + y)
nSites = Lx*Ly
sites = [Latticesite(k, epsilon_w) for k in range(nSites)]
pos = getIndex(Lx,Ly)
for site in sites:
x,y = [site.index//Lx,site.index%Lx] #Get x and y coordinates and from those the coordinates of the neighbors
nns = set([((x+1)%Lx,y),((x-1)%Lx,y),(x,(y+1)%Ly),(x,(y-1)%Ly)])
nnns = set([( (x+1)%Lx,(y+1)%Ly ),( (x-1)%Lx, (y-1)%Ly),((x-1)%Lx,(y+1)%Ly),((x+1)%Lx,(y-1)%Ly)])
site.NNs = [pos(x[0],x[1]) for x in nns] #Store the neighbor indices as instance variables
site.NNNs = [pos(x[0],x[1]) for x in nnns]
site.density_previous = 0.2 #Initialize the system in the low density limit
return sites
#Now we iterate the solver until the density is converged
def run(mu, T, epsilon, epsilon_w, Lx,Ly,cTol=10**-8,mixing=0.1,iterMax=1000,show=True):
'Calculates the density profile at a given mu,T'
sites = initialize(Lx,Ly, epsilon_w)
convergence = 0.1
iteration = 0.0
while (convergence>cTol) and (iteration<iterMax):
for k in range(len(sites)):
sites[k].density_current = sites[k].density_previous*(1 - mixing) + mixing*iterate(sites,k,mu,1/T, epsilon) #Calculate new state of the system from the old state of the system
two_norm = sum([(site.density_current-site.density_previous)**2 for site in sites])
convergence = math.sqrt(two_norm)
iteration = iteration + 1
for site in sites:
site.update()
'Can then return an image of the density profile'
z = []
for site in sites:
z.append(site.density_previous)
Z = sp.array(z)
Z = sp.reshape(Z,(Lx,Ly))
Z = np.transpose(Z)
return Lx * Z[0]
#Run a few examples
epsilon = 1.2
epsilon_w = 1.6
beta = 1
y = []
MU = [-2.67 * epsilon, -2.53 * epsilon]
for mu in MU:
y.append(run(mu, 1 / beta, epsilon, epsilon_w, Lx, Ly))
x = np.linspace(0, Ly, Ly)
py.style.use("dark_background")
py.plot(x, y[0], color = 'c', label = 'μ / Ɛ = -2.67')
py.plot(x, y[1], color = 'm', label = 'μ / Ɛ = -2.53')
py.xlabel('y', size = 20)
py.ylabel('ρ', size = 20)
py.legend(prop={'size': 15})
py.tight_layout()
py.savefig('Problem10.pdf')
py.show()
#figs, ax = py.subplots()
#ax = [run(k,0.5,4,4,show=False) for k in [-1,-4]] | [
"noreply@github.com"
] | NikitaPoljakov.noreply@github.com |
7fd2d5ad64fa43f8ec7d8a279323a084331cf8ba | e024f354b91474438457cb1067bed48e07cfab45 | /gpii/node_modules/packagekit/nodepackagekit/binding.gyp | 981609d9e75f37c3d7a3331957b79840e0984fc8 | [
"BSD-3-Clause"
] | permissive | avtar/linux | 5a889985250ddbd49427756a78f1a97594bc01e8 | e9d3fdbc3d3cc71b9984532d35de64b98d5d6d38 | refs/heads/master | 2020-11-30T01:43:27.392813 | 2016-02-13T02:51:01 | 2016-02-13T02:51:01 | 40,628,691 | 0 | 1 | null | 2015-10-02T18:23:25 | 2015-08-12T23:13:19 | JavaScript | UTF-8 | Python | false | false | 368 | gyp | {
"targets": [
{
"target_name": "nodepackagekit",
"sources": ["nodepackagekit.cc"],
"libraries": ["<!@(pkg-config --libs gio-2.0 packagekit-glib2 json-glib-1.0)"],
"cflags": ["<!@(pkg-config --cflags gio-2.0 packagekit-glib2 json-glib-1.0)"],
"ldflags": ["<!@(pkg-config --libs gio-2.0 packagekit-glib2 json-glib-1.0)"]
}
]
}
| [
"jhernandez@emergya.com"
] | jhernandez@emergya.com |
7066f6324d677c473d56f32926737143bc9f2c62 | 3c936c644748309614dce52ed7aa1abfc4d15ed2 | /code/03_parse_price_reports.py | 2e5878ece3a72a258d3cbe08e869b4ae9926c558 | [] | no_license | drewdiprinzio/usda-esmis-parsing | c6a0a55958e6ba6bbfd85178cb442a9ed1a90bfb | e69f89d075453ffbc925cd8d204240e9fb3cf675 | refs/heads/master | 2022-06-12T20:44:23.507876 | 2020-05-06T02:07:56 | 2020-05-06T02:07:56 | 255,337,332 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,980 | py | # -*- coding: utf-8 -*-
"""
Last edited April 2020
@author: Drew DiPrinzio
"""
import urllib
import pandas as pd
from datetime import datetime
import re
import pickle
import os
"""
Create directories for saving analysis
"""
def create_dir(path):
try:
# Create target Directory
os.mkdir(path)
print("Directory " , path , " Created ")
except FileExistsError:
print("Directory " , path , " already exists")
create_dir('txt_files')
create_dir('export')
"""
Download txt files from the web and save in "txt_files" folder.
The links to these files were saved in 'export/files.csv' in 01_scrape_reports.py file.
"""
link_df = pd.read_csv('export/files.csv')
txt_files = link_df[link_df['file_type']=='txt']
def save_files(i):
file_path = list(txt_files['file'])[i]
date = list(txt_files['date'])[i][0:10]
name = list(txt_files['file_name'])[i]
file = urllib.request.urlopen(file_path)
content = []
for line in file:
decoded_line = line.decode("unicode_escape")
content.append(decoded_line)
with open(f'txt_files/{i:04}_{date}_{name}.txt', 'wb') as fp:
pickle.dump(content, fp)
# Run function
for i in range(0,len(txt_files)):
save_files(i)
if(i % 10 == 0):
print(i)
"""
Open and parse txt files and append to a dataframe.
Each report contains two sub-tables:
- Average weekly price by variety, dollars per pound
- Weekly marketings by variety, in 1,000 pounds
The below functions do the following:
- Reads in txt file and creates a list where each element is a line in the file
- Finds beginning and end lines of both sub-tables, parses data and creates dataframe
- Stack dataframe from each file and deduplicate based on date, since the same week
can be in multiple reports
- Return stacked_data_p1 and stacked_data_p2 which contains all data for panel 1 and panel 2
"""
def parse_file(i):
# a_file = list(txt_files['Files'])[i]
date = list(txt_files['date'])[i][0:10]
name = list(txt_files['file_name'])[i]
#Returns indices in list where {string} is in the element
def grepl(string,l):
return [i for i, val in enumerate(l) if string in val]
with open (f'txt_files/{i:04}_{date}_{name}.txt', 'rb') as fp:
content = pickle.load(fp)
"""
Find the lines which contain data tables
"""
# This line is always at the beginning of the table in the txt file
start_table_index = grepl('Peanut Prices and Marketings by Type',content)
# More recent years have 'Statistical Methodology' immediately after the table
# In the past this section was called 'Survey Procedures' so we use this to find
# the end of the table.
end_table_index = grepl('Statistical Methodology',content)
end_table_index_alt = grepl('Survey Procedures',content)
if(len(start_table_index)<1 and len(end_table_index)<1 and len(end_table_index_alt)<1):
print(f'File {i:04} does not seem to have a table.')
return(None,None)
start_table_index = start_table_index[0]
if (len(end_table_index)>0):
end_table_index = end_table_index[0]
else:
end_table_index = end_table_index_alt[0]
table_lines = content[start_table_index:end_table_index]
"""
Parse Month and Day Lines to Create 6-element Date list
"""
date_start = grepl('Item and type',table_lines)[0]
md_line = table_lines[date_start+1]
year_line = table_lines[date_start+2]
def create_dates(months,years):
month = re.compile('[A-Za-z]{3,10} [0-9]{1,2},')
m_parsed = month.findall(months)
year = re.compile('[0-9]{4}')
y_parsed = year.findall(years)
if(len(m_parsed)<5 or len(y_parsed)<5):
print(f'File {i:04} might be missing dates.')
return(None,None)
dates = []
for (item1, item2) in zip(m_parsed, y_parsed):
dates.append(item1+' '+item2)
dates = list(map(lambda x: datetime.strptime(x, '%B %d, %Y'), dates))
# print('The most recent date is {:%B %d, %Y}'.format(dates[len(dates)-1]))
dates.insert(0,'Date')
return(dates)
dates = create_dates(md_line,year_line)
"""
We now have a list of strings which only contains the table information as 'table_lines'.
We also have a series called 'dates' which will be used as the date column in the df.
We run parse_panel() on the first and second sub-tables, or "panels"
"""
#Subset to two panels
#Panel one lines
beg_panel_one = grepl('Runner',table_lines)[0]
end_panel_one = grepl('All .....',table_lines)[0]+1
first_panel = table_lines[beg_panel_one:end_panel_one]
#Panel two lines
beg_panel_two = grepl('Runner',table_lines)[1]
end_panel_two = grepl('All .....',table_lines)[1]+1
second_panel = table_lines[beg_panel_two:end_panel_two]
#Define parsing function
def parse_panel(panel):
parsed_panel = []
def parse_line(l):
parsed = [l[0:15].replace(".","").replace(":","").replace(" ",""),
l[15:25],
l[25:40],
l[40:55],
l[55:70],
l[70:85]]
parsed = list(map(lambda x: str.strip(x).replace('Runners','Runner').replace('Valencias','Valencia').replace('Virginias','Virginia'), parsed))
return(parsed)
for line in panel:
parsed_panel.append(parse_line(line))
df = pd.DataFrame(parsed_panel, columns = ['type','date1','date2','date3','date4','date5'])
# filters out row which is blank in type column
df = df[(list(map(lambda x: len(x)!=0,df['type'])))]
# reshapes table
df = df.stack().unstack(0)
df['name_date'] = dates
df.columns = df.iloc[0]
df = df.drop(df.index[0])
df['file_num'] = i
# df.to_csv('export/{:%Y%m%d}_{}.csv'.format(max(df['date']),file_name))
return(df)
parsed_panel_one = parse_panel(first_panel)
parsed_panel_two = parse_panel(second_panel)
return(parsed_panel_one, parsed_panel_two)
#txt_files = list(link_df[link_df['Types']=='txt']['Files'])
"""
run_all() is a wrapper function to run parse_file() over a certian number
of txt files and append them together.
"""
def run_all(file_list,start,end):
#for i in range(0,len(file_list)):
for i in range(start,end):
if (i%50==0):
print(f'Parsing file {i}')
a, b = parse_file(i)
if (a is not None):
if(i==0):
stacked_data_p1 = a
stacked_data_p2 = b
else:
stacked_data_p1 = pd.concat([stacked_data_p1, a], axis=0)
stacked_data_p2 = pd.concat([stacked_data_p2, b], axis=0)
stacked_data_p1 = stacked_data_p1.sort_values('Date').replace(to_replace={'(D)': None, '(X)': None}).drop_duplicates('Date')
stacked_data_p2 = stacked_data_p2.sort_values('Date').replace(to_replace={'(D)': None, '(X)': None}).drop_duplicates('Date')
stacked_data_p1.reset_index(drop=True, inplace=True)
stacked_data_p2.reset_index(drop=True, inplace=True)
return(stacked_data_p1, stacked_data_p2)
"""
Run function
"""
stacked_data_p1, stacked_data_p2 = run_all(txt_files,0,500)
"""
Plot data with matplotlib
"""
#Change types of price columns to float
cols_to_change = ['Runner','Spanish','Valencia','Virginia','All']
for i in cols_to_change:
stacked_data_p1[i] = stacked_data_p1[i].astype('float64')
#Plot with matplotlib
from matplotlib import pyplot as plt
plt.style.use('seaborn')
plt.plot('Date', 'Runner', data=stacked_data_p1, color='midnightblue', linewidth=1.5)
plt.plot('Date', 'Spanish', data=stacked_data_p1, color='royalblue', linewidth=1.5)
plt.plot('Date', 'Virginia', data=stacked_data_p1, color='mediumslateblue', linewidth=1.5)
plt.plot('Date', 'Valencia', data=stacked_data_p1, color='c', linewidth=1.5)
plt.plot('Date', 'All', data=stacked_data_p1, color='grey', linewidth=1.5)
plt.ylabel('Dollars per Pound')
plt.suptitle('Prices of Peanut Varieties from Web-scraped USDA Reports\n2010-2020')
plt.xlabel('\n\nSource: National Agricultural Statistics Service (NASS), Agricultural Statistics Board, \nUnited States Department of Agriculture (USDA), accessed at Cornell Mann Library website:\nhttps://usda.library.cornell.edu\n\nData from 500 files reported weekly, from June 2010 to April 2020.', position=(0., 1e6),horizontalalignment='left')
plt.legend()
plt.savefig('export/historical_peanut_prices.png', bbox_inches='tight') | [
"drewdiprinzio@gmail.com"
] | drewdiprinzio@gmail.com |
0e37440791d78c9663e093eafeeae77a3c40d5d9 | 56799d321030b5e2ddda6138c171e185c1443154 | /training/emmental/modules/masked_nn.py | 5db001d0aa43d93723bd880586322f827e04d6cf | [
"MIT"
] | permissive | yaozhewei/MLPruning | def36abbd089111a326549541479661f5d389028 | 54839126218b53d08ef41a3767cc15e71933023f | refs/heads/main | 2023-06-12T10:13:33.882045 | 2021-06-29T05:58:09 | 2021-06-29T05:58:09 | 366,893,028 | 19 | 2 | null | null | null | null | UTF-8 | Python | false | false | 11,015 | py | # This code is modified from https://github.com/huggingface/transformers/tree/master/examples/research_projects/movement-pruning
# Licensed under the Apache License, Version 2.0 (the "License");
# We add more functionalities as well as remove unnecessary functionalities
import math
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn import init
from .binarizer import TopKBinarizer
# This function is from
# https://stackoverflow.com/questions/16873441/form-a-big-2d-array-from-multiple-smaller-2d-arrays
def blockshaped(arr, nrows, ncols):
"""
Return an array of shape (n, nrows, ncols) where
n * nrows * ncols = arr.size
If arr is a 2D array, the returned array looks like n subblocks with
each subblock preserving the "physical" layout of arr.
"""
h, w = arr.shape
return (arr.reshape(h // nrows, nrows, -1, ncols)
.swapaxes(1, 2)
.reshape(-1, nrows, ncols))
# This function is from
# https://stackoverflow.com/questions/16873441/form-a-big-2d-array-from-multiple-smaller-2d-arrays
def unblockshaped(arr, h, w):
"""
Return an array of shape (h, w) where
h * w = arr.size
If arr is of shape (n, nrows, ncols), n sublocks of shape (nrows, ncols),
then the returned array preserves the "physical" layout of the sublocks.
"""
n, nrows, ncols = arr.shape
return (arr.reshape(h // nrows, -1, nrows, ncols)
.swapaxes(1, 2)
.reshape(h, w))
class MaskedLinear(nn.Linear):
"""
Fully Connected layer with on the fly adaptive mask during training,
and does real pruning during inference
"""
def __init__(
self,
in_features: int,
out_features: int,
bias: bool = True,
mask_init: str = "constant",
mask_scale: float = 0.0,
pruning_method: str = "topK",
head_split: int = -1,
bias_mask: bool = False,
head_pruning: bool = False,
row_pruning: bool = True
):
"""
Args:
in_features (`int`)
Size of each input sample
out_features (`int`)
Size of each output sample
bias (`bool`)
If set to ``False``, the layer will not learn an additive bias.
Default: ``True``
mask_init (`str`)
The initialization method for the score matrix if a score matrix is needed.
Choices: ["constant", "uniform", "kaiming"]
Default: ``constant``
mask_scale (`float`)
The initialization parameter for the chosen initialization method `mask_init`.
Default: ``0.``
pruning_method (`str`)
Method to compute the mask.
Default: ``topK``
head_split:
The number of head in the layer. This can also used to make each head prune
out with same number of rows (so that we can do parallize forward with reshape)
Default: ``-1`` (means no need for head split)
bias_mask:
Prune bias or not
Default: False
head_pruning:
Do Head Pruning or not
Default: False
row_pruning:
Do Row Pruning or Not
Defualt: True
"""
super(
MaskedLinear,
self).__init__(
in_features=in_features,
out_features=out_features,
bias=bias)
self.pruning_method = pruning_method
self.head_split = head_split
self.bias_mask = bias_mask
self.head_pruning = head_pruning
self.row_pruning = row_pruning
self.inference_mode = False
# this is used for final block-wise pruning, for init we do not need to
# worry about that!
self.block_pruning = False # We will enable this when needed
self.block_mask_scores = None # the mask for block wise pruning
self.threshold_block = None # the threshold for block wise pruning
self.mask_scale = mask_scale
self.mask_init = mask_init
if self.row_pruning:
self.mask_scores = nn.Parameter(
torch.Tensor(
self.weight.size(0),
1)) # number of rows * 1
self.init_mask(self.mask_scores)
self.threshold_row = nn.Parameter(torch.zeros(1) + 10.0)
if self.head_pruning:
self.head_mask_scores = nn.Parameter(
torch.Tensor(self.head_split, 1)) # number of heads * 1
self.init_mask(self.head_mask_scores)
self.threshold_head = nn.Parameter(torch.zeros(1) + 10.0)
def init_mask(self, mask):
if self.mask_init == "constant":
init.constant_(mask, val=self.mask_scale)
elif self.mask_init == "uniform":
init.uniform_(mask, a=-self.mask_scale, b=self.mask_scale)
elif self.mask_init == "kaiming":
init.kaiming_uniform_(mask, a=math.sqrt(5))
def get_mask(self):
# get head mask
if self.head_pruning:
mask_head = TopKBinarizer.apply(
self.head_mask_scores, self.threshold_head, -1) # for now, only support this
else:
mask_head = None
if self.row_pruning:
mask = TopKBinarizer.apply(
self.mask_scores, self.threshold_row, -1)
else:
mask = None
return mask_head, mask
def make_inference_pruning(self, blocksize):
self.inference_mode = True
weight_shape = self.weight.size()
# if there is no block wise pruning needed, we do not have to increase the
# numner of rows/cols.
# Otherwise, we need to pad the matrix so that the # of ros/cols is divided by
# block size
if blocksize[0] is not None and blocksize[1] is not None and self.row_pruning:
rows = weight_shape[0]
row_block = blocksize[0]
# remain rows
mask_head, mask = self.get_mask()
remaining_row_block = math.ceil(mask.sum().item() / row_block)
remaining_row = remaining_row_block * row_block
remaining_ratio = remaining_row / rows - 1e-6
self.threshold_row.data = self.threshold_row.data * 0 + \
math.log(remaining_ratio / (1 - remaining_ratio))
mask_head, mask = self.get_mask()
if not self.head_pruning:
mask_head = torch.ones_like(self.weight[:, 0]).type(
'torch.BoolTensor').view(-1)
else:
mask_head = mask_head.type('torch.BoolTensor').view(-1)
mask_head = torch.repeat_interleave(
mask_head, weight_shape[0] // self.head_split)
if not self.row_pruning:
mask = torch.ones_like(self.weight[:, 0])
mask = mask.type('torch.BoolTensor').view(-1)
mask = torch.logical_and(mask_head, mask)
self.weight = nn.Parameter(self.weight[mask, :])
if self.bias_mask:
self.bias = nn.Parameter(self.bias[mask])
# we do not need those parameters!
self.mask_scores = None
self.head_mask_scores = None
self.threshold_head = None
self.threshold_row = None
# we need this mask for some Layer O and FC2 pruning
return mask
def make_column_purning(self, mask):
# make column pruning for Layer O and FC2
self.weight = nn.Parameter(self.weight[:, mask])
def enable_block_pruning(self, block_size):
# As the name suggested, enable block wise pruning
self.block_pruning = True
self.block_rows = block_size[0]
self.block_cols = block_size[1]
mask_size_row = self.weight.size(0) // block_size[0]
mask_size_col = self.weight.size(1) // block_size[1]
self.block_mask_scores = nn.Parameter(
torch.Tensor(
mask_size_row *
mask_size_col,
1,
1)) # number of row_block * col_block
self.init_mask(self.block_mask_scores)
self.threshold_block = nn.Parameter(torch.zeros(1) + 10.0)
def get_block_wise_pruning(self):
# As the name suggested, get the block wise mask
mask_block = TopKBinarizer.apply(
self.block_mask_scores, self.threshold_block, -1) # for now, only support this
return mask_block
def make_block_wise_inference_pruning(self):
mask_block = self.get_block_wise_pruning()
rows, cols = self.weight.shape
tmp_weight = blockshaped(
self.weight,
self.block_rows,
self.block_cols) # n-block x 32 x 32
tmp_weight = tmp_weight * mask_block # n-block x 1 x 1
tmp_weight = unblockshaped(tmp_weight, rows, cols) # d x d
self.weight = nn.Parameter(tmp_weight)
# we do not need those values anymore
self.block_pruning = False
self.block_mask_scores = None
self.threshold_block = None
def forward(self, input: torch.tensor):
if not self.inference_mode:
output = self.training_forward(input)
else:
if not self.block_pruning:
output = self.inference_forward(input)
else:
output = self.block_pruning_forward(input)
return output
def block_pruning_forward(self, input: torch.tensor):
mask_block = self.get_block_wise_pruning()
rows, cols = self.weight.shape
tmp_weight = blockshaped(self.weight, self.block_rows, self.block_cols)
tmp_weight = tmp_weight * mask_block
tmp_weight = unblockshaped(tmp_weight, rows, cols)
return F.linear(input, tmp_weight, self.bias)
def inference_forward(self, input: torch.tensor):
return F.linear(input, self.weight, self.bias)
def training_forward(self, input: torch.tensor):
mask_head, mask = self.get_mask()
weight_shape = self.weight.size()
bias_shape = self.bias.size()
if self.head_pruning:
weight_thresholded = (
self.weight.view(
self.head_split, -1) * mask_head).view(weight_shape)
if self.bias_mask:
bias_thresholded = (
self.bias.view(
self.head_split, -1) * mask_head).view(bias_shape)
else:
weight_thresholded = self.weight
bias_thresholded = self.bias
# Mask weights with computed mask
if self.row_pruning:
weight_thresholded = mask * weight_thresholded
if self.bias_mask:
bias_thresholded = mask.view(
self.bias.size()) * bias_thresholded
else:
bias_thresholded = bias_thresholded
return F.linear(input, weight_thresholded, bias_thresholded)
| [
"zheweiy@berkeley.edu"
] | zheweiy@berkeley.edu |
8341914461ecb9234ab7a445508b8100836b4b20 | d7d0f11e9eb74ad2a1b487082e61ce41b6cd6ae5 | /SingleNumber.py | fc8f444cd4d4897465d4665f1f7199e20d311563 | [] | no_license | liuiuge/LeetCodeSummary | 7b1a7670d8e579f4abca16a461f692a1273fb5b1 | 0fd06566bb12b19d8088507ec4824995e869d01f | refs/heads/master | 2021-11-24T07:34:37.472304 | 2021-11-23T08:26:07 | 2021-11-23T08:26:07 | 100,717,895 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 252 | py | #!/usr/bin/env python
# coding=utf-8
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
cnt = 0
for num in (nums):
cnt^=num
return cnt
| [
"1220595883@qq.com"
] | 1220595883@qq.com |
bacdf2f00350a68110f0280482dc9a5a66f42ca1 | d6adf44edd07fc3a5b656369a90d772e0f5b67d9 | /books/scipy-lectures-scipy-lectures.github.com-465c16a/plot_directive/pyplots/numpy_intro_1.py | 193fbb394da73c3b870a1f444452134aa7c75ec1 | [
"CC-BY-4.0"
] | permissive | N4A/papers | d82d410d1261eacf3077cd04cd50696e805e2d1d | d7cd63eb8bb3dcaff495e67a75f453e01cc5ac50 | refs/heads/master | 2021-01-22T23:43:44.157677 | 2019-02-25T16:13:19 | 2019-02-25T16:13:19 | 85,660,885 | 7 | 1 | null | null | null | null | UTF-8 | Python | false | false | 237 | py | import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 3, 20)
y = np.linspace(0, 9, 20)
plt.plot(x, y) # line plot
plt.plot(x, y, 'o') # dot plot
plt.show() # <-- shows the plot (not needed with Ipython)
| [
"1813877406@qq.com"
] | 1813877406@qq.com |
b36f06c9652e2fbae6172bcb85bd4a8c0f31b2a2 | 35a87eeced2d2ed6f93ec9fa823c2c85ccc3c947 | /tests/opengl/test_color_opengl.py | 0a53f60c539eaec2ee6eb79e223edf4b57e75237 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | torannn/manim | 384004ef41108b9699ece500f1a1a9446f5b51d9 | 88836df8ab1ea153ed57848a74a694c517962163 | refs/heads/main | 2023-09-01T11:51:09.600670 | 2023-08-09T17:44:17 | 2023-08-09T17:44:17 | 386,832,604 | 2 | 0 | MIT | 2021-07-17T04:09:12 | 2021-07-17T04:09:11 | null | UTF-8 | Python | false | false | 6,013 | py | from __future__ import annotations
import numpy as np
from manim import BLACK, BLUE, GREEN, PURE_BLUE, PURE_GREEN, PURE_RED, Scene
from manim.mobject.opengl.opengl_mobject import OpenGLMobject
from manim.mobject.opengl.opengl_vectorized_mobject import OpenGLVMobject
def test_import_color(using_opengl_renderer):
import manim.utils.color as C
C.WHITE
def test_background_color(using_opengl_renderer):
S = Scene()
S.renderer.background_color = "#FF0000"
S.renderer.update_frame(S)
np.testing.assert_array_equal(
S.renderer.get_frame()[0, 0], np.array([255, 0, 0, 255])
)
S.renderer.background_color = "#436F80"
S.renderer.update_frame(S)
np.testing.assert_array_equal(
S.renderer.get_frame()[0, 0], np.array([67, 111, 128, 255])
)
S.renderer.background_color = "#FFFFFF"
S.renderer.update_frame(S)
np.testing.assert_array_equal(
S.renderer.get_frame()[0, 0], np.array([255, 255, 255, 255])
)
def test_set_color(using_opengl_renderer):
m = OpenGLMobject()
assert m.color.to_hex() == "#FFFFFF"
np.alltrue(m.rgbas == np.array((0.0, 0.0, 0.0, 1.0)))
m.set_color(BLACK)
assert m.color.to_hex() == "#000000"
np.alltrue(m.rgbas == np.array((1.0, 1.0, 1.0, 1.0)))
m.set_color(PURE_GREEN, opacity=0.5)
assert m.color.to_hex() == "#00FF00"
np.alltrue(m.rgbas == np.array((0.0, 1.0, 0.0, 0.5)))
m = OpenGLVMobject()
assert m.color.to_hex() == "#FFFFFF"
np.alltrue(m.fill_rgba == np.array((0.0, 0.0, 0.0, 1.0)))
np.alltrue(m.stroke_rgba == np.array((0.0, 0.0, 0.0, 1.0)))
m.set_color(BLACK)
assert m.color.to_hex() == "#000000"
np.alltrue(m.fill_rgba == np.array((1.0, 1.0, 1.0, 1.0)))
np.alltrue(m.stroke_rgba == np.array((1.0, 1.0, 1.0, 1.0)))
m.set_color(PURE_GREEN, opacity=0.5)
assert m.color.to_hex() == "#00FF00"
np.alltrue(m.fill_rgba == np.array((0.0, 1.0, 0.0, 0.5)))
np.alltrue(m.stroke_rgba == np.array((0.0, 1.0, 0.0, 0.5)))
def test_set_fill_color(using_opengl_renderer):
m = OpenGLVMobject()
assert m.fill_color.to_hex() == "#FFFFFF"
np.alltrue(m.fill_rgba == np.array((0.0, 1.0, 0.0, 0.5)))
m.set_fill(BLACK)
assert m.fill_color.to_hex() == "#000000"
np.alltrue(m.fill_rgba == np.array((1.0, 1.0, 1.0, 1.0)))
m.set_fill(PURE_GREEN, opacity=0.5)
assert m.fill_color.to_hex() == "#00FF00"
np.alltrue(m.fill_rgba == np.array((0.0, 1.0, 0.0, 0.5)))
def test_set_stroke_color(using_opengl_renderer):
m = OpenGLVMobject()
assert m.stroke_color.to_hex() == "#FFFFFF"
np.alltrue(m.stroke_rgba == np.array((0.0, 1.0, 0.0, 0.5)))
m.set_stroke(BLACK)
assert m.stroke_color.to_hex() == "#000000"
np.alltrue(m.stroke_rgba == np.array((1.0, 1.0, 1.0, 1.0)))
m.set_stroke(PURE_GREEN, opacity=0.5)
assert m.stroke_color.to_hex() == "#00FF00"
np.alltrue(m.stroke_rgba == np.array((0.0, 1.0, 0.0, 0.5)))
def test_set_fill(using_opengl_renderer):
m = OpenGLMobject()
assert m.color.to_hex() == "#FFFFFF"
m.set_color(BLACK)
assert m.color.to_hex() == "#000000"
m = OpenGLVMobject()
assert m.color.to_hex() == "#FFFFFF"
m.set_color(BLACK)
assert m.color.to_hex() == "#000000"
def test_set_color_handles_lists_of_strs(using_opengl_renderer):
m = OpenGLVMobject()
assert m.color.to_hex() == "#FFFFFF"
m.set_color([BLACK, BLUE, GREEN])
assert m.get_colors()[0] == BLACK
assert m.get_colors()[1] == BLUE
assert m.get_colors()[2] == GREEN
assert m.get_fill_colors()[0] == BLACK
assert m.get_fill_colors()[1] == BLUE
assert m.get_fill_colors()[2] == GREEN
assert m.get_stroke_colors()[0] == BLACK
assert m.get_stroke_colors()[1] == BLUE
assert m.get_stroke_colors()[2] == GREEN
def test_set_color_handles_lists_of_color_objects(using_opengl_renderer):
m = OpenGLVMobject()
assert m.color.to_hex() == "#FFFFFF"
m.set_color([PURE_BLUE, PURE_GREEN, PURE_RED])
assert m.get_colors()[0].to_hex() == "#0000FF"
assert m.get_colors()[1].to_hex() == "#00FF00"
assert m.get_colors()[2].to_hex() == "#FF0000"
assert m.get_fill_colors()[0].to_hex() == "#0000FF"
assert m.get_fill_colors()[1].to_hex() == "#00FF00"
assert m.get_fill_colors()[2].to_hex() == "#FF0000"
assert m.get_stroke_colors()[0].to_hex() == "#0000FF"
assert m.get_stroke_colors()[1].to_hex() == "#00FF00"
assert m.get_stroke_colors()[2].to_hex() == "#FF0000"
def test_set_fill_handles_lists_of_strs(using_opengl_renderer):
m = OpenGLVMobject()
assert m.fill_color.to_hex() == "#FFFFFF"
m.set_fill([BLACK.to_hex(), BLUE.to_hex(), GREEN.to_hex()])
assert m.get_fill_colors()[0].to_hex() == BLACK.to_hex()
assert m.get_fill_colors()[1].to_hex() == BLUE.to_hex()
assert m.get_fill_colors()[2].to_hex() == GREEN.to_hex()
def test_set_fill_handles_lists_of_color_objects(using_opengl_renderer):
m = OpenGLVMobject()
assert m.fill_color.to_hex() == "#FFFFFF"
m.set_fill([PURE_BLUE, PURE_GREEN, PURE_RED])
assert m.get_fill_colors()[0].to_hex() == "#0000FF"
assert m.get_fill_colors()[1].to_hex() == "#00FF00"
assert m.get_fill_colors()[2].to_hex() == "#FF0000"
def test_set_stroke_handles_lists_of_strs(using_opengl_renderer):
m = OpenGLVMobject()
assert m.stroke_color.to_hex() == "#FFFFFF"
m.set_stroke([BLACK.to_hex(), BLUE.to_hex(), GREEN.to_hex()])
assert m.get_stroke_colors()[0].to_hex() == BLACK.to_hex()
assert m.get_stroke_colors()[1].to_hex() == BLUE.to_hex()
assert m.get_stroke_colors()[2].to_hex() == GREEN.to_hex()
def test_set_stroke_handles_lists_of_color_objects(using_opengl_renderer):
m = OpenGLVMobject()
assert m.stroke_color.to_hex() == "#FFFFFF"
m.set_stroke([PURE_BLUE, PURE_GREEN, PURE_RED])
assert m.get_stroke_colors()[0].to_hex() == "#0000FF"
assert m.get_stroke_colors()[1].to_hex() == "#00FF00"
assert m.get_stroke_colors()[2].to_hex() == "#FF0000"
| [
"noreply@github.com"
] | torannn.noreply@github.com |
4aff6a1ff0913c30d0c6e961e1a3eb15b811179d | 9dbc57b8cfb23c1df0521e6f0c43830d0849ff6b | /pyrkup/core.py | 1aef18f9c49f46407d1114f7e7fbb4256e283d84 | [
"BSD-3-Clause"
] | permissive | kosqx/pyrkup | c722b752eb7fa9d02d58a57c5644ce3d0c7e13a2 | 2fe39809d987be04156c3667bd0595e74e8a1e1f | refs/heads/master | 2021-01-20T13:48:30.193502 | 2013-11-20T23:57:33 | 2013-11-20T23:57:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,361 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import with_statement, division, absolute_import, print_function
from pyrkup import five
class Node(object):
def __init__(self, kind, attr=None, data=None):
self.kind = kind
self.attr = attr
self.data = data
def __repr__(self):
return 'Node(kind=%r, attr=%r, data=%r)' % (
self.kind, self.attr, self.data
)
def __cmp__(self, other):
if not isinstance(other, Node):
raise TypeError
return cmp(self.to_tuple(), other.to_tuple())
def __eq__(self, other):
if not isinstance(other, Node):
raise TypeError
return self.to_tuple() == other.to_tuple()
def to_tuple(self):
return (self.kind, self.attr, self.data)
class NodeKind(object):
PARAGRAPH = 'para'
BLOCKQUOTE = 'blockquote'
HEADER = 'header'
RAW = 'raw'
HORIZONTAL_RULE = 'hr'
ORDERED_LIST = 'ol'
UNORDERED_LIST = 'ul'
LIST_ITEM = 'li'
DEFINITION_LIST = 'dl'
DEFINITION_TERM = 'dt'
DEFINITION_DESCRIPTION = 'dd'
TABLE = 'table'
TABLE_ROW = 'row'
TABLE_CELL = 'cell'
LINK = 'link'
IMAGE = 'image'
BOLD = 'bold'
ITALIC = 'italic'
MONOSPACE = 'mono'
SUBSCRIPT = 'sub'
SUPERSCRIPT = 'super'
UNDERLINE = 'under'
STRIKETHROUGH = 'strike'
NEWLINE = 'newline'
class Markup(object):
def auto_format(self, node):
if isinstance(node, five.string_types):
return five.force_unicode(node)
elif isinstance(node, list):
return u''.join(self.auto_format(i) for i in node)
elif isinstance(node, Node):
formatter = self.auto_format_table.get(node.kind)
if callable(formatter):
formatter = formatter(node)
if isinstance(formatter, tuple) and len(formatter) == 2:
return formatter[0] + self.auto_format(node.data) + formatter[1]
elif isinstance(formatter, five.string_types):
return five.force_unicode(formatter)
else:
raise ValueError('unsupported node kind: %r' % node.kind)
else:
raise TypeError('unsupported node type: %r' % type(node))
def format(self, data):
pass
def parse(self, text):
pass
| [
"krzysztof.kosyl@gmail.com"
] | krzysztof.kosyl@gmail.com |
50decef1a503b122a6f867eb1ff8092320ad0380 | fe67390f6cfcf26c75f821f40df5670dbb648ebf | /C++/gen_txt_file.py | 6ab7e9a94e320e20cf8131f7db668fcbdb56125c | [] | no_license | Sprinterzzj/model_deployment | a133dc5cbc35a016f7adf6d3e6399c5b271a090f | 4ca4e270787e6dccac37e53f18c67aa50c4946a0 | refs/heads/master | 2022-12-25T02:20:43.392058 | 2020-09-27T10:36:28 | 2020-09-27T10:36:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 196 | py | import numpy as np
f = np.load('../model/data/mnist.npz')
x_test, y_test = f['x_test'], f['y_test']
x_test = np.reshape(x_test, [-1, 784])
np.savetxt('test_file.txt',x_test[1:100],delimiter=',')
| [
"gdyshi@126.com"
] | gdyshi@126.com |
9ed5a2425042d0e129ebe8034ec9ba2124835648 | 8d2e57635806485140a5c64caadf257ef560d7a5 | /nmeta/policy.py | 316d4c12cccc7e9304263734263d1e1546143b61 | [
"Apache-2.0"
] | permissive | awesome-nfv/nmeta | 098a60376cf081e4dea65e12a4409f3757733ddb | 55cc27e81defc42775ff563bfbef31800e089b14 | refs/heads/master | 2020-04-04T14:31:53.735071 | 2017-10-28T21:46:24 | 2017-10-28T21:46:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 38,856 | py | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#*** nmeta - Network Metadata - Policy Interpretation Class and Methods
"""
This module is part of the nmeta suite running on top of Ryu SDN controller.
It provides a policy class as an interface to policy configuration and
classification of packets against policy.
See Policy class docstring for more information.
"""
import sys
import os
import datetime
#*** nmeta imports:
import tc_static
import tc_identity
import tc_custom
#*** Voluptuous to verify inputs against schema:
from voluptuous import Schema, Optional, Any, All, Required, Extra
from voluptuous import Invalid, MultipleInvalid, Range
#*** Import netaddr for MAC and IP address checking:
from netaddr import IPAddress
from netaddr import IPNetwork
from netaddr import EUI
#*** YAML for config and policy file parsing:
import yaml
#*** Regular Expressions:
import re
#*** For logging configuration:
from baseclass import BaseClass
#================== Functions (need to come first):
def validate(logger, data, schema, where):
"""
Generic validation of a data structure against schema
using Voluptuous data validation library
Parameters:
- logger: valid logger reference
- data: structure to validate
- schema: a valid Voluptuous schema
- where: string for debugging purposes to identity the policy location
"""
logger.debug("validating data=%s", data)
try:
#*** Check correctness of data against schema with Voluptuous:
schema(data)
except MultipleInvalid as exc:
#*** There was a problem with the data:
logger.critical("Voluptuous detected a problem where=%s, exception=%s",
where, exc)
sys.exit("Exiting nmeta. Please fix error in main_policy.yaml")
return 1
def validate_port_set_list(logger, port_set_list, policy):
"""
Validate that a list of dictionaries [{'port_set': str}]
reference valid port_sets. Return Boolean 1 if good otherwise
exit with exception
"""
for port_set_dict in port_set_list:
found = 0
for port_set in policy.port_sets.port_sets_list:
if port_set.name == port_set_dict['port_set']:
found = 1
if not found:
logger.critical("Undefined port_set=%s", port_set_dict['port_set'])
sys.exit("Exiting nmeta. Please fix error in main_policy.yaml")
return 1
def validate_location(logger, location, policy):
"""
Validator for location compliance (i.e. check that the supplied
location string exists as a location defined in policy)
Return Boolean True if good, otherwise exit with exception
"""
for policy_location in policy.locations.locations_list:
if policy_location.name == location:
return True
logger.critical("Undefined location=%s", location)
sys.exit("Exiting nmeta. Please fix error in main_policy.yaml")
def validate_type(type, value, msg):
"""
Used for Voluptuous schema validation.
Check a value is correct type, otherwise raise Invalid exception,
including elaborated version of msg
"""
try:
return type(value)
except ValueError:
msg = msg + ", value=" + value + ", expected type=" + type.__name__
raise Invalid(msg)
def transform_ports(ports):
"""
Passed a ports specification and return a list of
port numbers for easy searching.
Example:
Ports specification "1-3,5,66" becomes list [1,2,3,5,66]
"""
result = []
ports = str(ports)
for part in ports.split(','):
if '-' in part:
part_a, part_b = part.split('-')
part_a, part_b = int(part_a), int(part_b)
result.extend(range(part_a, part_b + 1))
else:
part_a = int(part)
result.append(part_a)
return result
def validate_ports(ports):
"""
Custom Voluptuous validator for a list of ports.
Example good ports specification:
1-3,5,66
Will raise Voluptuous Invalid exception if types or
ranges are not correct
"""
msg = 'Ports specification contains non-integer value'
msg2 = 'Ports specification contains invalid range'
#*** Cast to String:
ports = str(ports)
#*** Split into components separated by commas:
for part in ports.split(','):
#*** Handle ranges:
if '-' in part:
part_a, part_b = part.split('-')
#*** can they be cast to integer?:
validate_type(int, part_a, msg)
validate_type(int, part_b, msg)
#*** In a port range, part_b must be larger than part_a:
if not int(part_b) > int(part_a):
raise Invalid(msg2)
else:
#*** can it be cast to integer?:
validate_type(int, part, msg)
return ports
def validate_time_of_day(time_of_day):
"""
Custom Voluptuous validator for time of day compliance.
Returns original time of day if compliant, otherwise
raises Voluptuous Invalid exception
"""
msg1 = 'Invalid time of day start'
msg2 = 'Invalid time of day finish'
timeformat = "%H:%M"
(time_of_day1, time_of_day2) = time_of_day.split('-')
try:
validtime = datetime.datetime.strptime(time_of_day1, timeformat)
except:
raise Invalid(msg1)
try:
validtime = datetime.datetime.strptime(time_of_day2, timeformat)
except:
raise Invalid(msg2)
return time_of_day
def validate_macaddress(mac_addr):
"""
Custom Voluptuous validator for MAC address compliance.
Returns original MAC address if compliant, otherwise
raises Voluptuous Invalid exception
"""
msg = 'Invalid MAC address'
try:
result = EUI(mac_addr)
if result.version != 48:
raise Invalid(msg)
except:
raise Invalid(msg)
return mac_addr
def validate_macaddress_OLD(mac_addr):
"""
Custom Voluptuous validator for MAC address compliance.
Returns original MAC address if compliant, otherwise
raises Voluptuous Invalid exception
"""
msg = 'Invalid MAC address'
try:
if not re.match("[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$", mac_addr.lower()):
raise Invalid(msg)
except:
raise Invalid(msg)
return mac_addr
def validate_ip_space(ip_addr):
"""
Custom Voluptuous validator for IP address compliance.
Can be IPv4 or IPv6 and can be range or have CIDR mask.
Returns original IP address if compliant, otherwise
raises Voluptuous Invalid exception
"""
msg = 'Invalid IP address'
#*** Does it look like a CIDR network?:
if "/" in ip_addr:
try:
if not IPNetwork(ip_addr):
raise Invalid(msg)
except:
raise Invalid(msg)
return ip_addr
#*** Does it look like an IP range?:
elif "-" in ip_addr:
ip_range = ip_addr.split("-")
if len(ip_range) != 2:
raise Invalid(msg)
try:
if not (IPAddress(ip_range[0]) and IPAddress(ip_range[1])):
raise Invalid(msg)
except:
raise Invalid(msg)
#*** Check second value in range greater than first value:
if IPAddress(ip_range[0]).value >= IPAddress(ip_range[1]).value:
raise Invalid(msg)
#*** Check both IP addresses are the same version:
if IPAddress(ip_range[0]).version != \
IPAddress(ip_range[1]).version:
raise Invalid(msg)
return ip_addr
else:
#*** Or is it just a plain simple IP address?:
try:
if not IPAddress(ip_addr):
raise Invalid(msg)
except:
raise Invalid(msg)
return ip_addr
def validate_ethertype(ethertype):
"""
Custom Voluptuous validator for ethertype compliance.
Can be in hex (starting with 0x) or decimal.
Returns ethertype if compliant, otherwise
raises Voluptuous Invalid exception
"""
msg = 'Invalid EtherType'
if str(ethertype)[:2] == '0x':
#*** Looks like hex:
try:
if not (int(ethertype, 16) > 0 and \
int(ethertype, 16) < 65536):
raise Invalid(msg)
except:
raise Invalid(msg)
else:
#*** Perhaps it's decimal?
try:
if not (int(ethertype) > 0 and \
int(ethertype) < 65536):
raise Invalid(msg)
except:
raise Invalid(msg)
return ethertype
#================= Voluptuous Schema for Validating Policy
#*** Voluptuous schema for top level keys in the main policy:
TOP_LEVEL_SCHEMA = Schema({
Required('tc_rules'):
{Extra: object},
Required('qos_treatment'):
{Extra: object},
Required('port_sets'):
{Extra: object},
Required('locations'):
{Extra: object}
})
#*** Voluptuous schema for tc_rules branch of main policy:
TC_RULES_SCHEMA = Schema([{Extra: object}])
#*** Voluptuous schema for a tc_rule:
TC_RULE_SCHEMA = Schema({
Optional('comment'):
str,
Required('match_type'):
Required(Any('any', 'all', 'none')),
Required('conditions_list'):
[{Extra: object}],
Required('actions'):
{Extra: object}
})
#*** Voluptuous schema for a tc condition:
TC_CONDITION_SCHEMA = Schema({
Required('match_type'):
Required(Any('any', 'all', 'none')),
Required('classifiers_list'):
[{Extra: object}]
})
#*** Voluptuous schema for a tc classifier:
TC_CLASSIFIER_SCHEMA = Schema({
Optional('location_src'): str,
Optional('time_of_day'): validate_time_of_day,
Optional('eth_src'): validate_macaddress,
Optional('eth_dst'): validate_macaddress,
Optional('ip_src'): validate_ip_space,
Optional('ip_dst'): validate_ip_space,
Optional('tcp_src'): All(int, Range(min=0, max=65535)),
Optional('tcp_dst'): All(int, Range(min=0, max=65535)),
Optional('udp_src'): All(int, Range(min=0, max=65535)),
Optional('udp_dst'): All(int, Range(min=0, max=65535)),
Optional('eth_type'): validate_ethertype,
Optional('identity_lldp_systemname'): str,
Optional('identity_lldp_systemname_re'): str,
Optional('identity_dhcp_hostname'): str,
Optional('identity_dhcp_hostname_re'): str,
Optional('identity_service_dns'): str,
Optional('identity_service_dns_re'): str,
Optional('custom'): str
})
#*** Voluptuous schema for tc actions:
TC_ACTIONS_SCHEMA = Schema({
Optional('drop'): Any('at_controller',
'at_controller_and_switch'),
Optional('qos_treatment'): Any('default_priority',
'constrained_bw',
'high_priority',
'low_priority',
'classifier_return'),
Required('set_desc'): str
})
#*** Voluptuous schema for qos_treatment branch of main policy:
QOS_TREATMENT_SCHEMA = Schema({str: int})
#*** Voluptuous schema for port_sets branch of main policy:
PORT_SETS_SCHEMA = Schema({
Required('port_set_list'):
[{Extra: object}]
})
#*** Voluptuous schema for a port set node in main policy:
PORT_SET_SCHEMA = Schema({
Required('name'): str,
Required('port_list'):
[
{
'name': str,
'DPID': int,
'ports': validate_ports,
'vlan_id': int
}
]
})
#*** Voluptuous schema for locations branch of main policy:
LOCATIONS_SCHEMA = Schema({
Required('locations_list'):
[{Extra: object}],
Required('default_match'): str
})
#*** Voluptuous schema for a location node in main policy:
LOCATION_SCHEMA = Schema({
Required('name'): str,
Required('port_set_list'):
[{'port_set': str}],
})
#*** Default policy file location parameters:
POL_DIR_DEFAULT = "config"
POL_DIR_USER = "config/user"
POL_FILENAME = "main_policy.yaml"
class Policy(BaseClass):
"""
This policy class serves 4 main purposes:
- Ingest policy (main_policy.yaml) from file
- Validate correctness of policy against schema
- Classify packets against policy, passing through to static,
identity and custom classifiers, as required
- Other methods and functions to check various parameters
against policy
Note: Class definitions are not nested as not considered Pythonic
Main Methods and Variables:
- check_policy(flow, ident) # Check a packet against policy
- qos(qos_treatment) # Map qos_treatment string to queue number
- main_policy # main policy YAML object. Read-only,
no verbs. Use methods instead where
possible.
TC Methods and Variables:
- tc_rules.rules_list # List of TC rules
- tc_rules.custom_classifiers # dedup list of custom classifier names
"""
def __init__(self, config, pol_dir_default=POL_DIR_DEFAULT,
pol_dir_user=POL_DIR_USER,
pol_filename=POL_FILENAME):
""" Initialise the Policy Class """
#*** Required for BaseClass:
self.config = config
#*** Set up Logging with inherited base class method:
self.configure_logging(__name__, "policy_logging_level_s",
"policy_logging_level_c")
self.policy_dir_default = pol_dir_default
self.policy_dir_user = pol_dir_user
self.policy_filename = pol_filename
#*** Get working directory:
self.working_directory = os.path.dirname(__file__)
#*** Build the full path and filename for the user policy file:
self.fullpathname = os.path.join(self.working_directory,
self.policy_dir_user,
self.policy_filename)
if os.path.isfile(self.fullpathname):
self.logger.info("Opening user policy file=%s", self.fullpathname)
else:
self.logger.info("User policy file=%s not found",
self.fullpathname)
self.fullpathname = os.path.join(self.working_directory,
self.policy_dir_default,
self.policy_filename)
self.logger.info("Opening default policy file=%s",
self.fullpathname)
#*** Ingest the policy file:
try:
with open(self.fullpathname, 'r') as filename:
self.main_policy = yaml.safe_load(filename)
except (IOError, OSError) as exception:
self.logger.error("Failed to open policy "
"file=%s exception=%s",
self.fullpathname, exception)
sys.exit("Exiting nmeta. Please create policy file")
#*** Instantiate Classes:
self.static = tc_static.StaticInspect(config, self)
self.identity = tc_identity.IdentityInspect(config)
self.custom = tc_custom.CustomInspect(config)
#*** Check the correctness of the top level of main policy:
validate(self.logger, self.main_policy, TOP_LEVEL_SCHEMA, 'top')
#*** Instantiate classes for the second levels of policy:
self.port_sets = PortSets(self)
self.locations = Locations(self)
self.tc_rules = TCRules(self)
self.qos_treatment = QoSTreatment(self)
#*** Instantiate any custom classifiers:
self.custom.instantiate_classifiers(self.tc_rules.custom_classifiers)
def check_policy(self, flow, ident):
"""
Passed a flows object, set in context of current packet-in event,
and an identities object.
Check if packet matches against any policy
rules and if it does, update the classifications portion of
the flows object to reflect details of the classification.
"""
#*** Check against TC policy:
for tc_rule in self.tc_rules.rules_list:
#*** Check the rule:
tc_rule_result = tc_rule.check_tc_rule(flow, ident)
if tc_rule_result.match:
self.logger.debug("Matched policy rule=%s", tc_rule.__dict__)
#*** Only set 'classified' if continue_to_inspect not set:
if not tc_rule_result.continue_to_inspect:
flow.classification.classified = True
else:
flow.classification.classified = False
flow.classification.classification_tag = \
tc_rule_result.classification_tag
flow.classification.classification_time = \
datetime.datetime.now()
#*** Accumulate any actions:
flow.classification.actions.update(tc_rule_result.actions)
self.logger.debug("flow.classification.actions=%s",
flow.classification.actions)
return 1
#*** No matches. Mark as classified so we don't process again:
flow.classification.classified = True
return 0
def qos(self, qos_treatment):
"""
Passed a QoS treatment string and return the relevant
QoS queue number to use, otherwise 0. Works by lookup
on qos_treatment section of main_policy
"""
qos_policy = self.main_policy['qos_treatment']
if qos_treatment in qos_policy:
return qos_policy[qos_treatment]
elif qos_treatment == 'classifier_return':
#*** This happens:
self.logger.debug("custom classifier did not return "
"qos_treatment")
return 0
else:
self.logger.error("qos_treatment=%s not found in main_policy",
qos_treatment)
return 0
class TCRules(object):
"""
An object that represents the tc_rules root branch of
the main policy
"""
def __init__(self, policy):
""" Initialise the TCRules Class """
#*** Extract logger and policy YAML branch:
self.logger = policy.logger
#*** TBD: fix arbitrary single ruleset...
self.yaml = policy.main_policy['tc_rules']['tc_ruleset_1']
#*** List to be populated with names of any custom classifiers:
self.custom_classifiers = []
#*** Check the correctness of the tc_rules branch of main policy:
validate(self.logger, self.yaml, TC_RULES_SCHEMA, 'tc_rules')
#*** Read in rules:
self.rules_list = []
for idx, key in enumerate(self.yaml):
self.rules_list.append(TCRule(self, policy, idx))
class TCRule(object):
"""
An object that represents a single traffic classification
(TC) rule.
"""
def __init__(self, tc_rules, policy, idx):
"""
Initialise the TCRule Class
Passed a TCRules class instance, a Policy class instance
and an index integer for the index of the tc rule in policy
"""
#*** Extract logger and policy YAML:
self.logger = policy.logger
#*** TBD: fix arbitrary single ruleset...
self.yaml = policy.main_policy['tc_rules']['tc_ruleset_1'][idx]
#*** Check the correctness of the tc rule, including actions:
validate(self.logger, self.yaml, TC_RULE_SCHEMA, 'tc_rule')
validate(self.logger, self.yaml['actions'], TC_ACTIONS_SCHEMA,
'tc_rule_actions')
self.match_type = self.yaml['match_type']
self.actions = self.yaml['actions']
#*** Read in conditions_list:
self.conditions_list = []
for condition in self.yaml['conditions_list']:
self.conditions_list.append(TCCondition(tc_rules,
policy, condition))
def check_tc_rule(self, flow, ident):
"""
Passed Packet and Identity class objects.
Check to see if packet matches conditions as per the
TC rule. Return a TCRuleResult object
"""
#*** Instantiate object to hold results for checks:
result = TCRuleResult(self.actions)
#*** Iterate through the conditions list:
for condition in self.conditions_list:
condition_result = condition.check_tc_condition(flow, ident)
self.logger.debug("condition=%s result=%s", condition.__dict__,
condition_result.__dict__)
#*** Decide what to do based on match result and type:
if condition_result.match and self.match_type == "any":
result.match = True
result.add_rule_actions()
result.accumulate(condition_result)
self.logger.debug("matched_1, result=%s", result.__dict__)
return result
elif not result.match and self.match_type == "all":
result.match = False
self.logger.debug("no_match_1, result=%s", result.__dict__)
return result
elif result.match and self.match_type == "all":
#*** Just accumulate the results:
result.accumulate(condition_result)
elif result.match and self.match_type == "none":
result.match = False
self.logger.debug("no_match_2, result=%s", result.__dict__)
return result
else:
#*** Not a condition we take action on so keep going:
pass
#*** We've finished loop through all conditions and haven't
#*** returned. Work out what action to take:
if not condition_result.match and self.match_type == "any":
result.match = False
self.logger.debug("no_match_3, result=%s", result.__dict__)
return result
elif condition_result.match and self.match_type == "all":
result.match = True
result.add_rule_actions()
result.accumulate(condition_result)
self.logger.debug("matched_2, result=%s", result.__dict__)
return result
elif not condition_result.match and self.match_type == "none":
result.match = True
result.add_rule_actions()
self.logger.debug("matched_3, result=%s", result.__dict__)
return result
else:
#*** Unexpected result:
self.logger.error("Unexpected result at "
"end of loop through rule=%s", self.yaml)
result.match = False
return result
class TCRuleResult(object):
"""
An object that represents a traffic classification
result, including any decision collateral
on matches and actions.
Use __dict__ to dump to data to dictionary
"""
def __init__(self, rule_actions):
""" Initialise the TCRuleResult Class """
self.match = 0
self.continue_to_inspect = 0
self.classification_tag = ""
self.actions = {}
#*** Actions defined in policy for this rule:
self.rule_actions = rule_actions
def accumulate(self, condition_result):
"""
Passed a TCConditionResult object and
accumulate values into our object
"""
if condition_result.match:
self.match = True
if condition_result.continue_to_inspect:
self.continue_to_inspect = True
if self.rule_actions['set_desc'] == 'classifier_return':
self.classification_tag = condition_result.classification_tag
else:
self.classification_tag = self.rule_actions['set_desc']
self.actions.update(condition_result.actions)
def add_rule_actions(self):
"""
Add rule actions from policy to the actions of this class
"""
self.actions.update(self.rule_actions)
class TCCondition(object):
"""
An object that represents a single traffic classification
(TC) rule condition from a conditions list
(contains a match type and a list of one or more classifiers)
"""
def __init__(self, tc_rules, policy, policy_snippet):
"""
Initialise the TCCondition Class
Passed a TCRules class instance, a Policy class instance
and a snippet of tc policy for a condition
"""
self.policy = policy
self.logger = policy.logger
self.yaml = policy_snippet
self.classifiers = []
#*** Check the correctness of the tc condition:
validate(self.logger, self.yaml, TC_CONDITION_SCHEMA,
'tc_rule_condition')
for classifier in self.yaml['classifiers_list']:
#*** Validate classifier:
validate(self.logger, classifier, TC_CLASSIFIER_SCHEMA,
'tc_classifier')
#*** Extra validation for location_src:
policy_attr = next(iter(classifier))
policy_value = classifier[policy_attr]
if policy_attr == 'location_src':
validate_location(self.logger, policy_value, policy)
self.classifiers.append(classifier)
#*** Accumulate deduplicated custom classifier names:
if 'custom' in classifier:
custlist = tc_rules.custom_classifiers
if classifier['custom'] not in custlist:
custlist.append(classifier['custom'])
self.match_type = self.yaml['match_type']
def check_tc_condition(self, flow, ident):
"""
Passed a Flow and Identity class objects. Check to see if
flow.packet matches condition (a set of classifiers)
as per the match type.
Return a TCConditionResult object with match information.
"""
pkt = flow.packet
result = TCConditionResult()
self.logger.debug("self.classifiers=%s", self.classifiers)
#*** Iterate through classifiers (example: tcp_src: 123):
for classifier in self.classifiers:
policy_attr = next(iter(classifier))
policy_value = classifier[policy_attr]
#*** Instantiate data structure for classifier result:
classifier_result = TCClassifierResult(policy_attr, policy_value)
self.logger.debug("Iterating classifiers, policy_attr=%s "
"policy_value=%s, policy_attr_type=%s", policy_attr,
policy_value, classifier_result.policy_attr_type)
#*** Main check on classifier attribute type:
if classifier_result.policy_attr_type == "identity":
self.policy.identity.check_identity(classifier_result, pkt,
ident)
elif policy_attr == "custom":
self.policy.custom.check_custom(classifier_result, flow, ident)
self.logger.debug("custom match condition=%s",
classifier_result.__dict__)
else:
#*** default to static classifier:
self.policy.static.check_static(classifier_result, pkt)
self.logger.debug("static match=%s",
classifier_result.__dict__)
#*** Decide what to do based on match result and type:
if classifier_result.match and self.match_type == "any":
result.accumulate(classifier_result)
return result
elif not classifier_result.match and self.match_type == "all":
result.match = False
return result
elif classifier_result.match and self.match_type == "none":
result.match = False
return result
else:
#*** Not a condition we take action on, keep going:
pass
#*** Finished loop through all conditions without return.
#*** Work out what action to take:
if not classifier_result.match and self.match_type == "any":
result.match = False
return result
elif classifier_result.match and self.match_type == "all":
result.accumulate(classifier_result)
return result
elif not classifier_result.match and self.match_type == "none":
result.match = True
return result
else:
#*** Unexpected result:
self.logger.error("Unexpected result at end of loop"
"classifier_result=%s",
classifier_result.__dict__)
result.match = False
return result
class TCConditionResult(object):
"""
An object that represents a traffic classification condition
result. Custom classifiers can return additional parameters
beyond a Boolean match, so cater for these too.
Use __dict__ to dump to data to dictionary
"""
def __init__(self):
""" Initialise the TCConditionResult Class """
self.match = False
self.continue_to_inspect = False
self.classification_tag = ""
self.actions = {}
def accumulate(self, classifier_result):
"""
Passed a TCClassifierResult object and
accumulate values into our object
"""
if classifier_result.match:
self.match = True
if classifier_result.continue_to_inspect:
self.continue_to_inspect = True
self.actions.update(classifier_result.actions)
self.classification_tag += classifier_result.classification_tag
class TCClassifierResult(object):
"""
An object that represents a traffic classification classifier
result. Custom classifiers can return additional parameters
beyond a Boolean match, so cater for these too.
Use __dict__ to dump to data to dictionary
"""
def __init__(self, policy_attr, policy_value):
""" Initialise the TCClassifierResult Class """
self.match = False
self.continue_to_inspect = 0
self.policy_attr = policy_attr
#*** Policy Attribute Type is for identity classifiers
self.policy_attr_type = policy_attr.split("_")[0]
self.policy_value = policy_value
self.classification_tag = ""
self.actions = {}
class QoSTreatment(object):
"""
An object that represents the qos_treatment root branch of
the main policy
"""
def __init__(self, policy):
""" Initialise the QoSTreatment Class """
#*** Extract logger and policy YAML branch:
self.logger = policy.logger
self.yaml = policy.main_policy['qos_treatment']
#*** Check the correctness of the qos_treatment branch of main policy:
validate(self.logger, self.yaml, QOS_TREATMENT_SCHEMA, 'qos_treatment')
class PortSets(object):
"""
An object that represents the port_sets root branch of
the main policy
"""
def __init__(self, policy):
""" Initialise the PortSets Class """
#*** Extract logger and policy YAML branch:
self.logger = policy.logger
self.yaml = policy.main_policy['port_sets']
#*** Check the correctness of the port_sets branch of main policy:
validate(self.logger, self.yaml, PORT_SETS_SCHEMA, 'port_sets')
#*** Read in port_sets:
self.port_sets_list = []
for idx, key in enumerate(self.yaml['port_set_list']):
self.port_sets_list.append(PortSet(policy, idx))
def get_port_set(self, dpid, port, vlan_id=0):
"""
Check if supplied dpid/port/vlan_id is member of
a port set and if so, return the port_set name. If no
match return empty string.
"""
for idx in self.port_sets_list:
if idx.is_member(dpid, port, vlan_id):
return idx.name
return ""
class PortSet(object):
"""
An object that represents a single port set
"""
def __init__(self, policy, idx):
""" Initialise the PortSet Class """
#*** Extract logger and policy YAML:
self.logger = policy.logger
self.yaml = \
policy.main_policy['port_sets']['port_set_list'][idx]
self.name = self.yaml['name']
#*** Check the correctness of the location policy:
validate(self.logger, self.yaml, PORT_SET_SCHEMA, 'port_set')
#*** Build searchable lists of ports
#*** (ranges turned into multiple single values):
port_list = self.yaml['port_list']
for ports in port_list:
ports['ports_xform'] = transform_ports(ports['ports'])
def is_member(self, dpid, port, vlan_id=0):
"""
Check to see supplied dpid/port/vlan_id is member of
this port set. Returns a Boolean
"""
#*** Validate dpid is an integer (and coerce if required):
msg = 'dpid must be integer'
dpid = validate_type(int, dpid, msg)
#*** Validate port is an integer (and coerce if required):
msg = 'Port must be integer'
port = validate_type(int, port, msg)
#*** Validate vlan_id is an integer (and coerce if required):
msg = 'vlan_id must be integer'
vlan_id = validate_type(int, vlan_id, msg)
#*** Iterate through port list looking for a match:
port_list = self.yaml['port_list']
for ports in port_list:
if not ports['DPID'] == dpid:
self.logger.debug("did not match dpid")
continue
if not ports['vlan_id'] == vlan_id:
self.logger.debug("did not match vlan_id")
continue
if port in ports['ports_xform']:
return True
self.logger.debug("no match, returning False")
return False
class Locations(object):
"""
An object that represents the locations root branch of
the main policy
"""
def __init__(self, policy):
""" Initialise the Locations Class """
#*** Extract logger and policy YAML branch:
self.logger = policy.logger
self.yaml = policy.main_policy['locations']
#*** Check the correctness of the locations branch of main policy:
validate(self.logger, self.yaml, LOCATIONS_SCHEMA, 'locations')
#*** Read in locations etc:
self.locations_list = []
for idx, key in enumerate(self.yaml['locations_list']):
self.locations_list.append(Location(policy, idx))
#*** Default location to use if no match:
self.default_match = self.yaml['default_match']
def get_location(self, dpid, port):
"""
Passed a DPID and port and return a logical location
name, as per policy configuration.
"""
result = ""
for location in self.locations_list:
result = location.check(dpid, port)
if result:
return result
return self.default_match
class Location(object):
"""
An object that represents a single location
"""
def __init__(self, policy, idx):
""" Initialise the Location Class """
#*** Extract logger and policy YAML:
self.logger = policy.logger
self.policy = policy
self.yaml = \
policy.main_policy['locations']['locations_list'][idx]
#*** Check the correctness of the location policy:
validate(self.logger, self.yaml, LOCATION_SCHEMA, 'location')
#*** Check that port sets exist:
validate_port_set_list(self.logger, self.yaml['port_set_list'],
policy)
#*** Store data from YAML into this class:
self.name = self.yaml['name']
self.port_set_list = self.yaml['port_set_list']
def check(self, dpid, port):
"""
Check a dpid/port to see if it is part of this location
and if so return the string name of the location otherwise
return empty string
"""
port_set_membership = \
self.policy.port_sets.get_port_set(dpid, port)
for port_set in self.port_set_list:
if port_set['port_set'] == port_set_membership:
return self.name
return ""
| [
"matthew_john_hayes@hotmail.com"
] | matthew_john_hayes@hotmail.com |
7aea7ba30cf485a4760e2c849d353c42f8bdddbd | 2985ebf7d5deee28b55059bcc11c1e2c99039585 | /MovieHtmlParser.py | 96d8ded493f136a0c9fc5d4ccefe2436178e0ae8 | [] | no_license | laixintao/Tree | fdfa1b4faedc00cbc947cea29aa7ffdb376620dd | 068240a69e7f5b0f7475f73bc6b4064d1c81d97c | refs/heads/master | 2021-01-10T08:03:28.781373 | 2015-10-23T10:56:00 | 2015-10-23T10:56:00 | 44,246,486 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,396 | py | #!/user/bin/env python
#_*_ coding: utf-8 _*_
__author__="laixintao"
import urllib2
import re
import time
from moviedb import Movie,DBSession
from HTMLParser import HTMLParser
from log import log
from config import PINTURE_PATH
# set the system encoding
import sys
default_encoding = 'utf-8'
if sys.getdefaultencoding() != default_encoding:
reload(sys)
sys.setdefaultencoding(default_encoding)
class MovieHtmlParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.ispost = False
# self.movies = []
self.isp = False
self.istitle = False
# self.num_movie = 0
# self.have_pic = False
self.pic = ""
self.hasurl = False
self.url = ""
self.title = ""
self.ch_sent=""
self.en_sent=""
self.movie=""
self.pic_local = ""
self.line = 0
self.next_page_url = ""
def get_next_page_url(self):
return self.next_page_url
def clear_next_page_url(self):
self.next_page_url = None
def show_data(self):
print "title:",self.title
print "url:",self.url
print "movie:",self.movie
print "pic:",self.pic
print "ch:",self.ch_sent
print "en:",self.en_sent
print("-"*20)
def handle_data(self, data):
if self.isp:
# print self.line,data
if len(data)>4:
if self.line==0:
self.ch_sent = data
# self.line += 1
elif self.line == 1:
self.en_sent = data
elif self.line == 2:
self.movie = data
else :pass
self.line += 1
else:
# print "*"*20,data
pass
if self.istitle:
self.title = data
else:
pass
def handle_starttag(self, tag, attrs):
if tag == "h1" and attrs[0][1]=="entry-title":
self.ispost = True
self.istitle = True
if tag == "p":
self.isp = True
if tag == "img":
if self.isp:
self.pic=attrs[1][1]
self.have_pic = True
if tag == "a" and self.istitle:
self.url = attrs[0][1]
self.hasurl = True
self.id = re.findall(r"[\d]{1,5}",self.url)[0]
def handle_endtag(self, tag):
if tag == "p":
self.isp = False
# self.have_pic = False
if tag == "article":
# self.show_data()
self.add_to_db()
self.line = 0;
self.ispost = False
if tag == "h1":
self.istitle = False
def add_to_db(self):
try:
s = DBSession()
old = s.query(Movie).filter(Movie.url==self.url).first()
if old == None:
# if True:
try:
suffix = re.findall(r"\.[a-z]{3,4}$",self.pic)[0]
pic_name = PINTURE_PATH + str(self.id) + suffix
self.pic_local = pic_name
except Exception,e:
log("[ERR]error in download pic..."+str(e))
year = False
if len(re.findall(r"[\d]{4}$",self.movie)) >= 1:
year = True
print self.movie
m = Movie(
id = self.id,
post_title=self.title,
sent_ch=self.ch_sent,
sent_en=self.en_sent,
pic_url=self.pic,
pic_localname=self.pic_local,
url=self.url,
movie=self.movie,
couldPublish = year
)
s.add(m)
s.commit()
log_info = "[O K]add "+str(self.url)+" to DB successfully..."
log(log_info)
else:
log("[O K]"+str(self.url)+" has already exist...")
s.close()
except Exception,e:
log("[ERR]error when add to db..."+str(e))
def handle_charref(self,name):
try:
charnum=int(name)
except ValueError:
return
if charnum<1 or charnum>255:
return
self.handle_data(chr(charnum))
if __name__ == "__main__":
pass | [
"laixintao1995@163.com"
] | laixintao1995@163.com |
3d84e500c8726db6e95fbb74d398b3624ef0cee4 | 4683079af4abcf271ad2b2f15a1f5052b22b3576 | /music_site/asgi.py | 84a4f8eb48ed8681e5a61961969c1bc5cbe6285d | [] | no_license | AbdullahNoori/music_site | 21fb3a9d547d026393798b8af8d3be4a9fefa416 | 6f16f9c9bb40aabdfdae6e433f918002864210b4 | refs/heads/master | 2022-07-15T15:53:13.178544 | 2020-05-13T07:53:54 | 2020-05-13T07:53:54 | 257,746,874 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 392 | py | """
ASGI config for Music_Site project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Music.settings')
application = get_asgi_application()
| [
"nooriabdullah86@gmail.com"
] | nooriabdullah86@gmail.com |
5eef6e496f145d55f9cb241cc893414fbc9dbca8 | d99d372f4c80748319c72f662eae9b8fda991142 | /KivyDemos-master/box_layout_demo.py | 064750fda0cb01321f8229e263681a1361eab491 | [] | no_license | MaxDunsmore/Prac06 | 7037dbad0d10fd3132ca5b7dbf130907da75ca2e | 1964c791f8aab06610a4329967c45d2238b6f627 | refs/heads/master | 2021-01-19T08:59:11.048360 | 2017-04-09T11:48:51 | 2017-04-09T11:48:51 | 87,704,622 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 350 | py | from kivy.app import App
from kivy.lang import Builder
class BoxLayoutDemo(App):
def build(self):
self.title = "Box Layout Demo"
self.root = Builder.load_file('box_layout.kv')
return self.root
def handle_greet(self):
print("greet")
self.root.ids.output_label.text = "Hello "
BoxLayoutDemo().run()
| [
"max.dunsmore@my.jcu.edu.au"
] | max.dunsmore@my.jcu.edu.au |
17ad669a0e46d848942f3120af2a64aa5b935caf | 0a799ff8dbdb7791b41bca079ec09d8b42c65d59 | /api_basic/serializers.py | ce375618e2206997becb58e265a57357e9a3a427 | [] | no_license | moshowsJournal/royalty_django_api | b1cffb3c619c586b48b0385f1bd8ea9ee1ad35f2 | 99530f1739260c66b8d01fee908678f46f26f551 | refs/heads/master | 2022-06-21T03:50:55.515663 | 2020-05-12T07:41:23 | 2020-05-12T07:41:23 | 263,267,119 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 914 | py | from rest_framework import serializers
from .models import Article
class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = User
#fields = ['id','title','author','email']
fields = '__all__'
# title = serializers.CharField(max_length=100)
# author = serializers.CharField(max_length=100)
# email = serializers.EmailField(max_length=100)
# date = serializers.DateTimeField()
# def create(self, validated_data):
# return Article.objects.create(validated_data)
# def update(self,instance,validated_data):
# instance.title = validated_data.get('title',instance.title)
# instance.title = validated_data.get('author',instance.author)
# instance.title = validated_data.get('email',instance.email)
# instance.title = validated_data.get('date',instance.date)
# instance.save()
# return instance | [
"withyouamalive@gmail.com"
] | withyouamalive@gmail.com |
e8903d4f4699625df2cda18ac35f4222d2fd4b28 | 59f8bf58860d021216449b135f486f9b7145f6be | /application/utils/helper.py | b0f149aafc09f1948981c1ab3c93845eb97d3ddc | [] | no_license | JFluo2011/fisher | f5b58e2e151022b2173490b504dda7c704862b19 | d899e2a3dc296cf9d1c2802067d995dde1c3d32e | refs/heads/master | 2022-12-10T12:42:36.376854 | 2018-12-27T07:57:00 | 2018-12-27T07:57:00 | 158,154,663 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 126 | py | def keyword_is_isbn(keyword):
tmp = keyword.strip().replace('-', '')
return (len(tmp) in [10, 13]) and tmp.isdigit()
| [
"luojianfeng2011@163.com"
] | luojianfeng2011@163.com |
04d67e88f991f93432f88d8af074b1294411c372 | 8b49b9ef894b9513aa0c10af60a69c0fc5c30d5a | /evaluate_kb/evaluate.py | fcf217157d89a6facb387aca56c925768e9bf41f | [] | no_license | DulanjanaYasara/Internship-Project | d2742c488480962c3654bc2747102b52715e5e9f | ce03935017e08b33595fb9af668022f0cbf2a2a8 | refs/heads/master | 2021-08-23T23:50:20.368692 | 2017-12-07T04:33:40 | 2017-12-07T04:33:40 | 113,403,289 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,466 | py | import re
from locale import str
from pprint import pprint
from time import sleep
import requests
from spreadsheet import SpreadsheetConnector
from stackoverflow import extract
path_kb = 'http://203.94.95.153/content'
path_client_json = './path/to/client.json'
spreadsheet_name = "Stackoverflow"
# Threshold value for the answer
thres_ans = 25
# Stack-overflow tag set that is searched under WSO2
tags = ['wso2', # WSO2
'wso2-am', # API Manager
'wso2as', # Application Server
'wso2bam', # Business Activity Monitor
'wso2bps', # Business Process Server
'wso2brs', # Business Rules Server
'wso2carbon', # WSO2 Carbon
'wso2cep', # Complex Event Processor
'wso2-das', # Data Analytics Server
'wso2dss', # Data Services Server
'wso2elb', # Elastic Load Balancer
'wso2esb', # Enterprise Service Bus
'wso2es', # Enterprise Store
'wso2greg', # Governance Registry
'wso2is', # Identity Server
'wso2ml', # Machine Learner
'wso2mb', # Message Broker
'wso2ss', # Storage Server
'wso2ues', # User Engagement Server
'wso2developerstudio', # WSO2 Developer Studio
'wso2-emm', # Enterprise Mobility Manager
'wso2ppaas', # WSO2 Private PaaS
'wso2stratos', # Private Cloud
'wso2cloud', # WSO2 Cloud
'wso2msf4j'] # WSO2 Micro-services Framework for Java
def ask_kb(question):
"""Asking questions from the kb"""
params = (
('question', question),
)
# Sending the request to the kb
response = requests.get(path_kb, params=params)
output = response.json()
# If no answer given by the kb
if not output['answers']:
return '',0
else:
first_answer = output['answers'][0]
# Returning the first answer and it's score
return first_answer['answer'], first_answer['score']
def sentence_phrases_separation(text):
"""Used for part of sentence extraction based on punctuation delimiters.
An additional space is added in between period and capital letter"""
sentence_phrases = []
for sent in re.split(r'[.,!:;?*\-()\n]+\s+|\s+[.,!:;?*\-()\n]+|(->)', re.sub(r'(\.)([A-Z])', r'\1 \2', text)):
if sent:
sentence_phrases.append(sent)
return sentence_phrases
def main():
"""This is the main class"""
connector = SpreadsheetConnector(path_client_json)
# Obtaining the searching criteria
search_criteria1 = ' or '.join(['[' + x + ']' for x in tags])
# search_criteria2 = ' or '.join(['['+x+']' for x in tags[len(tags)/2:]])
row = 2
page_number = 1
tot_qs = []
while True:
try:
sheet_export_data = []
question_no = 0
# Finding the questions with the tags through the Stack Exchange API with the use of access tokens and keys
# N.B. Only the questions with the accepted answer are considered
responseQuestion = requests.get(
"https://api.stackexchange.com/2.2/search/advanced?page=" + str(page_number) +
"&pagesize=100&order=desc&sort=activity&q=" + search_criteria1 + "&accepted=True&site=stackoverflow&filter="
"!*e9ibzERTZv_4jPLGyBUXbiO0TCnjFLALrHd"
"*&access_token=3*MQ0YtINm2*xpbWplNVKw"
"))&key=b500RPkbAnAO3TH6oRQVew((")
print 'Page no.', page_number
page_number += 1
data_question = responseQuestion.json()
# Generating the accepted answer for the given question
for value in data_question['items']:
# Extracting the question
question = extract(value['body'])
question_intent = extract(value['title'])
for answer in value['answers']:
if answer['is_accepted']:
# Extracting the answer
answer = extract(answer['body'])
while True:
try:
response, score = ask_kb(question_intent)
# If the answer is below the threshold value
if score < thres_ans:
# Asking the question phrases from the kb
for phrase in sentence_phrases_separation(question_intent):
phrase_response, phrase_score = ask_kb(phrase)
if phrase_score > thres_ans:
break
else:
# Else the question is unanswered by the kb
print question_intent
sheet_export_data += [question_intent] + [question] + [answer]
question_no += 1
break
except requests.ConnectionError:
print '!',
sleep(2)
except KeyError:
print '#', question_intent,
bot_answer, answered = None, False
break
break
# Exporting the whole set of unanswered questions to the spreadsheet on a page basis
cell_range = 'A' + str(row) + ':C' + str(row + question_no -1)
connector.export_cell_range(spreadsheet_name, sheet_export_data, cell_range=cell_range, sheet_no=1)
row += question_no
print ''
print 'Total no. of unanswered questions within page :', question_no
tot_qs.append(question_no)
if not data_question['has_more']:
break
except KeyError:
print 'X'
# print data_question
except requests.ConnectionError:
print '!',
sleep(1)
print 'Total no. of question intents unanswered :', sum(tot_qs)
def test():
main()
if __name__ == '__main__':
test()
| [
"dulanjanayasara1@gmail.com"
] | dulanjanayasara1@gmail.com |
7aaa18f3d770e6cfc0a9ff020df2ebf34bb6a471 | 4cd2c9803766f250b7ef9313ffdbf85959d7b295 | /manage.py | 90f9cb894699cb2c9e8cf3c10822ec3a66812dd9 | [] | no_license | lubeda/PixelIt-AddOn | 5d80b8b91ec590ad11dbcd7dbe0fc98cf3a4c9f0 | f973d78a2f67e21d7156ae238aa801e2f242f0fd | refs/heads/master | 2020-12-14T23:51:16.348980 | 2020-01-25T16:49:31 | 2020-01-25T16:49:31 | 234,916,836 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 625 | py | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'PixOn.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
| [
"lb@sell-e.de"
] | lb@sell-e.de |
58c58c2aa06311710749227f4e0405344d093517 | 663d429e1f552ef958d37cfe4a0707354b544a9a | /rimi_linux_mysql/tcp_ip_socket/my_async/asyncsocket_chat/client1.py | 4a9a11ecfbb9b7904ff495bf8814706de43aa992 | [] | no_license | nie000/mylinuxlearn | 72a33024648fc4393442511c85d7c439e169a960 | 813ed75a0018446cd661001e8803f50880d09fff | refs/heads/main | 2023-06-20T07:46:11.842538 | 2021-07-15T13:46:43 | 2021-07-15T13:46:43 | 307,377,665 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 413 | py | import socket
ss_address = ("0.0.0.0",19528)
ss = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print('123')
ss.connect(ss_address)
print('456')
while True:
data = input('请输入消息:')
if not data:
break
try:
ss.send(data.encode('utf8'))
print(ss.recv(1024).decode('utf8'))
except BrokenPipeError:
print('连接已经关闭')
break
ss.close()
| [
"1073438012@qq.com"
] | 1073438012@qq.com |
97fe7ee81d9840e8c7664b609d833a3fa2b31645 | 26c25a7e45390a93a5e97d4d7d1b70ba8bab68ef | /Week 02 Leet Code/Delete Node in a Linked List.py | 2d92995592425e2f461bfd2605b605e3106e4690 | [] | no_license | akashcodepal/Summer-Internship-Plan-SIP | aa89c3f630e7485b576b1f3bc42dfa639109eafd | c1af7096986ce62be2e1c03b5fb1f0e5c5d5be7c | refs/heads/main | 2023-06-25T16:58:50.826957 | 2021-07-12T04:03:36 | 2021-07-12T04:03:36 | 380,293,889 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 572 | py | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteNode(self, node):
# we need 2 pointers to delete 1 node , but for this case we don't have prev
# so we will delete next node inplce of this node and copy its value and pass it in this node
nodeValue = node.next.val # 1
node.val = nodeValue # replace 5 with 1
node.next = node.next.next # delete node with origianl value 1
| [
"noreply@github.com"
] | akashcodepal.noreply@github.com |
c7fee91cb539c4e1e261ffa6c3de60b555291813 | 05bf7de1337bc938578accba64416863cec1ed63 | /docs/historical/MSD/MSDTutorial/Post_Processing/common/post_processing_class.py | 493bc56ae42de7f8b5544648a723bab83e78ce4c | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-other-permissive"
] | permissive | metamorph-inc/openmeta-mms | d0dccae88e7532594f02c5eff8daa74c6c0e4010 | 2644cb7273916e36c3725785fc9a44948d64c343 | refs/heads/master | 2023-04-06T11:09:36.316306 | 2023-03-28T18:17:55 | 2023-03-28T18:17:55 | 70,078,378 | 21 | 8 | NOASSERTION | 2023-01-14T09:31:14 | 2016-10-05T16:29:54 | Python | UTF-8 | Python | false | false | 24,179 | py | import os
import json
import sys
import re
import numpy as np
from py_modelica.mat_file_functions.mat_file_to_dict import MatFile2Dict
# Rescue if the limit-checking should get stuck in an infinite while-loop.
# Which should be impossible to start with, but if I am wrong...
MAX_ITERATIONS = 100000
class PostProcess:
filter = [] # list of all variables/parameter to load from mat-file
# (does not need to include 'time' - loaded by default)
time = None
result = None
def __init__(self, mat_file='', filter=None):
"""
Loads in mat-file, extracts given variables in filter (time always included)
and converts lists of values into numpy arrays.
These are stored in result as:
{{name1: array([values1])}, ..., {nameN: array([valuesN])}}
"""
mat_converter = MatFile2Dict(mat_file, filter, False)
result_lists = mat_converter.get_results()
# convert lists into numpy arrays
self.result = {}
for item in result_lists.iteritems():
self.result.update({item[0]: np.array(item[1])})
self.time = self.result['time']
def data_array(self, name):
"""
Get time-series in numpy array format.
name - name of variable
e.g. data_array('time')
returns with the time.
"""
try:
A = self.result[name]
return A
except KeyError:
print 'ERROR: cannot find [' + name + '] in Modelica results'
return []
def print_data(self, name):
"""
Prints the time-series.
name - name of variable
e.g. data_array('time')
returns with the time.
"""
data = self.data_array(name)
print 'name of data: '
print name
print 'here is the data: (with index)'
print '[',
for i in xrange(data.size - 1):
print str(i) + ':', str(data[i]) + ',',
print str(i + 1) + ':', str(data[i + 1]) + ']'
return data
def time_array(self):
"""
Get time-series of time in numpy array format.
"""
return self.time
def print_time(self):
"""
Prints and returns with time-series of time.
"""
time = self.time
print 'here are time intervals:', time
return time
def short_array(self, name, start=0, end=-1):
"""
Get a truncated, from n1 to n2 array for variable name
name - name of variable
start - start index of interval
end - end index of interval
N.B index goes from 0 to len(array)-1
"""
return self.result[name][start:end]
def plot(self, name):
"""
Returns a tuple, suitable for plotting, of the variable's time-series together with time.
name - name of variable
"""
return self.data_array(name), self.time
def get_data_by_time(self, name, time_val):
"""
Get data based on time value.
name - name of variable to consider
time_val - time point where to extract the value
Returns the data and the index of the data
"""
i = 0
time = self.time
while time[i] < time_val and i in xrange(time.size - 1):
i += 1
data_arr = self.data_array(name)
if time[i - 1] != time_val:
cur = data_arr[i - 1]
next = data_arr[i]
data = time[i - 1] / ((time[i - 1] + time[i]) / 2) * (next - cur) + cur
else:
data = data_arr[i - 1]
return data, i
def get_data_by_index(self, name, index):
return self.data_array(name)[index]
def get_index_from_time(self, time_val):
"""
Get index based on time value.
time_val - time point where to extract the value
Returns index nearest to time_val
"""
i = 0
time = self.time
while time[i] < time_val and i in xrange(time.size-1):
i += 1
return i
def get_time(self, name, value, atol=1e-4, rtol=1e-4, start_index=0, end_index=-1):
"""
Gets the first time point where the variable satisfies either atol or rtol,
if no such point exists - returns with -1.
name - name of variable
atol - absolute tolerance
rtol - relative tolerance
"""
index = -1
# N.B. this is only one of many ways to do this
denominator = 1
if value > rtol:
denominator = value
data = self.data_array(name)[start_index:end_index]
cnt = 0
for x in data:
abs_diff = abs(x - value)
rel_diff = abs_diff / denominator
if abs_diff < atol or rel_diff < rtol:
index = cnt
break
else:
cnt += 1
if index >= 0:
return self.time[start_index + index]
return -1
def last_value(self, name):
"""
Get last value of variable
name - name of variable
"""
return self.data_array(name)[-1]
def global_max(self, name):
"""
Get maximum value of variable
name - name of variable
"""
return self.data_array(name).max()
def global_max_time(self, name):
"""
Get time where max occurs
name - name of variable
returns the time at where the max is
"""
index = self.data_array(name).argmax()
time_at_max = self.time[index]
return time_at_max
def global_min(self, name):
"""
Get minimum value of variable
name - name of variable
"""
return self.data_array(name).min()
def global_min_time(self, name):
"""
Get time where min occurs
name - name of variable
returns the time at where the min is
"""
index = self.data_array(name).argmin()
time_at_min = self.time[index]
return time_at_min
def global_abs_max(self, name):
"""
Get the maximum absolute value of variable
name - name of variable
"""
return np.absolute(self.data_array(name)).max()
def std_dev(self, name):
"""
Returns the standard deviation of variable
name - name of variable
"""
stddev = self.data_array(name).std()
return stddev
def variance(self, name):
"""
Returns the variance of variable
name - name of variable
"""
variance = self.data_array(name).var()
return variance
def sum_value(self, name):
"""
Returns the sum of the time-series for the variable
name - name of variable
"""
result = self.data_array(name).sum()
return result
def mean(self, name):
"""
Returns the mean of the time-series for the variable
name - name of variable
"""
result = np.mean(self.data_array(name), dtype=np.float64)
return result
def integrate(self, name):
"""
Returns the area under the curve of the time-series for the variable
name - name of variable
"""
time = self.time
data = self.data_array(name)
sum = 0
next = data[0]
next_t = time[0]
for i in xrange(data.size):
cur = next
next = data[i]
cur_t = next_t
next_t = time[i]
height = (next + cur) / 2
interval = next_t - cur_t
sum += height * interval
return sum
def minima(self, name):
"""
Returns the minima of time-series of variable
name - name of variable
"""
data = self.data_array(name)
min = []
prev = 0
cur = 0
next = data[0]
for i in xrange(data.size):
if cur < prev and cur <= next:
min.append(cur)
prev = cur
cur = next
next = data[++i]
minimum = np.array(min)
return minimum
def maxima(self, name):
"""
Returns the maxima of time-series of variable
name - name of variable
"""
data = self.data_array(name)
max = []
prev = 0
cur = 0
next = data[0]
for i in xrange(data.size):
if cur >= prev and cur > next:
max.append(cur)
prev = cur
cur = next
next = data[++i]
maximum = np.array(max)
return maximum
def pos_neg(self, name, tol=0.00000015):
"""
Returns time of the roots from positive to negative of time-series of variable
name - name of variable
tol - tolerance
"""
data = self.data_array(name)
time_arr = self.time
time = []
next = -1
for i in xrange(data.size):
cur = next
next = data[i]
if cur > 0 + tol and next <= 0 + tol:
if cur != 0:
cur_t = time_arr[i - 1]
next_t = time_arr[i]
time.append((cur / (cur + next) / 2) * (next_t - cur_t) + cur_t)
else:
time.append(time_arr[i - 1])
timing = np.array(time)
return timing
def neg_pos(self, name, tol=0.00000015):
"""
Returns time of the roots from negative to positive of time-series of variable
name - name of variable
tol - tolerance
"""
time = []
data = self.data_array(name)
time_arr = self.time
next = 1
for i in xrange(data.size):
cur = next
next = data[i]
if cur <= 0 + tol and next > 0 + tol:
if cur != 0:
cur_t = time_arr[i - 1]
next_t = time_arr[i]
time.append(cur / ((cur + next) / 2) * (next_t - cur_t) + cur_t)
else:
time.append(time_arr[i - 1])
timing = np.array(time)
return timing
def to_zero(self, name, value_index):
"""
# time from a number to zero
# (use index from print_data() function)
# parameters: data array, time array, index of value
# returns the time of the zero
"""
data = self.data_array(name)
time_arr = self.time
i = value_index + 1
cur = data[value_index]
next = data[i]
tolerance = 0.00000015
if data[value_index] >= 0:
while next >= 0 + tolerance and i in xrange(data.size - 1):
i += 1
cur = next
next = data[i]
if next >= 0 + tolerance:
return -1
else:
while next <= 0 + tolerance and i in xrange(data.size - 1):
i += 1
cur = next
next = data[i]
if next <= 0 + tolerance:
return -1
if cur != 0:
cur_t = time_arr[i - 1]
next_t = time_arr[i]
time = cur / ((cur + next) / 2) * (next_t - cur_t) + cur_t
else:
time = time_arr[i - 1]
return time
def from_zero(self, name, value_index):
"""
# time from a number to zero
# (use index from print_data() function)
# parameters: data array, time array, index of value
# returns the time of the zero
"""
data = self.data_array(name)
time_arr = self.time
i = value_index - 1
cur = data[value_index]
next = data[i]
tolerance = 0.00000015
if data[value_index - 1] >= 0:
while next >= 0 + tolerance and i in xrange(data.size):
i -= 1
cur = next
next = data[i]
if next >= 0 + tolerance:
return -1
else:
while next <= 0 + tolerance and i in xrange(data.size):
i -= 1
cur = next
next = data[i]
if next <= 0 + tolerance:
return -1
if cur != 0:
cur_t = time_arr[i + 1]
next_t = time_arr[i]
time = cur / ((cur + next) / 2) * (next_t - cur_t) + cur_t
else:
time = time_arr[i + 1]
return time
def zeros(self, name):
"""
Find zeros of time-series for variable
name - name of variable
returns the time of the zero
"""
data_array = self.data_array(name)
time = self.time
data = [[], []]
data[0].append(self.pos_neg(data_array, time))
data[1].append(self.neg_pos(data_array, time))
data_arr = np.array(data)
return data_arr
def compare(self, name1, name2):
"""
Compare the time-series of two variables
name1 - name of variable 1
name2 - name of variable 2
returns true if the results are identical
"""
data1 = self.data_array(name1)
data2 = self.data_array(name2)
for i in xrange(data1.size):
if data1[i] != data2[i]:
return False
return True
def time_total(self, val1, val2):
# finding the difference between 2 times
time = abs(val2 - val1)
return time
def delta_t(self, start_index, end_index):
"""
Returns the length of the time-interval between to indices
"""
t1 = self.time[start_index]
t2 = self.time[end_index]
dt = t2 - t1
return dt
def get_local_max(self, name, start_index, end_index):
"""
Returns the value of the maximum between two indices
N.B. including both points
:param name:
:param start_index:
:param end_index:
"""
if end_index == -1:
maximum = self.data_array(name)[start_index:].max()
else:
maximum = self.data_array(name)[start_index:end_index + 1].max()
return maximum
def get_local_min(self, name, start_index, end_index):
"""
Returns the value of the minimum between two indices
N.B. including both points
"""
if end_index == -1:
minimum = self.data_array(name)[start_index:].min()
else:
minimum = self.data_array(name)[start_index:end_index + 1].min()
return minimum
def find_first_max_violation(self, name, value, start_index=0):
"""
Starting from start_index it looks for the first index where the
time-series has a value greater than value.
If it never occurs, it returns -1
"""
time_series = self.data_array(name)[start_index:]
n = len(time_series)
for i in range(n):
if time_series[i] > value:
return i + start_index
return -1
def find_first_min_violation(self, name, value, start_index=0):
"""
Starting from start_index it looks for the first index where the
time-series has a value less than value.
If it never occurs, it returns -1
"""
time_series = self.data_array(name)[start_index:]
n = len(time_series)
for i in range(n):
if time_series[i] < value:
return i + start_index
return -1
def check_max_limit(self, name, value):
actual_value = ''
limit_exceeded = False
start_index = 0
global_max = -np.Inf
cnt = 0
print 'check_max_limit'
while start_index > -1:
index = self.find_first_max_violation(name, value, start_index)
if index > -1:
end_index = self.find_first_min_violation(name, value, index)
d_t = self.delta_t(index, end_index)
print 'Found violation at t={0} lasting : {1}'.format(self.time[index], d_t)
if d_t > 0.5:
limit_exceeded = True
local_max = self.get_local_max(name, index, end_index)
print 'Local maximum : {0}'.format(local_max)
if local_max > global_max:
global_max = local_max
start_index = end_index
else:
break
cnt += 1
if cnt == MAX_ITERATIONS:
print 'Limit checking for variable {0} aborted after {1} iterations' \
.format(name, MAX_ITERATIONS)
sys.exit(1)
if limit_exceeded:
actual_value = global_max
return limit_exceeded, actual_value
def check_min_limit(self, name, value):
actual_value = ''
limit_exceeded = False
start_index = 0
global_min = np.Inf
cnt = 0
print 'check_min_limit'
while start_index > -1:
index = self.find_first_min_violation(name, value, start_index)
if index > -1:
end_index = self.find_first_max_violation(name, value, index)
d_t = self.delta_t(index, end_index)
print 'Found violation at t={0} lasting : {1} s'.format(self.time[index], d_t)
if d_t > 0.5:
limit_exceeded = True
local_min = self.get_local_min(name, index, end_index)
print 'Local minimum : {0}'.format(local_min)
if local_min < global_min:
global_min = local_min
start_index = end_index
else:
break
cnt += 1
if cnt == MAX_ITERATIONS:
print 'Limit checking for variable {0} aborted after {1} iterations' \
.format(name, MAX_ITERATIONS)
sys.exit(1)
if limit_exceeded:
actual_value = global_min
return limit_exceeded, actual_value
#find_zero(self, array1, array2):
def find_zero(self, array1, array2, time_arr):
tolerance = 0.000000015
tol = 0.0001
for i in xrange(array1.size):
if array1[i] <= (array2[i] + tol):
if array1[i] >= (array2[i] - tol):
if array1[i] <= (0 + tolerance):
if array1[i] >= (0 - tolerance):
return time_arr[i];
return -1
def update_metrics_in_report_json(metrics, report_file='summary.testresults.json'):
"""
Metrics should be of the form
:param metrics:
:param report_file:
{'name_of_metric' : {value: (int) or (float), unit: ""}, ...}
"""
if not os.path.exists(report_file):
raise IOError('Report file does not exits : {0}'.format(report_file))
# read current summary report, which contains the metrics
with open(report_file, 'r') as file_in:
result_json = json.load(file_in)
assert isinstance(result_json, dict)
if 'Metrics' in result_json:
for metric in result_json['Metrics']:
if 'Name' in metric and 'Value' in metric:
if metric['Name'] in metrics.keys():
new_value = metrics[metric['Name']]['value']
new_unit = metrics[metric['Name']]['unit']
if new_unit is not None:
metric['Unit'] = new_unit
if new_value is not None:
metric['Value'] = str(new_value)
else:
pass
else:
print 'Metric item : {0} does not have right format'.format(metric)
pass
# update json file with the new values
with open(report_file, 'wb') as file_out:
json.dump(result_json, file_out, indent=4)
else:
print 'Report file {0} does not have any Metrics defined..'
pass
def read_limits():
"""
Reads in limits and modifies the ModelicaUri to the correct one.
Returns:
- the updated limit_dict
- the filter as a list
"""
with open('limits.json', 'r') as f_in:
limit_dict = json.load(f_in)
# use set to avoid checking for duplicates
filter = set()
for limit_item in limit_dict['LimitChecks']:
# drop first part of VariableFullPath update the limit_item
# once the limit.json is generated correctly these two lines can be dropped
modelica_uri = '.'.join(limit_item['VariableFullPath'].split('.')[1:])
modelica_model_rel_uri = limit_item['VariableName']
split_full_path = limit_item['LimitFullPath'].split('/')
modelica_model = split_full_path[-2]
cyphy_relative_uri = '{0}.{1}'.format(modelica_model, modelica_model_rel_uri)
modelica_uri = modelica_uri.replace(modelica_model_rel_uri, cyphy_relative_uri)
limit_item['VariableFullPath'] = modelica_uri
limit_item['ComponentInstanceName'] = split_full_path[-3]
# filter out this variable in the .mat-file
filter.add(modelica_uri)
# Code specific for FANG-I, with no defined VariableName from GME
#limit_var_name = limit_item['VariableName']
limit_var_name = re.sub('\.u(.*)$', '', modelica_uri)
limit_var_name_split = limit_var_name.split('.')
limit_var_name = limit_var_name_split[len(limit_var_name_split)-3] + '=>' + \
limit_var_name_split[len(limit_var_name_split)-1]
limit_item['LimitName'] = limit_var_name
filter = list(filter)
print "Variables for limit-checking : {0}".format(filter)
return limit_dict, filter
def check_limits_and_add_to_report_json(pp, limit_dict):
"""
Check the limits and write out dictionary to summary.report.json
"""
assert isinstance(pp, PostProcess)
for limit_item in limit_dict['LimitChecks']:
modelica_uri = limit_item['VariableFullPath']
limit_value = limit_item['Value']
limit_type = limit_item['Type']
print "--== {0} ==--".format(modelica_uri)
print "Type of Limit : {0}".format(limit_type)
print "Limit : {0} ".format(limit_value)
if limit_type == 'min':
limit_exceeded, actual_value = pp.check_min_limit(modelica_uri, limit_value)
limit_item['LimitExceeded'] = limit_exceeded
limit_item['ActualValue'] = str(actual_value)
elif limit_type == 'max':
limit_exceeded, actual_value = pp.check_max_limit(modelica_uri, limit_value)
limit_item['LimitExceeded'] = limit_exceeded
limit_item['ActualValue'] = str(actual_value)
else:
limit_exceeded_max, actual_max_value = pp.check_max_limit(modelica_uri, limit_value)
limit_exceeded_min, actual_min_value = pp.check_min_limit(modelica_uri, -limit_value)
# determine the actual value depending on which limits were exceeded
if limit_exceeded_max and limit_exceeded_min:
if actual_max_value > abs(actual_min_value):
actual_value = str(actual_max_value)
else:
actual_value = str(abs(actual_min_value))
elif limit_exceeded_max:
actual_value = str(actual_max_value)
elif limit_exceeded_min:
actual_value = str(abs(actual_min_value))
else:
actual_value = ''
limit_item['LimitExceeded'] = limit_exceeded_max or limit_exceeded_min
limit_item['ActualValue'] = actual_value
limit_item['Value'] = str(limit_value)
print "Violation : {0}".format(limit_item["LimitExceeded"])
with open('summary.testresults.json', 'r') as f_in:
sum_rep_json = json.load(f_in)
sum_rep_json['LimitChecks'] = limit_dict['LimitChecks']
with open('summary.testresults.json', 'wb') as f_out:
json.dump(sum_rep_json, f_out, indent=4)
print "Limits updated"
| [
"tthomas@metamorphsoftware.com"
] | tthomas@metamorphsoftware.com |
a75e5ccc9f7e433c6bdd2b00d6fa814ee47428ba | 52dd82ac3eef74bbaede3ea2938ee3fdd7cea1a7 | /Sources/pyvisa_test.py | cefab94321e5d43afc3f47654994a21f2f3a9700 | [] | no_license | Virgile-Colrat/YFA-Project_python_interface | 4a935895c976c0367864c38380caae63967eca3e | 261d7dba595761726ea272c277a804e62f78bdca | refs/heads/master | 2022-12-25T15:17:31.484500 | 2020-09-15T15:22:15 | 2020-09-15T15:22:15 | 265,026,438 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 527 | py | #import pyvisa
#import time
#rm = pyvisa.ResourceManager()
#print(rm.list_resources())
#inst = rm.open_resource('GPIB0::16::INSTR')
#print(inst.query("*IDN?"))
import pyvisa
import time #import python time functionality
rm = pyvisa.ResourceManager()
A = rm.open_resource("GPIB::16::INSTR") #create variable for instrument address
time.sleep(2)
#A.write("*rst; status:preset; *cls")
A.write("N1")
#A.write("Q1,Virgile Colrat")
#A.write("R1")
#A.write("J2X") | [
"virgile.colrat@utah.edu"
] | virgile.colrat@utah.edu |
0f12dd67a52fa677727c9bb9f8811134440c07c0 | bf4a42534abb260dfb57392f22f4fb9d04072eda | /dependencies.py | 0054ba3df81396b144754d40bca211062b31c2ab | [] | no_license | armagheaddon/virtual-router | 9ce12ac8a8ee2b904f43d8900e550f801481450c | 766640b973e2d746febb0c04c0159a23461b70d3 | refs/heads/master | 2020-08-11T23:24:07.645317 | 2019-11-04T20:05:49 | 2019-11-04T20:05:49 | 214,647,151 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 266 | py | import subprocess
import sys
def install(package):
print 'installing', package
subprocess.call([sys.executable, "-m", "pip", "install", package])
def install_wmi():
install('wmi')
install('pywin32')
def install_pydivert():
install('pydivert')
| [
"dooda174@gmail.com"
] | dooda174@gmail.com |
b25d14bcf3d884d480b51ebd9c1190f821a66ace | 1b858fb089b8588ebaf821a1d33dae4595dc0af1 | /assignment2/cs231n/classifiers/cnn.py | fa01df2c7bfd6ef581a8970f936700d25469f6c0 | [] | no_license | runnphoenix/cs231nAssignments | 20626c91790d9a34bc520026b2a32504926ed728 | fb441a4714a5a1ba5cf97153cecb325fe2feedf8 | refs/heads/master | 2021-09-09T23:59:52.995560 | 2018-03-20T09:30:39 | 2018-03-20T09:30:39 | 109,482,161 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 11,927 | py | import numpy as np
from cs231n.layers import *
from cs231n.fast_layers import *
from cs231n.layer_utils import *
class ThreeLayerConvNet(object):
"""
A three-layer convolutional network with the following architecture:
conv - relu - 2x2 max pool - affine - relu - affine - softmax
The network operates on minibatches of data that have shape (N, C, H, W)
consisting of N images, each with height H and width W and with C input
channels.
"""
def __init__(self, input_dim=(3, 32, 32), num_filters=32, filter_size=7,
hidden_dim=100, num_classes=10, weight_scale=1e-3, reg=0.0,
dtype=np.float32):
"""
Initialize a new network.
Inputs:
- input_dim: Tuple (C, H, W) giving size of input data
- num_filters: Number of filters to use in the convolutional layer
- filter_size: Size of filters to use in the convolutional layer
- hidden_dim: Number of units to use in the fully-connected hidden layer
- num_classes: Number of scores to produce from the final affine layer.
- weight_scale: Scalar giving standard deviation for random initialization
of weights.
- reg: Scalar giving L2 regularization strength
- dtype: numpy datatype to use for computation.
"""
self.params = {}
self.reg = reg
self.dtype = dtype
############################################################################
# TODO: Initialize weights and biases for the three-layer convolutional #
# network. Weights should be initialized from a Gaussian with standard #
# deviation equal to weight_scale; biases should be initialized to zero. #
# All weights and biases should be stored in the dictionary self.params. #
# Store weights and biases for the convolutional layer using the keys 'W1' #
# and 'b1'; use keys 'W2' and 'b2' for the weights and biases of the #
# hidden affine layer, and keys 'W3' and 'b3' for the weights and biases #
# of the output affine layer. #
############################################################################
W1 = np.random.randn(num_filters, input_dim[0], filter_size, filter_size) * weight_scale
b1 = np.zeros(num_filters)
W2 = np.random.randn(num_filters*input_dim[1]/2*input_dim[2]/2, hidden_dim) * weight_scale
b2 = np.zeros(hidden_dim)
W3 = np.random.randn(hidden_dim, num_classes) * weight_scale
b3 = np.zeros(num_classes)
self.params['W1'] = W1
self.params['W2'] = W2
self.params['W3'] = W3
self.params['b1'] = b1
self.params['b2'] = b2
self.params['b3'] = b3
############################################################################
# END OF YOUR CODE #
############################################################################
for k, v in self.params.iteritems():
self.params[k] = v.astype(dtype)
def loss(self, X, y=None):
"""
Evaluate loss and gradient for the three-layer convolutional network.
Input / output: Same API as TwoLayerNet in fc_net.py.
"""
W1, b1 = self.params['W1'], self.params['b1']
W2, b2 = self.params['W2'], self.params['b2']
W3, b3 = self.params['W3'], self.params['b3']
# pass conv_param to the forward pass for the convolutional layer
filter_size = W1.shape[2]
conv_param = {'stride': 1, 'pad': (filter_size - 1) / 2}
# pass pool_param to the forward pass for the max-pooling layer
pool_param = {'pool_height': 2, 'pool_width': 2, 'stride': 2}
scores = None
############################################################################
# TODO: Implement the forward pass for the three-layer convolutional net, #
# computing the class scores for X and storing them in the scores #
# variable. #
############################################################################
l1, cache1 = conv_relu_pool_forward(X,W1,b1,conv_param,pool_param)
l2, cache2 = affine_relu_forward(l1, W2, b2)
l3, cache3 = affine_forward(l2, W3, b3)
scores = l3
############################################################################
# END OF YOUR CODE #
############################################################################
if y is None:
return scores
loss, grads = 0, {}
############################################################################
# TODO: Implement the backward pass for the three-layer convolutional net, #
# storing the loss and gradients in the loss and grads variables. Compute #
# data loss using softmax, and make sure that grads[k] holds the gradients #
# for self.params[k]. Don't forget to add L2 regularization! #
############################################################################
loss, dl3 = softmax_loss(l3, y)
loss += 0.5 * self.reg * (np.sum(W1*W1) + np.sum(W2*W2) + np.sum(W3*W3))
dl2, dW3, db3 = affine_backward(dl3, cache3)
dl1, dW2, db2 = affine_relu_backward(dl2, cache2)
dx, dW1, db1 = conv_relu_pool_backward(dl1, cache1)
dW3 += self.reg * W3
dW2 += self.reg * W2
dW1 += self.reg * W1
grads['W1'] = dW1
grads['W2'] = dW2
grads['W3'] = dW3
grads['b1'] = db1
grads['b2'] = db2
grads['b3'] = db3
############################################################################
# END OF YOUR CODE #
############################################################################
return loss, grads
class FourLayerConvNet(object):
"""
A three-layer convolutional network with the following architecture:
conv - relu - 2x2 max pool - conv - relu - 2*2 max pool - affine - relu - affine - softmax
The network operates on minibatches of data that have shape (N, C, H, W)
consisting of N images, each with height H and width W and with C input
channels.
"""
def __init__(self, input_dim=(3, 32, 32), num_filters_1=32, num_filters_2 = 64, filter_size=7,
hidden_dim=100, num_classes=10, weight_scale=1e-3, reg=0.0,
dtype=np.float32):
"""
Initialize a new network.
Inputs:
- input_dim: Tuple (C, H, W) giving size of input data
- num_filters: Number of filters to use in the convolutional layer
- filter_size: Size of filters to use in the convolutional layer
- hidden_dim: Number of units to use in the fully-connected hidden layer
- num_classes: Number of scores to produce from the final affine layer.
- weight_scale: Scalar giving standard deviation for random initialization
of weights.
- reg: Scalar giving L2 regularization strength
- dtype: numpy datatype to use for computation.
"""
self.params = {}
self.reg = reg
self.dtype = dtype
############################################################################
# TODO: Initialize weights and biases for the three-layer convolutional #
# network. Weights should be initialized from a Gaussian with standard #
# deviation equal to weight_scale; biases should be initialized to zero. #
# All weights and biases should be stored in the dictionary self.params. #
# Store weights and biases for the convolutional layer using the keys 'W1' #
# and 'b1'; use keys 'W2' and 'b2' for the weights and biases of the #
# hidden affine layer, and keys 'W3' and 'b3' for the weights and biases #
# of the output affine layer. #
############################################################################
W1 = np.random.randn(num_filters_1, input_dim[0], filter_size, filter_size) * weight_scale
b1 = np.zeros(num_filters_1)
W1_2 = np.random.randn(num_filters_2, num_filters_1, filter_size, filter_size) * weight_scale
b1_2 = np.zeros(num_filters_2)
W2 = np.random.randn(num_filters_2 * input_dim[1]/4 * input_dim[2]/4, hidden_dim) * weight_scale
b2 = np.zeros(hidden_dim)
W3 = np.random.randn(hidden_dim, num_classes) * weight_scale
b3 = np.zeros(num_classes)
self.params['W1'] = W1
self.params['W1_2'] = W1_2
self.params['W2'] = W2
self.params['W3'] = W3
self.params['b1'] = b1
self.params['b1_2'] = b1_2
self.params['b2'] = b2
self.params['b3'] = b3
############################################################################
# END OF YOUR CODE #
############################################################################
for k, v in self.params.iteritems():
self.params[k] = v.astype(dtype)
def loss(self, X, y=None):
"""
Evaluate loss and gradient for the three-layer convolutional network.
Input / output: Same API as TwoLayerNet in fc_net.py.
"""
W1, b1 = self.params['W1'], self.params['b1']
W1_2, b1_2 = self.params['W1_2'], self.params['b1_2']
W2, b2 = self.params['W2'], self.params['b2']
W3, b3 = self.params['W3'], self.params['b3']
# pass conv_param to the forward pass for the convolutional layer
filter_size = W1.shape[2]
conv_param = {'stride': 1, 'pad': (filter_size - 1) / 2}
# pass pool_param to the forward pass for the max-pooling layer
pool_param = {'pool_height': 2, 'pool_width': 2, 'stride': 2}
scores = None
############################################################################
# TODO: Implement the forward pass for the three-layer convolutional net, #
# computing the class scores for X and storing them in the scores #
# variable. #
############################################################################
l1, cache1 = conv_relu_pool_forward(X, W1, b1, conv_param, pool_param)
l1_2, cache1_2 = conv_relu_pool_forward(l1, W1_2, b1_2, conv_param, pool_param)
l2, cache2 = affine_relu_forward(l1_2, W2, b2)
l3, cache3 = affine_forward(l2, W3, b3)
scores = l3
############################################################################
# END OF YOUR CODE #
############################################################################
if y is None:
return scores
loss, grads = 0, {}
############################################################################
# TODO: Implement the backward pass for the three-layer convolutional net, #
# storing the loss and gradients in the loss and grads variables. Compute #
# data loss using softmax, and make sure that grads[k] holds the gradients #
# for self.params[k]. Don't forget to add L2 regularization! #
############################################################################
loss, dl3 = softmax_loss(l3, y)
loss += 0.5 * self.reg * (np.sum(W1*W1) + np.sum(W2*W2) + np.sum(W3*W3) + np.sum(W1_2*W1_2))
dl2, dW3, db3 = affine_backward(dl3, cache3)
dl1_2, dW2, db2 = affine_relu_backward(dl2, cache2)
dl1, dW1_2, db1_2 = conv_relu_pool_backward(dl1_2, cache1_2)
dx, dW1, db1 = conv_relu_pool_backward(dl1, cache1)
dW3 += self.reg * W3
dW2 += self.reg * W2
dW1_2 += self.reg * W1_2
dW1 += self.reg * W1
grads['W1'] = dW1
grads['W1_2'] = dW1_2
grads['W2'] = dW2
grads['W3'] = dW3
grads['b1'] = db1
grads['b1_2'] = db1_2
grads['b2'] = db2
grads['b3'] = db3
############################################################################
# END OF YOUR CODE #
############################################################################
return loss, grads
| [
"runnphoenix@gmail.com"
] | runnphoenix@gmail.com |
37bd9345c527cc1ef1581f65d4b3d0dc7bd16f23 | 461d2a2faf825175c107381b176ab5a05af8c1de | /ch7/callable_fn.py | 2c145762aaa3bd49959fcbd781874ec41c156f98 | [] | no_license | thatguysilver/py3oop | 29e2455c4fd7f3b2c6ef0d160646a9fbcc0d87b0 | dfc65b813f371c2a4c24ee521121e1558635d1b4 | refs/heads/master | 2021-01-15T22:01:42.399603 | 2017-08-31T06:36:26 | 2017-08-31T06:36:26 | 99,881,062 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 214 | py | # does not work as demonstrated in the text.
class A:
def print(self):
print('my class is A')
def fake_print():
print('my clas is not A')
a = A()
a.print()
a.print = fake_print
a.print()
| [
"adampaulsilver@gmail.com"
] | adampaulsilver@gmail.com |
686d84246b45e52dd12f18ac11155e8b756bddd4 | 7c5c5382751e34ce2377d64786c341f5992e8941 | /espnet/nets/pytorch_backend/transducer/vgg2l.py | 134116c1a031777b9f0525d86439e7a6005e3755 | [
"Apache-2.0"
] | permissive | ZeyuChen/espnet | a6ed0dc6fba992b38db8816e8385f5556a487fdc | 01eaefef7698453d3c6497c17ba679c98e9f5f85 | refs/heads/master | 2022-12-28T16:05:23.975355 | 2020-09-24T18:18:24 | 2020-09-24T18:18:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,047 | py | """VGG2L module definition for transformer encoder."""
import torch
class VGG2L(torch.nn.Module):
"""VGG2L module for transformer encoder.
Args:
idim (int): dimension of inputs
odim (int): dimension of outputs
"""
def __init__(self, idim, odim):
"""Construct a VGG2L object."""
super(VGG2L, self).__init__()
self.vgg2l = torch.nn.Sequential(
torch.nn.Conv2d(1, 64, 3, stride=1, padding=1),
torch.nn.ReLU(),
torch.nn.Conv2d(64, 64, 3, stride=1, padding=1),
torch.nn.ReLU(),
torch.nn.MaxPool2d((3, 2)),
torch.nn.Conv2d(64, 128, 3, stride=1, padding=1),
torch.nn.ReLU(),
torch.nn.Conv2d(128, 128, 3, stride=1, padding=1),
torch.nn.ReLU(),
torch.nn.MaxPool2d((2, 2)),
)
self.output = torch.nn.Linear(128 * ((idim // 2) // 2), odim)
def forward(self, x, x_mask):
"""VGG2L forward for x.
Args:
x (torch.Tensor): input torch (B, T, idim)
x_mask (torch.Tensor): (B, 1, T)
Returns:
x (torch.Tensor): input torch (B, sub(T), attention_dim)
x_mask (torch.Tensor): (B, 1, sub(T))
"""
x = x.unsqueeze(1)
x = self.vgg2l(x)
b, c, t, f = x.size()
x = self.output(x.transpose(1, 2).contiguous().view(b, t, c * f))
if x_mask is not None:
x_mask = self.create_new_mask(x_mask, x)
return x, x_mask
def create_new_mask(self, x_mask, x):
"""Create a subsampled version of x_mask.
Args:
x_mask (torch.Tensor): (B, 1, T)
x (torch.Tensor): (B, sub(T), attention_dim)
Returns:
x_mask (torch.Tensor): (B, 1, sub(T))
"""
x_t1 = x_mask.size(2) - (x_mask.size(2) % 3)
x_mask = x_mask[:, :, :x_t1][:, :, ::3]
x_t2 = x_mask.size(2) - (x_mask.size(2) % 2)
x_mask = x_mask[:, :, :x_t2][:, :, ::2]
return x_mask
| [
"florian.boyer@labri.fr"
] | florian.boyer@labri.fr |
c5c84ece0298586ded8abcbd83eeaed543a4d70a | 7c7e9f68ecc973b8779b2c8b96f6396d0d54f5bb | /selection_sort/SelectionSort.py | 02130702e9ac0fc232a64f5f2c72735e5a11ff3c | [] | no_license | Ab4rdo/Python_Algorithms | b08def3f6150695639f4824526d2d56f78a58073 | 1c0dfe3010d08946423e45af96ddae213c5626f2 | refs/heads/master | 2021-08-22T09:28:48.899514 | 2017-11-29T21:29:06 | 2017-11-29T21:29:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 806 | py |
def sort(seq):
"""
Implementation of selection sort algortihm
:param seq: a integer list
:return: new ascending sorted array
"""
if not seq:
raise ValueError('List is empty')
i = 0
length = len(seq)
while i < length:
mini = index_of_min(seq, i)
temp = seq[i]
seq[i] = seq[mini]
seq[mini] = temp
i += 1
return seq
# Helping methods
def index_of_min(seq, i):
"""
:param seq: a integer list
:param i: most left-hand side index
:return: index of the smallest element in seq starting form i index
"""
min_index = i
for x in range(len(seq[i:])):
current_index = x + i
if seq[current_index] < seq[min_index]:
min_index = current_index
return min_index
| [
"fryderyk97@protonmail.com"
] | fryderyk97@protonmail.com |
a1d0935887279858f210d20a3d36d3b9b197070e | 3babb8eb818665e7ba07ca19321066d3e7463bb9 | /leetcode/9-palindrome.py | 901312cdd379e43288d7a7ac91fcbfd69675a2c1 | [] | no_license | MLL1228/mycode | 44b5ca662f9465f4e17c7422a8f5dc1d56fcbc12 | 187d809371390d08313ca02f94e299d5484431ba | refs/heads/master | 2020-04-22T08:16:14.689394 | 2019-03-01T06:07:02 | 2019-03-01T06:07:02 | 170,239,089 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 452 | py | class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
else:
mystr = str(x)
reverse_str = mystr[::-1]
# print(reverse_str)
if int(reverse_str) == x:
return True
else:
return False
if __name__ == '__main__':
print(Solution().isPalindrome(-121)) | [
"menglili@menglilideMacBook-Pro.local"
] | menglili@menglilideMacBook-Pro.local |
a6c573e0f691bc552fe6e058fb7f7e4db8f2b091 | 01d26dafe380aff75767ddaf4943f17e09a7d55e | /main.py | 44f1f5d0a9ea14310b540773c7dedcdb66892bd1 | [] | no_license | Eyads99/UltimateTicTacToeML | 6f3a0d04b6272f5ccd511382f26512ce1bb7a507 | ea5d8c9e8958a11e19e8b6e6de3f6f2d9ce5719d | refs/heads/main | 2023-01-24T17:49:25.704764 | 2020-12-07T21:27:07 | 2020-12-07T21:27:07 | 315,648,400 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,151 | py | import numpy as np
import math
from numpy import random
# x==
turn = 'x'
# board =np.zeros((9,9))
board=np.full((9,9), ['e'],dtype=str)
inputMB=-1
inputPosition=-1
miniboardOutcome=np.full((9), ['e'],dtype=str)
print(miniboardOutcome)
def StateOfGame():
global miniboardOutcome
for i in range(3):
if (miniboardOutcome[i] == miniboardOutcome[i + 3] == miniboardOutcome[i + 6]): # check col
if miniboardOutcome[i] != 'e':#this assumes that undefined state is e
print("Player "+ miniboardOutcome[i]+" has won")
return miniboardOutcome[i]#returning winnning symbol x or y
if (miniboardOutcome[0 + (i * 3)] == miniboardOutcome[1 + (i * 3)] == miniboardOutcome[2 + (i * 3)]): # check row
if miniboardOutcome[0 + (i * 3)] != 'e':
print("Player " + miniboardOutcome[0 + (i * 3)] + " has won")
return miniboardOutcome[0 + (i * 3)]#return x or y
if (miniboardOutcome[0] == miniboardOutcome[4] == miniboardOutcome[8]): # check diag
if miniboardOutcome[0] != 'e':
print("Player " + miniboardOutcome[0] + " has won")
return miniboardOutcome[0]
if (miniboardOutcome[2] == miniboardOutcome[4] == miniboardOutcome[6]): # check inv-diag
if miniboardOutcome[2] != 'e':
print("Player "+miniboardOutcome[2]+" has won")
return miniboardOutcome[2]
for i in range(9):
if (miniboardOutcome[i] == 'e'):
return 'i'#i for incomplete
print("The game is tied :)")
return 't'#the game is completly tied
def inputXO():
global turn
global inputMB
global board
global inputPosition
isValid = False
if (inputMB == -1): ##very first input of game
manualMB = True
else:
if (miniboardOutcome[inputMB] != 'e'): # has an outcome
print(miniboardOutcome)
manualMB = True
else: # does not have an outcome
manualMB = False
while isValid==False:
if(manualMB):
# inputMB = int(input(turn + "'s turn: input your Miniboard number: "))
# inputMB-=1
inputMB=random.randint(9)
if not(inputMB <= 8 and inputMB >= 0 and miniboardOutcome[inputMB] == 'e'):
isValid=False
print("Miniboard input is not valid")
continue
else:
print("you are paying in miniboard "+str(inputMB+1))
# inputPosition = int(input(turn + "'s turn:input your Position number: "))
# inputPosition-=1
inputPosition = random.randint(9)
if not(inputPosition <= 8 and inputPosition >= 0):
isValid = False
print("Input Position input is not valid")
continue
if(board[inputMB][inputPosition]=='e'):
board[inputMB][inputPosition] = turn
isValid = True
else:
print("Position is invalid, reinput")
print(turn + " "+str(inputMB)+ " "+str(inputPosition) )
print(manualMB)
if(turn=='x'): turn = 'o'
else: turn = 'x'
miniboardOutcomeF(inputMB)
inputMB = inputPosition
printBoard()
print(miniboardOutcome)
def miniboardOutcomeF(miniboard):
for i in range(3):
if(board[miniboard][i]==board[miniboard][i+3]==board[miniboard][i+6]): #check col
if board[miniboard][i] != 'e':
miniboardOutcome[miniboard] = board[miniboard][i]
return board[miniboard][i]
if(board[miniboard][0+(i*3)]==board[miniboard][1+(i*3)]==board[miniboard][2+(i*3)]): #check row
if board[miniboard][0+(i*3)] !='e':
miniboardOutcome[miniboard]=board[miniboard][0+(i*3)]
return board[miniboard][0+(i*3)]
if(board[miniboard][0]==board[miniboard][4]==board[miniboard][8]): #check diag
if board[miniboard][0]!='e':
miniboardOutcome[miniboard] = board[miniboard][0]
return board[miniboard][0]
if(board[miniboard][2]==board[miniboard][4]==board[miniboard][6]): #check inv-diag
if board[miniboard][2] != 'e':
miniboardOutcome[miniboard] = board[miniboard][2]#why is this 0 should be 2
return board[miniboard][2]
for i in range(9):
if(board[miniboard][i]=='e'):
return 'e'#should return e
miniboardOutcome[miniboard] = 't'
print(miniboardOutcome)
return 't'
def printBoard():
for q in range(3):
for k in range(3):
line = ""
for i in range(3):
for j in range(3):
line = line + board[i+(q*3)][j+(k*3)]
#line = line + str(i + (q * 3)) + str(j + (k * 3)) + " "
line += "|"
print(line)
print("------------")
# for i in range(3): #first three boards
# for k in range(3):
# print(board[i)
# print(board[k][k*(i+1)]+board[k][k*(i+1)]+board[k][k*(i+1)]+' | ')
# for j in range(3,6):
#
# for i in range(6,9):
while StateOfGame()=='i':
inputXO() #while loop
## x o x
## e e x
## x e e
| [
"eyadshaban99@gmail.com"
] | eyadshaban99@gmail.com |
5925c4fef5a3c394c43a7fefeee95cbf444d7cf9 | 13faca2aa7c8cd378274e79a4c974adb03320920 | /data_wrangling.py | e008a81b5b0ef33cafe7506d756c8f4bcb56c3be | [
"MIT"
] | permissive | ovravindra/SentimentAnalysis | 16361aa148cb085733debb428fe445ac26b4b921 | 2e5dea9806d86fc12ab30fff125a24208ae9e003 | refs/heads/master | 2022-12-14T14:02:05.925597 | 2020-09-14T08:12:52 | 2020-09-14T08:12:52 | 295,315,278 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,598 | py | # AIM : to construct a modular code blocks to perform standard text wrangling operations and also to
# produce handy plots and other functionality.
# we can borrow the word vectors generated using the CountVectoriser and TfidfVectoriser to
# train the binary classification Logistic Regression model and check the accuracy.
# starting the Data wrangling using pandas and numpy
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style = 'whitegrid', color_codes = True)
import os
import re
# loading the text data
twitter_df = pd.read_csv("twitter_train.csv")
twitter_df.head(50)
"""
input variables
1. id : is the ID of the tweet
2. Keyword : is the main word that is used to extract the tweet. both the positive and negative sentiments revolve around this words
3. Location: is the geo-location of the person tweeting.
4. Text: is the main body of the tweet. Any tweet can have only 280 characters. i.e., for example any one of the following list is a character :- [a,1,@,A... etc]
5. Target: finally the sentiment of the tweet, manually added. This makes the data labeled data, and hence, the problem a classification problem.
"""
twitter_df.info()
twitter_df.shape
twitter_df = twitter_df.dropna(how = 'all', axis = 0)
twitter_df.shape
twitter_df = twitter_df.fillna('0')
print(twitter_df['target'].value_counts())
sns.countplot(x = 'target', data = twitter_df, palette='hls')
df = twitter_df.groupby(['keyword', 'target'])['text'].count().reset_index()
"""
further implementations to be done
1. number of characters in a tweet.
""" | [
"ravindra.oguri@gmail.com"
] | ravindra.oguri@gmail.com |
7046501e30ccbee9cab11a5ecea1858f0d31b987 | bee6c97cdac6f8d7c9888209930ece354cd8b009 | /AtCoder/ABC/162/C.py | b3d9513b243909a4e41ea083228cda7ffd2212e2 | [] | no_license | U-MA-dev/contest | 40bc225a27d85f819b15419b9797550bcc67b401 | 5d677371a271f87098f7b8680640990f7e646e23 | refs/heads/master | 2022-04-27T12:39:20.226049 | 2020-04-28T06:58:07 | 2020-04-28T06:58:07 | 255,538,984 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 480 | py | from collections import defaultdict
K = int(input())
def calcGcd(a, b):
large = max(a, b)
small = min(a, b)
while (True):
num = large % small
large = small
small = num
if small == 0:
return large
ans = 0
dd = defaultdict(int)
for i in range(1, K + 1):
for j in range(1, K + 1):
dd[calcGcd(i, j)] += 1
for num in dd.keys():
for k in range(1, K + 1):
ans += calcGcd(num, k) * dd[num]
print(ans)
| [
"kawabata@iotbase.co.jp"
] | kawabata@iotbase.co.jp |
757740985f08fab8c8e151f77801737e140d2722 | d8fabc8d17cce9cfbc02a7c293f13a6fd3ed3c0e | /backend/backend/settings.py | 16eab2d3a6a814c60ecbf05b9b2308fb89f550c3 | [] | no_license | lashleykeith/djangoReactShop | 2213dfb0d52c4ef2f42148a4932fc3f6284182bc | c48c085457360e7c0d481633594d475fb7c56672 | refs/heads/main | 2023-08-27T20:02:31.357355 | 2021-10-30T10:47:04 | 2021-10-30T10:47:04 | 422,797,986 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,686 | py | """
Django settings for backend project.
Generated by 'django-admin startproject' using Django 3.1.7.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '9l13*841s1ff4m!9tx&gf_lt4bpzf)be!&0s7p_k7heivaeglp'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders',
'base.apps.BaseConfig',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
)
}
# Django project settings.py
from datetime import timedelta
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(days=30),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'ROTATE_REFRESH_TOKENS': False,
'BLACKLIST_AFTER_ROTATION': True,
'UPDATE_LAST_LOGIN': False,
'ALGORITHM': 'HS256',
'VERIFYING_KEY': None,
'AUDIENCE': None,
'ISSUER': None,
'JWK_URL': None,
'LEEWAY': 0,
'AUTH_HEADER_TYPES': ('Bearer',),
'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION',
'USER_ID_FIELD': 'id',
'USER_ID_CLAIM': 'user_id',
'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule',
'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
'TOKEN_TYPE_CLAIM': 'token_type',
'JTI_CLAIM': 'jti',
'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
}
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
#'django.middleware.common.CommonMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'backend.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'backend.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
MEDIA_URL = '/images/'
STATICFILES_DIRS = [
BASE_DIR / 'static'
]
MEDIA_ROOT = 'static/images'
CORS_ORIGIN_ALLOW_ALL = True
#CORS_ALLOWED_ORIGINS = True | [
"noreply@github.com"
] | lashleykeith.noreply@github.com |
a22e4b641fd599215f054548a58f5cd1ff662611 | a524901d55a4c0a74a91301d60486aec5aec3cfa | /mi_buy.py | 202964957df6c264e4ddf7c644e47a584af822f9 | [] | no_license | tenlee2012/PlayCollections | 4d32516ce05dc1b72fa43816f7044004d7abd49a | a8b5cf835c54605ccabfb14b2c2926a147c99c60 | refs/heads/master | 2021-09-10T15:14:24.339577 | 2018-03-28T09:51:40 | 2018-03-28T09:51:40 | 104,848,122 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 7,079 | py | # coding=utf-8
import requests
import logging
import time
logging.basicConfig(
# filename='mi_buy.log',
level=logging.INFO,
format='%(levelname)s:%(asctime)s:%(message)s'
)
class MiBuyError(IOError):
pass
class MiBuy(object):
ADD_CART_URL = 'https://m.mi.com/v1/cart/add'
SEL_CART_URL = 'https://m.mi.com/v1/cart/selcart'
DEL_CART_URL = 'https://m.mi.com/v1/cart/del'
SUBMIT_ORDER_URL = 'https://m.mi.com/v1/order/submitPay'
ADDRESS_URL = 'https://m.mi.com/v1/address/list'
CHECKOUT_URL = 'https://m.mi.com/v1/order/checkout'
session = requests.Session()
def __init__(self, client_id, cookie):
self.cookie = cookie
self.client_id = client_id
self.address_id = None
self.paymethod = 'alipaywap'
self.invoice_email = None
self.invoice_tel = None
self.invoice_title = None
self.invoice_type = None
self.session.headers.update({
"Host": "m.mi.com",
"User-Agent": "Mozilla/5.0 (Linux; Android 5.1.1; Nexus 6 Build/LYZ28E) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.23 Mobile Safari/537.36",
"Accept": "application/json, text/plain, */*",
"Cookie": self.cookie
})
def __make_referer__(self, cookie, referer):
self.session.headers.update({
"Referer": referer,
})
def __post__(self, url, referer, payload={}):
self.__make_referer__(cookie, referer)
if payload is None:
payload = {}
payload['client_id'] = self.client_id
payload['webp'] = 0
resp = self.session.post(url, data=payload)
logging.debug("url=[{}],status_code=[{}],data=[{}]".format(resp.url, resp.status_code, resp.text))
return resp
def add_cart(self, product_id, referer):
payload = {
"product_id": product_id
}
resp = self.__post__(self.ADD_CART_URL, referer, payload).json()
if resp.get('code', -1) != 0:
raise MiBuyError("商品加入购物车失败,原因:{}".format(resp.get('description')))
logging.info("商品加入购物车成功,目前数量是{}".format(resp.get("data", dict()).get('count', -1)))
def sel_cart(self, product_id):
payload = {
"sel_itemid_list": [product_id+"_0_buy"],
"sel_status": 1
}
referer = 'https://m.mi.com/cart'
resp = self.__post__(self.SEL_CART_URL, referer, payload).json()
if resp.get('code', -1) != 0:
raise MiBuyError("勾选商品失败,原因:{}".format(resp.get('description')))
def del_cart(self, product_id):
referer = 'https://m.mi.com/cart'
payload = {
"itemId": product_id + '_0_buy',
}
resp = self.__post__(self.DEL_CART_URL, referer, payload).json()
if resp.get('code', -1) != 0:
raise MiBuyError("购物车删除失败,原因:{}".format(resp.get('description')))
logging.info('购物车删除成功')
def show_cart(self):
url = 'https://m.mi.com/v1/cart/index'
referer = 'https://m.mi.com/user'
self.__post__(url, referer)
def show_all_address(self):
referer = 'https://m.mi.com/order/checkout?address_id='
resp = self.__post__(self.ADDRESS_URL, referer).json()
if resp.get('code', -1) != 0 or not resp.get('data'):
raise MiBuyError("获取收货地址失败,原因:{}".format(resp.get('description')))
data = resp.get('data')
print('请选择收货地址(输入收货地址ID):')
for address in data:
print("ID:{address_id},地址:{province} {city} {district} {area} {address} {consignee} {tel}".format(**address))
self.address_id = input()
def get_delivery(self):
'''
获取配送地址,发票信息
:return:
'''
referer = 'https://m.mi.com/cart?from=product&address_id='
resp = self.__post__(self.CHECKOUT_URL, referer).json()
if resp.get('code', -1) != 0:
raise MiBuyError("获取收货地址发票失败,原因:{}".format(resp.get('description')))
else:
data = resp.get('data', {})
self.address_id = data.get('address', {}).get('address_id')
address = data.get('address', {}).get('address')
self.invoice_email = data.get('default_invoice_email')
self.invoice_tel = data.get('default_invoice_tel')
self.invoice_title = data.get('default_invoice_title')
self.invoice_type = data.get('default_invoice_type')
logging.info('获取收货地址发票成功,地址为{},发票邮箱:{},抬头:{}'.format(address, self.invoice_email, self.invoice_title))
def submit_order(self):
# 提交订单前需要先访问我的购物车页面, 以获取最新cookie
self.show_cart()
referer = 'https://m.mi.com/order/checkout?address_id='
payload = {
'address_id': self.address_id,
'best_time': 1,
'channel_id': 0,
'pay_id': 1,
'paymethod': self.paymethod,
'invoice_email': 'tenlee2012@163.com',
'invoice_tel': '176****7879',
'invoice_title': '个人',
'invoice_type': '4',
}
resp = self.__post__(self.SUBMIT_ORDER_URL, referer, payload).json()
if resp.get('code', -1) != 0:
raise MiBuyError("订单提交失败,原因:{}".format(resp.get('description')))
else:
logging.info('订单提交成功,请到APP或者web页面查看并付款')
def buy(self, product_id, product_url):
while True:
try:
# 先将该商品从购物车清空
mi_buy.del_cart(product_id)
# 加入购物车
mi_buy.add_cart(product_id, product_url)
# 获取默认地址发票等
mi_buy.get_delivery()
# 提交订单
mi_buy.submit_order()
except MiBuyError as e:
print(e)
else:
break
time.sleep(0.5)
if __name__ == '__main__':
# mix 2s 黑色 6+64 2181000001
# mix 2s 白色 6+64 2181000002
# mix 2s 黑色 6+128 2181000003
# mix 2s 白色 6+128 2181000004
# mix 2s 黑色 8+256 2181000005
# mix 2s 白色 8+256 2181000006
# mix 2 黑色陶瓷 6+64 2174200042
input("订单配送地址为设置的默认收货地址,发票也为默认的发票信息,如果不同修改请至小米商城修改(ps:订单提交成功后,也是支持修改收货地址的),如果你已悉知,请输入任意字符")
cookie = input("输入cookie:")
client_id = input("输入clientId:")
mi_buy = MiBuy(client_id, cookie)
product_id = input("输入购买的商品ID:")
product_id = '2174200042'
product_url = 'https://m.mi.com/commodity/detail/7153'
mi_buy.buy(product_id, product_url)
| [
"jiahao.li@petkit.com"
] | jiahao.li@petkit.com |
01cabaa83df787a973353fd6f3c195237768f961 | c4a2c5d2ee3bb946333bec267c337858c2eaa87c | /bhiveapi/hivenoderpc.py | 58ce7500c87b948f6e6633ae663e981fa3749a04 | [
"MIT"
] | permissive | TheCrazyGM/bhive | 93b237140def25a8cb4de0160678db116b45d4e0 | 1494e90a99123ecfc5efbd927258f9ba59443e2e | refs/heads/master | 2021-04-10T20:15:59.966431 | 2020-03-22T23:50:52 | 2020-03-22T23:50:52 | 248,962,200 | 3 | 1 | NOASSERTION | 2020-10-27T22:24:53 | 2020-03-21T11:29:02 | Python | UTF-8 | Python | false | false | 9,554 | py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from builtins import bytes, int, str
import re
import sys
from .graphenerpc import GrapheneRPC
from . import exceptions
import logging
log = logging.getLogger(__name__)
class HiveNodeRPC(GrapheneRPC):
""" This class allows to call API methods exposed by the witness node via
websockets / rpc-json.
:param str urls: Either a single Websocket/Http URL, or a list of URLs
:param str user: Username for Authentication
:param str password: Password for Authentication
:param int num_retries: Try x times to num_retries to a node on disconnect, -1 for indefinitely
:param int num_retries_call: Repeat num_retries_call times a rpc call on node error (default is 5)
:param int timeout: Timeout setting for https nodes (default is 60)
:param bool use_condenser: Use the old condenser_api rpc protocol on nodes with version
0.19.4 or higher. The settings has no effect on nodes with version of 0.19.3 or lower.
"""
def __init__(self, *args, **kwargs):
""" Init HiveNodeRPC
:param str urls: Either a single Websocket/Http URL, or a list of URLs
:param str user: Username for Authentication
:param str password: Password for Authentication
:param int num_retries: Try x times to num_retries to a node on disconnect, -1 for indefinitely
:param int num_retries_call: Repeat num_retries_call times a rpc call on node error (default is 5)
:param int timeout: Timeout setting for https nodes (default is 60)
"""
super(HiveNodeRPC, self).__init__(*args, **kwargs)
self.next_node_on_empty_reply = False
def set_next_node_on_empty_reply(self, next_node_on_empty_reply=True):
"""Switch to next node on empty reply for the next rpc call"""
self.next_node_on_empty_reply = next_node_on_empty_reply
def rpcexec(self, payload):
""" Execute a call by sending the payload.
It makes use of the GrapheneRPC library.
In here, we mostly deal with Hive specific error handling
:param json payload: Payload data
:raises ValueError: if the server does not respond in proper JSON format
:raises RPCError: if the server returns an error
"""
if self.url is None:
raise exceptions.RPCConnection("RPC is not connected!")
doRetry = True
maxRetryCountReached = False
while doRetry and not maxRetryCountReached:
doRetry = False
try:
# Forward call to GrapheneWebsocketRPC and catch+evaluate errors
reply = super(HiveNodeRPC, self).rpcexec(payload)
if self.next_node_on_empty_reply and not bool(reply) and self.nodes.working_nodes_count > 1:
self._retry_on_next_node("Empty Reply")
doRetry = True
self.next_node_on_empty_reply = True
else:
self.next_node_on_empty_reply = False
return reply
except exceptions.RPCErrorDoRetry as e:
msg = exceptions.decodeRPCErrorMsg(e).strip()
try:
self.nodes.sleep_and_check_retries(str(msg), call_retry=True)
doRetry = True
except exceptions.CallRetriesReached:
if self.nodes.working_nodes_count > 1:
self._retry_on_next_node(msg)
doRetry = True
else:
self.next_node_on_empty_reply = False
raise exceptions.CallRetriesReached
except exceptions.RPCError as e:
try:
doRetry = self._check_error_message(e, self.error_cnt_call)
except exceptions.CallRetriesReached:
msg = exceptions.decodeRPCErrorMsg(e).strip()
if self.nodes.working_nodes_count > 1:
self._retry_on_next_node(msg)
doRetry = True
else:
self.next_node_on_empty_reply = False
raise exceptions.CallRetriesReached
except Exception as e:
self.next_node_on_empty_reply = False
raise e
maxRetryCountReached = self.nodes.num_retries_call_reached
self.next_node_on_empty_reply = False
def _retry_on_next_node(self, error_msg):
self.nodes.increase_error_cnt()
self.nodes.sleep_and_check_retries(error_msg, sleep=False, call_retry=False)
self.next()
def _check_error_message(self, e, cnt):
"""Check error message and decide what to do"""
doRetry = False
msg = exceptions.decodeRPCErrorMsg(e).strip()
if re.search("missing required active authority", msg):
raise exceptions.MissingRequiredActiveAuthority
elif re.search("missing required active authority", msg):
raise exceptions.MissingRequiredActiveAuthority
elif re.match("^no method with name.*", msg):
raise exceptions.NoMethodWithName(msg)
elif re.search("Could not find method", msg):
raise exceptions.NoMethodWithName(msg)
elif re.search("Could not find API", msg):
if self._check_api_name(msg):
if self.nodes.working_nodes_count > 1 and self.nodes.num_retries > -1:
self.nodes.disable_node()
self._switch_to_next_node(msg, "ApiNotSupported")
doRetry = True
else:
raise exceptions.ApiNotSupported(msg)
else:
raise exceptions.NoApiWithName(msg)
elif re.search("follow_api_plugin not enabled", msg):
if self.nodes.working_nodes_count > 1 and self.nodes.num_retries > -1:
self._switch_to_next_node(str(e))
doRetry = True
else:
raise exceptions.FollowApiNotEnabled(msg)
elif re.search("irrelevant signature included", msg):
raise exceptions.UnnecessarySignatureDetected(msg)
elif re.search("WinError", msg):
raise exceptions.RPCError(msg)
elif re.search("Unable to acquire database lock", msg):
self.nodes.sleep_and_check_retries(str(msg), call_retry=True)
doRetry = True
elif re.search("Request Timeout", msg):
self.nodes.sleep_and_check_retries(str(msg), call_retry=True)
doRetry = True
elif re.search("Bad or missing upstream response", msg):
self.nodes.sleep_and_check_retries(str(msg), call_retry=True)
doRetry = True
elif re.search("Internal Error", msg) or re.search("Unknown exception", msg):
self.nodes.sleep_and_check_retries(str(msg), call_retry=True)
doRetry = True
elif re.search("!check_max_block_age", str(e)):
self._switch_to_next_node(str(e))
doRetry = True
elif re.search("Can only vote once every 3 seconds", msg):
raise exceptions.VotedBeforeWaitTimeReached(msg)
elif re.search("out_of_rangeEEEE: unknown key", msg) or re.search("unknown key:unknown key", msg):
raise exceptions.UnkownKey(msg)
elif re.search("Assert Exception:v.is_object(): Input data have to treated as object", msg):
raise exceptions.UnhandledRPCError("Use Operation(op, appbase=True) to prevent error: " + msg)
elif re.search("Client returned invalid format. Expected JSON!", msg):
if self.nodes.working_nodes_count > 1 and self.nodes.num_retries > -1:
self.nodes.disable_node()
self._switch_to_next_node(msg)
doRetry = True
else:
raise exceptions.UnhandledRPCError(msg)
elif msg:
raise exceptions.UnhandledRPCError(msg)
else:
raise e
return doRetry
def _switch_to_next_node(self, msg, error_type="UnhandledRPCError"):
if self.nodes.working_nodes_count == 1:
if error_type == "UnhandledRPCError":
raise exceptions.UnhandledRPCError(msg)
elif error_type == "ApiNotSupported":
raise exceptions.ApiNotSupported(msg)
self.nodes.increase_error_cnt()
self.nodes.sleep_and_check_retries(str(msg), sleep=False)
self.next()
def _check_api_name(self, msg):
error_start = "Could not find API"
known_apis = ['account_history_api', 'tags_api',
'database_api', 'market_history_api',
'block_api', 'account_by_key_api', 'chain_api',
'follow_api', 'condenser_api', 'debug_node_api',
'witness_api', 'test_api',
'network_broadcast_api']
for api in known_apis:
if re.search(error_start + " " + api, msg):
return True
if msg[-18:] == error_start:
return True
return False
def get_account(self, name, **kwargs):
""" Get full account details from account name
:param str name: Account name
"""
if isinstance(name, str):
return self.get_accounts([name], **kwargs)
| [
"thecrazygm@gmail.com"
] | thecrazygm@gmail.com |
14b44cfeeb857c270650b4444f4ec2d27f241160 | f3c8ec9ee5c2a70d847207ca39a9c9bf6d728de9 | /FaceDetect/detector.py | e81b50801088b9e8de7be99ca5a9d8aff0728f9c | [] | no_license | paparazzi/pprz-jevois | efdaafefdc8dd1235c0b0addfb9dd8bd68761fe7 | 4a35c0927efe6bf790ce5ca25740d78f0e22ecaf | refs/heads/master | 2020-04-19T04:52:29.455841 | 2019-12-26T18:06:13 | 2019-12-26T18:06:13 | 167,973,026 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,567 | py | #!/usr/bin/python
import sys
import cv2
class Detector:
def __init__(self, cascade_path=""):
#os.path.dirname(os.path.realpath(__file__))
if not cascade_path:
print("Detector: no cascade path, trying default location for face cascade")
cascade_path = '/jevois/share/facedetector/haarcascade_frontalface_alt.xml'
self.classifier = cv2.CascadeClassifier(cascade_path)
if(self.classifier.empty()):
print("Detector: error loading cascade file " + cascade_path)
def detect(self, gray):
if (len(gray) != 0):
faces = self.classifier.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags = cv2.CASCADE_SCALE_IMAGE) # cv2.cv.CV_HAAR_SCALE_IMAGE in older OpenCV
else:
print("Empty image...")
return faces
if __name__ == '__main__':
if(len(sys.argv) < 3):
print("Cascade path required")
exit()
# /usr/share/jevois-opencv-3.3.0/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml
cascade_path = str(sys.argv[1])
face_detector = Detector(cascade_path)
# /home/guido/Pictures/faces.jpg
img_path = str(sys.argv[2])
img = cv2.imread(img_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# face detection
faces = face_detector.detect(gray)
print ("Faces detected: " + str(len(faces)))
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.imshow("Faces found", img)
cv2.waitKey(0)
| [
"gautier.hattenberger@enac.fr"
] | gautier.hattenberger@enac.fr |
b446ebedf760f662c77f28e0640ccbc1645ef18b | 92b22755e0db57f16fc0620ca64a2bc750eb4df3 | /labs/Lab 11/filters.py | f227d08c57e481422900c682375fe2c9ab294b7f | [] | no_license | wall-daniel/SYSC_1005 | 2a4bf1367e3940e8be4f44bda9cbb7371656939f | f54ad4637f125055195d063b93f9f50ded839190 | refs/heads/master | 2020-03-29T00:29:23.410337 | 2018-12-04T15:59:55 | 2018-12-04T15:59:55 | 149,341,763 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 12,566 | py | """
SYSC 1005 Fall 2018
Filters for Lab 7. All of these filters were presented during lectures.
"""
from Cimpl import *
import random
def grayscale(image):
""" (Cimpl.Image) -> Cimpl.Image
Return a grayscale copy of image.
>>> image = load_image(choose_file())
>>> gray_image = grayscale(image)
>>> show(gray_image)
"""
new_image = copy(image)
for x, y, (r, g, b) in image:
# Use the pixel's brightness as the value of RGB components for the
# shade of gray. These means that the pixel's original colour and the
# corresponding gray shade will have approximately the same brightness.
brightness = (r + g + b) // 3
# or, brightness = (r + g + b) / 3
# create_color will convert an argument of type float to an int
gray = create_color(brightness, brightness, brightness)
set_color(new_image, x, y, gray)
return new_image
def weighted_grayscale(image):
""" (Cimpl.Image) -> Cimpl.Image
Return a grayscale copy of image.
>>> image = load_image(choose_file())
>>> gray_image = grayscale(image)
>>> show(gray_image)
"""
new_image = copy(image)
for x, y, (r, g, b) in image:
# Use the pixel's brightness as the value of RGB components for the
# shade of gray. These means that the pixel's original colour and the
# corresponding gray shade will have approximately the same brightness.
brightness = r * 0.299 + g * 0.587 + b * 0.114
# or, brightness = (r + g + b) / 3
# create_color will convert an argument of type float to an int
gray = create_color(brightness, brightness, brightness)
set_color(new_image, x, y, gray)
return new_image
def detect_edges(image, threshold):
""" (Cimpl.Image, float) -> Cimpl.Image
Return a new image that contains a copy of the original image
that has been modified using edge detection.
>>> image = load_image(choose_file())
>>> filtered = detect_edges(image, 10.0)
>>> show(filtered)
"""
new_image = copy(image)
for x in range(1, get_width(image)):
for y in range(1, get_height(image) - 1):
r, g, b = get_color(image, x, y)
tr, tg, tb = get_color(image, x, y + 1)
if abs((r + g + b) // 3 - (tr + tg + tb) // 3) > threshold:
set_color(new_image, x, y, black)
else:
set_color(new_image, x, y, white)
return new_image
def detect_edges_better(image, threshold):
""" (Cimpl.Image, float) -> Cimpl.Image
Return a new image that contains a copy of the original image
that has been modified using edge detection.
>>> image = load_image(choose_file())
>>> filtered = detect_edges(image, 10.0)
>>> show(filtered)
"""
white = create_color(255, 255, 255)
black = create_color(0, 0, 0)
new_image = copy(image)
for x in range(1, get_width(image) - 1):
for y in range(1, get_height(image) - 1):
r, g, b = get_color(image, x, y)
tr, tg, tb = get_color(image, x, y + 1)
rr, rg, rb = get_color(image, x + 1, y)
contrast_bottom = abs((r + g + b) // 3 - (tr + tg + tb) // 3)
contrast_right = abs((r + g + b) // 3 - (rr + rg + rb) // 3)
if contrast_bottom > threshold or contrast_right > threshold:
set_color(new_image, x, y, white)
else:
set_color(new_image, x, y, black)
return new_image
def blur(image):
""" (Cimpl.Image) -> Cimpl.Image
Return a new image that is a blurred copy of image.
original = load_image(choose_file())
blurred = blur(original)
show(blurred)
"""
target = copy(image)
# Recall that the x coordinates of an image's pixels range from 0 to
# get_width() - 1, inclusive, and the y coordinates range from 0 to
# get_height() - 1.
#
# To blur the pixel at location (x, y), we use that pixel's RGB components,
# as well as the components from the four neighbouring pixels located at
# coordinates (x - 1, y), (x + 1, y), (x, y - 1) and (x, y + 1).
#
# When generating the pixel coordinates, we have to ensure that (x, y)
# is never the location of pixel on the top, bottom, left or right edges
# of the image, because those pixels don't have four neighbours.
#
# As such, we can't use this loop to generate the x and y coordinates:
#
# for y in range(0, get_height(image)):
# for x in range(0, get_width(image)):
#
# With this loop, when x or y is 0, subtracting 1 from x or y yields -1,
# which is not a valid coordinate. Similarly, when x equals get_width() - 1
# or y equals get_height() - 1, adding 1 to x or y yields a coordinate that
# is too large.
for y in range(1, get_height(image) - 1):
for x in range(1, get_width(image) - 1):
# Grab the pixel @ (x, y) and its four neighbours
top_red, top_green, top_blue = get_color(image, x, y - 1)
left_red, left_green, left_blue = get_color(image, x - 1, y)
bottom_red, bottom_green, bottom_blue = get_color(image, x, y + 1)
right_red, right_green, right_blue = get_color(image, x + 1, y)
center_red, center_green, center_blue = get_color(image, x, y)
top_left_red, top_left_green, top_left_blue = get_color(image, x - 1, y - 1)
top_right_red, top_right_green, top_right_blue = get_color(image, x + 1, y - 1)
bottom_left_red, bottom_left_green, bottom_left_blue = get_color(image, x - 1, y + 1)
bottom_right_red, bottom_right_green, bottom_right_blue = get_color(image, x + 1, y + 1)
# Average the red components of the five pixels
new_red = (top_red + left_red + bottom_red +
right_red + center_red + top_left_red
+ top_right_red + bottom_left_red + bottom_right_red) // 9
# Average the green components of the five pixels
new_green = (top_green + left_green + bottom_green +
right_green + center_green + top_left_green
+ top_right_green + bottom_left_green + bottom_right_green) // 9
# Average the blue components of the five pixels
new_blue = (top_blue + left_blue + bottom_blue +
right_blue + center_blue + top_left_blue
+ top_right_blue + bottom_left_blue + bottom_right_blue) // 9
new_color = create_color(new_red, new_green, new_blue)
# Modify the pixel @ (x, y) in the copy of the image
set_color(target, x, y, new_color)
return target
def extreme_contrast(image):
"""
(Cimpl.Image) -> Cimpl.Image
Return a copy of image, maximizing the contrast between
the light and dark pixels.
>>> image = load_image(choose_file())
>>> new_image = extreme_contrast(image)
>>> show(new_image)
"""
new_image = copy(image)
for x, y, (r, g, b) in image:
if r < 128:
r = 0
else:
r = 255
if g < 128:
g = 0
else:
g = 255
if b < 128:
b = 0
else:
b = 255
set_color(new_image, x, y, create_color(r, g, b))
return new_image
def sepia_tint(image):
""" (Cimpl.Image) -> Cimpl.Image
Return a copy of image in which the colours have been
converted to sepia tones.
>>> image = load_image(choose_file())
>>> new_image = sepia_tint(image)
>>> show(new_image)
"""
new_image = copy(image)
for x, y, (r, g, b) in weighted_grayscale(image):
if r < 63:
set_color(new_image, x, y, create_color(r * 1.1, g, b * 0.9))
elif r <= 191:
set_color(new_image, x, y, create_color(r * 1.15, g, b * 0.85))
else:
set_color(new_image, x, y, create_color(r * 1.08, g, b * 0.93))
return new_image
def posterize(image):
""" (Cimpl.Image) -> Cimpl.Image
Return a "posterized" copy of image.
>>> image = load_image(choose_file())
>>> new_image = posterize(image)
>>> show(new_image)
"""
new_image = copy(image)
for x, y, (r, g, b) in image:
set_color(new_image, x, y, create_color(_adjust_component(r), _adjust_component(g), _adjust_component(b)))
return new_image
def _adjust_component(amount):
""" (int) -> int
Divide the range 0..255 into 4 equal-size quadrants,
and return the midpoint of the quadrant in which the
specified amount lies.
>>> _adjust_component(10)
31
>>> _adjust_component(85)
95
>>> _adjust_component(142)
159
>>> _adjust_component(230)
223
"""
if amount > 191:
return 223
if amount > 127:
return 159
if amount > 63:
return 95
return 31
def scatter(image, threshold):
""" (Cimpl.image) -> Cimpl.image
Return a new image that looks like a copy of an image in which the pixels
have been randomly scattered.
>>> original = load_image(choose_file())
>>> scattered = scatter(original)
>>> show(scattered)
"""
# Create an image that is a copy of the original.
new_image = copy(image)
# Visit all the pixels in new_image.
for x, y, (r, g, b) in image:
# Generate the row and column coordinates of a random pixel
# in the original image. Repeat this step if either coordinate
# is out of bounds.
row_and_column_are_in_bounds = False
while not row_and_column_are_in_bounds:
# Generate two random numbers between -10 and 10, inclusive.
rand1 = random.randint(-threshold, threshold)
rand2 = random.randint(-threshold, threshold)
# Calculate the column and row coordinates of a
# randomly-selected pixel in image.
random_column = x + rand1
random_row = y + rand2
# Determine if the random coordinates are in bounds.
if (random_column >= 0 and random_column < image.get_width()) and (random_row >= 0 and random_row < image.get_height()):
#print(str(random_column) + ' ' + str(random_row))
row_and_column_are_in_bounds = True
# Get the color of the randomly-selected pixel.
new_colour = get_color(image, random_column, random_row)
# Use that color to replace the color of the pixel we're visiting.
set_color(new_image, x, y, new_colour)
# Return the scattered image.
return new_image
#-------------------------------------
# A few functions to test the filters.
def test_grayscale(image):
gray_image = grayscale(image)
show(gray_image)
def test_negative(image):
inverted_image = negative(image)
show(inverted_image)
def test_solarize(image):
solarized_image = solarize(image, 64)
show(solarized_image)
solarized_image = solarize(image, 128)
show(solarized_image)
solarized_image = solarize(image, 192)
show(solarized_image)
solarized_image = solarize(image, 256)
show(solarized_image)
def test_black_and_white(image):
b_w_image = black_and_white(image)
show(b_w_image)
def test_black_and_white_and_gray(image):
b_w_g_image = black_and_white_and_gray(image)
show(b_w_g_image)
# print(__name__)
if __name__ == "__main__":
original = load_image(choose_file())
show(original)
test_grayscale(original)
test_negative(original)
test_solarize(original)
test_black_and_white(original)
test_black_and_white_and_gray(original)
| [
"dwall@dhcp-153-111.cu-wireless-students.carleton.ca"
] | dwall@dhcp-153-111.cu-wireless-students.carleton.ca |
014f5ef95b24f912eba396f00c732da8db3287e4 | c3f923f3bba6d60357bee87c716bcf66d3916149 | /TestPy3Tools/winPC/cmdFlushDns.py | 7f6baf7553ed8ca150c7e7f17a2f6519384998f4 | [] | no_license | yuchunhaiGit/pyProject | 514d52db7a0ba2cff8ec516186994236356e0d6a | a982939fdb1679a4d60149fc84eab563fb083b03 | refs/heads/master | 2021-08-28T13:48:06.607143 | 2017-12-12T10:49:15 | 2017-12-12T10:49:15 | 113,149,085 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 138 | py | # coding=utf-8
# @作者:yuchunhai
#@Time:2017/11/29-10:24
#@文件名称:pyProject-cmdFlushDns
import os
os.system(r'ipconfig /flushdns') | [
"18905255025@qq.com"
] | 18905255025@qq.com |
0779310c4d038fb9d6ba8e6af98bd44b0a8adc33 | 6ce155f14c3e758ef21417a6145535c3976309e6 | /exercise_1/main2.py | d81b1ec6a3ed031e51281526b95b94e5b7f7d7c2 | [] | no_license | brendan-martin/CompMod-excercise_1 | c628d71a6c8c2ed1daa57b74173975c5a74d1d3e | 254f79b1f6bfef3a8d04cbce5f29a6079981f758 | refs/heads/master | 2020-04-01T08:14:02.416962 | 2018-10-30T12:18:22 | 2018-10-30T12:18:22 | 153,022,438 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,284 | py | from vector_class import Vectors
import math as m
def main():
#ask user for components of the first vector
component_1=input("The first component of the vector is:")
component_2=input("The second component of the vector is:")
component_3=input("The third component of the vector is:")
vector_1=[component_1,component_2,component_3]
print("the first vector is"+str(vector_1))
#ask user for components of the second vector
component2_1=input("The first component of the second vector is:")
component2_2=input("The second component of the second vector is:")
component2_3=input("The third component of the second vector is:")
vector_2=[component2_1,component2_2,component2_3]
print("the second vector is"+str(vector_2))
#ask user for a scalar scalar multiple, c
c=input("my scalar multiple is:")
#initialise the first vector as an instance of the class Vectors
instance_vector=Vectors(vector_1)
#use mag property of vectors to compute the magnitude of the first vector
magnitude=instance_vector.mag
print("the magnitude of the first vector is:"+str(magnitude))
#use mag2 property of vectors to compute the squared magnitude of the first vector
magnitude2=instance_vector.mag2
print("the squared magnitude of the first vector is:"+str(magnitude2))
#use class method to compute dot product of the two vectors
dot_product=instance_vector.dot_prod(vector_2)
print("the dot product of the two vectors is:"+str(dot_product))
#find scalar multiple of first vector
multiple=instance_vector.scalar_multiple(c)
print("the scalar multiple of the first vector is:"+str(multiple))
#use class method "cross" to compute cross product of the two vectors
print("the cross product of the two vectors is:"+str(instance_vector.cross(vector_2)))
#use class method "sum" to add the two vectors
print("the sum of the two vectors is:"+str(instance_vector.sum(vector_2)))
#use class method "diff" the subtract the first vector from the second
print("the second vector minus the first is:"+str(instance_vector.diff(vector_2)))
#check whether the two vectors are the same
print("are the two vectors the same?"+str(instance_vector.same(vector_2)))
main()
| [
"noreply@github.com"
] | brendan-martin.noreply@github.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.