text string | size int64 | token_count int64 |
|---|---|---|
# -*- coding: utf-8 -*-
# This program is designed to create XML sidecar files for harvesting metadata into Mediaflux.
#
# Author: Jay van Schyndel
# Date: 02 May 2017.
#
# Significant modifications done by: Daniel Baird
# Date: 2018 and early 2019
#
# Scenario. Metadata is stored in an MS Excel file in various columns.
# Excel has been used to create a new column representing the metadata in the required XML format.
# The file is then saved as a CSV.
# This program will open the CSV file, read the appropriate column and save the XML into a sidecar file based on the name of the data file.
# Note the program assumes there is a header row in the CSV file. It skips processesing the first row.
#
# new example: python ./scripts/csvColumnToXMLFile.py "./rawdata/excel/PacELF Phases 1_2_3 13Dec2018.csv" "/Users/pvrdwb/projects/PacELFDocs/PacELFphase3/" ../docs --location="HardcopyLocation2018"
#
# old example: python csvColumnToXMLFile.py rawSpreadsheet/PacELF_Phase_1_AND_2.csv ~/projects/PacELFDocs/PacELF\ PDFs ./docs
#
import os
import re
import sys
import csv
import shutil
import argparse
parser = argparse.ArgumentParser(description="Create XML sidecar files from a CSV file")
parser.add_argument(
"metadata_csv", metavar="metadataCSV", help="CSV file containing the XML"
)
parser.add_argument(
"src_folder", metavar="sourceFolder", help="directory containing the source files"
)
parser.add_argument(
"dest_folder", metavar="destinationFolder", help="Path of the destination folder"
)
parser.add_argument(
"--title",
metavar="titleColumn",
help="Column containing the title",
default="Title",
)
parser.add_argument(
"--xml", metavar="xmlColumn", help="Column containing the XML", default="XML"
)
parser.add_argument(
"--access",
metavar="accessColumn",
help="Column containing the Access Rights",
default="Access Rights",
)
parser.add_argument(
"--type", metavar="accessColumn", help="Column containing the Type", default="Type"
)
parser.add_argument(
"--file",
metavar="fileColumn",
help="Column containing the data file name",
default="PDF",
)
parser.add_argument(
"--location",
metavar="primaryLocationColumn",
help="Column containing the primary hardcopy location",
default="Hardcopy Locations",
)
try:
args = parser.parse_args()
except:
sys.exit(0)
print("Processing CSV file: ", args.metadata_csv)
# this is all the location typos we've found
loc_replacements = {}
loc_replacements[r"JCU WHOCC Ichimori collectoin"] = r"JCU WHOCC Ichimori collection"
loc_replacements[r"JCU WHOCC Ichimori Collection"] = r"JCU WHOCC Ichimori collection"
loc_replacements[r"JCU WHOCC ICHIMORI Collection"] = r"JCU WHOCC Ichimori collection"
loc_replacements[r"JCU WHO Ichimori Collection"] = r"JCU WHOCC Ichimori collection"
loc_replacements[r"JCU WHO Ichimori collection"] = r"JCU WHOCC Ichimori collection"
loc_replacements[r"JCU WHO CC Ichimori Collection"] = r"JCU WHOCC Ichimori collection"
loc_replacements[r"JCUWHOCC Ichimori collection"] = r"JCU WHOCC Ichimori collection"
loc_replacements[r"JCUWHOCC Ichimori Collection"] = r"JCU WHOCC Ichimori collection"
loc_replacements[r"Ichimori Collection"] = r"JCU WHOCC Ichimori collection"
loc_replacements[r"JCU WHOCC Nagasaki Collection"] = r"JCU WHOCC Ichimori collection"
loc_replacements[r"JCU WHOCC Nagasaki collection"] = r"JCU WHOCC Ichimori collection"
loc_replacements[r"WHO DPS Suva"] = r"WHO DPS Fiji"
loc_replacements[r"WHO HQ Geneva"] = r"WHO Geneva"
# -----------------------------------------------------------------------------
def clean_hc_location(loc):
if loc in loc_replacements:
return loc_replacements[loc]
else:
return loc
# -----------------------------------------------------------------------------
def clean_xml_content(xml_string):
"""
Given some xml in string form that we got right from the spreadsheet,
clean it up
"""
for old_loc in loc_replacements:
old = r"<hardcopy_location>([^<]*)" + old_loc + r"([^<]*)</hardcopy_location>"
new = (
r"<hardcopy_location>\1"
+ loc_replacements[old_loc]
+ r"\2</hardcopy_location>"
)
xml_string = re.sub(old, new, xml_string)
return xml_string
# -----------------------------------------------------------------------------
def get_location_info(location):
locations = {}
locations[
"JCU WHOCC Ichimori collection"
] = "James Cook University, Bldg 41 Rm 207, Townsville, Queensland 4811, Australia"
locations[
"JCU WHOCC"
] = "James Cook University, Bldg 41 Rm 207, Townsville, Queensland 4811, Australia"
locations[
"JCU Cairns (PMG)"
] = "James Cook University, Bldg E1 Rm 003C, Cairns, Queensland 4870, Australia"
locations[
"WHO DPS Fiji"
] = "World Health Organization, Level 4, Provident Plaza One, Downtown Boulevard, 33 Ellery Street, Suva, Fiji"
locations[
"WHO WPRO Manila"
] = "P.O. Box 2932, United Nations Ave. cor. Taft Ave, 1000 Manila, Philippines"
locations["WHO Geneva"] = "Avenue Appia 20, 1202 Geneva, Switzerland"
locations[
"JCU library"
] = "James Cook University, Eddie Koiko Mabo library, Bldg 18, Townsville, Queensland 4811, Australia"
return locations[location]
# -----------------------------------------------------------------------------
with open(args.metadata_csv, "rb") as csvfile:
metadataReader = csv.DictReader(csvfile, delimiter=",")
counts = {
"rows": 0,
"docs": 0,
"restrict": 0,
"hc": 0,
"restrict_hc": 0,
"write_err": 0,
"copy_err": 0,
"sidecar_err": 0,
"no_doc": 0,
"doc_missing": 0,
"sidecars": 0,
}
for row in metadataReader:
counts["rows"] += 1
# Skipping first row as it contains the header row.
if counts["rows"] > 1:
real_file = row[args.file]
xml_content = row[args.xml]
# clean the XML (this part is special to the specific data we're getting)
xml_content = clean_xml_content(xml_content)
doc_access = row[args.access]
doc_type = row[args.type]
hc_location = (
row[args.location].split(";")[0].strip()
) # semicolon separated list -- get the first one
hc_location = clean_hc_location(hc_location)
doc_title = row[args.title]
# bail if there's no title
if doc_title == "":
continue
else:
# print("LOOKING: " + doc_title)
counts["docs"] += 1
pass
# destination for the xml file
flat_file_name, file_ext = os.path.splitext(real_file)
# maybe there are subdirs in the file name, we'll flatten those out
flat_file_name = flat_file_name.replace("/", "#")
# copy the file there
# maybe we have to fake up the content coz it's restricted or something
fake_content = False
if doc_access == "Restricted" and doc_type == "Hardcopy" and hc_location:
# it's a restricted hardcopy with a location
counts["restrict_hc"] += 1
fake_content = "".join(
[
'The document "',
doc_title,
'" is unavailable due to data sensitivity, publisher restrictions or is not digitised. ',
"Please e-mail pacelf@jcu.edu.au or write to:\n\n ",
get_location_info(hc_location),
"\n\nto negotiate gaining access to this item.",
]
)
elif (
doc_access == "Restricted"
and doc_type == "Hardcopy"
and not hc_location
):
# it's a restricted hardcopy with no location
counts["restrict_hc"] += 1
fake_content = "".join(
[
'The document "',
doc_title,
'" is unavailable due to data sensitivity, publisher restrictions or is not digitised. ',
"Please e-mail pacelf@jcu.edu.au to negotiate gaining access to this item.",
]
)
elif doc_access != "Restricted" and doc_type == "Hardcopy" and hc_location:
# it's an unrestricted hardcopy with a location
counts["hc"] += 1
fake_content = "".join(
[
'The document "',
doc_title,
'" is not available in digital format. ',
"A copy is held at:\n\n ",
get_location_info(hc_location),
"\n\nplease write or email pacelf@jcu.edu.au to request a copy.",
]
)
elif (
doc_access != "Restricted"
and doc_type == "Hardcopy"
and not hc_location
):
# it's an unrestricted hardcopy with no location
counts["hc"] += 1
fake_content = "".join(
[
'The document "',
doc_title,
'" is not available in digital format. ',
"Please e-mail pacelf@jcu.edu.au to request a copy.",
]
)
elif doc_access == "Restricted" and doc_type != "Hardcopy":
# it's a restricted PDF
counts["restrict"] += 1
fake_content = "".join(
[
'The document "',
doc_title,
'" is unavailable due to data sensitivity, publisher restrictions or is not digitised. ',
"Please e-mail pacelf@jcu.edu.au to negotiate gaining access to this item.",
]
)
elif flat_file_name == "":
# any other situation where there's no doc
counts["no_doc"] += 1
fake_content = "".join(
[
'The document "',
doc_title,
'" is not available in digital format. ',
"Please e-mail pacelf@jcu.edu.au to discuss access.",
]
)
if flat_file_name == "":
flat_file_name = "PacELF_Phase2_" + str(counts["rows"])
#
# by now have fake content to use, or we expect the doc to be available.
#
# destination for the real file
real_dest_file = os.path.join(args.dest_folder, flat_file_name + file_ext)
# destination for the proxy document (.txt extension)
fake_dest_path = os.path.join(args.dest_folder, flat_file_name + ".txt")
if fake_content:
# write the fake content, if we have it
try:
file = open(fake_dest_path, "w")
file.write(fake_content)
file.close()
# print(unicode('PROXIED: ') + unicode(doc_title))
except ValueError as e:
counts["write_err"] += 1
print("Couldn't write content to: " + real_dest_file)
print(e)
else:
# we didn't have fake content, so use the real doc/pdf
real_file_path = os.path.join(args.src_folder, real_file)
if real_file == "":
print('No doc file specified for "' + doc_title + '"')
counts["no_doc"] += 1
continue
# try to copy the file --------
# first let's get some common error versions of the filename
fn_to_try = [real_file_path]
fn_to_try.append(
re.sub(r"\.pdf$", r" .pdf", real_file_path)
) # space before the pdf
fn_to_try.append(re.sub(r"\\", r"/", real_file_path)) # other slashes
fn_to_try.append(re.sub(r"$", r".pdf", real_file_path)) # add .pdf
fn_to_try.append(
re.sub(
r"Multicountry Pacific", r"multicountry pacific", real_file_path
)
) # upper case
fn_to_try.append(
re.sub(
r"Mulitcountry Pacific", r"multicountry pacific", real_file_path
)
) # typo & upper case
# some straight fixes
fn_to_try.append(
re.sub(
r"\\\.pdf$",
r"PDF version\.pdf",
re.sub(
r"Mulitcountry Pacific",
r"multicountry pacific",
real_file_path,
),
)
) # two fixes
fn_to_try.append(
re.sub(
r"PacELF_102", r"PacELF_102 Jarno et al 2006", real_file_path
)
) # add author
fn_to_try.append(
re.sub(
r"PacELF_448",
r"PacELF_448 Andrews et al 2012 PLOS PATHOGENS ",
real_file_path,
)
)
fn_to_try.append(
re.sub(
r"PacELF_493",
r"PacELF_493 Brelsfoard et al 2008 PLOS NTDs Interspecific hybridization South Pacific filariasis vectors",
real_file_path,
)
)
fn_to_try.append(
re.sub(
r"PacELF_508",
r"PacELF_508 Burkot et al 2013 MAL J Barrier screens",
real_file_path,
)
)
fn_to_try.append(
re.sub(
r"PacELF_314",
r"PacELF_314 Stolk et al 2013 PLOS NTDs",
real_file_path,
)
)
fn_to_try.append(
re.sub(
r"PacELF_317",
r"PacELF_317 Debrah et al 2006 PLOS PATHOGENS Doxycycline reduces VGF and improves pathology LF",
real_file_path,
)
)
fn_to_try.append(
re.sub(
r"PacELF_319",
r"PacELF_319 Hooper et al 2014 PLOS NTDs Asseesing progress in reducing at risk population after 13 years",
real_file_path,
)
)
fn_to_try.append(
re.sub(
r"\\2001-05 PRG Fiji May-Jun 2011\\",
r"/2011-05 PRG Fiji May-Jun 2011/",
real_file_path,
)
)
fn_to_try.append(
re.sub(
r"PacELF_414 WPRO PMM 2011 report_2011 Oct 31\.pdf",
r"PacELF_414 WPRO PMM 2011 report_2011 Oct 31 PDF version.pdf",
real_file_path,
)
)
fn_to_try.append(
re.sub(
r"Multicountry Pacific/PacELF_585",
r"French Polynesia/PacELF_585",
real_file_path,
)
)
fn_to_try.append(
re.sub(
r"Manson-Bahr 1912 FIlariasis and elephantiasis in Fiji LSHTM b21356658",
r"Manson-Bahr 1912 FIlariasis and elephantiasis in Fiji LSHTM b21356658",
real_file_path,
)
)
# find the first that is a file
for pth in fn_to_try:
if os.path.isfile(pth):
break
# try copying that
if os.path.isfile(pth):
try:
shutil.copyfile(pth, real_dest_file)
# print(' COPIED: ' + doc_title)
except shutil.Error as e:
counts["copy_err"] += 1
print("Could not copy doc: " + pth)
print(e)
else:
print(
"Could not find doc file for title: '"
+ doc_title
+ "', file: "
+ pth
)
counts["doc_missing"] += 1
#
# Now we've got content there, make the xml sidecar file
#
xml_dest_file = flat_file_name + ".xml"
xml_dest_path = args.dest_folder + "/" + xml_dest_file
try:
file = open(xml_dest_path, "w")
file.write(xml_content)
file.close()
counts["sidecars"] += 1
except ValueError as e:
counts["sidecar_err"] += 1
print("Oops, this one is dodgy: " + xml_dest_path)
print("ValueError: ", e)
print("\nSummary:")
print(
"".join(
[
" ",
str(counts["rows"]),
" rows read: ",
str(counts["docs"]),
" documents processed, ",
str(counts["sidecars"]),
" metadata sidecars produced;",
"\n ",
str(counts["hc"]),
" hard copies, ",
str(counts["restrict"]),
" restricted docs, ",
str(counts["restrict_hc"]),
" restricted hard copies;",
"\n ",
str(counts["copy_err"]),
" copy errors, ",
str(counts["write_err"]),
" write errors, ",
str(counts["sidecar_err"]),
" sidecar errors, ",
str(counts["doc_missing"]),
" docs not locatable, ",
str(counts["no_doc"]),
" docs not listed.",
"\n",
]
)
)
| 18,839 | 5,474 |
from django.shortcuts import render
from django.shortcuts import HttpResponse
from .forms import FoodFitnessForm
from django.contrib.auth.models import User
# function to test with
def index(request):
return HttpResponse("You made it.")
# function to create new user
def createUser(request):
form = FoodFitnessForm(request.POST or None)
context = {
"form": form
}
if request.method == "POST":
print(request.POST)
User.objects.create_user(request.POST["username"], request.POST["calories"], request.POST["date"])
return render(request, "authenticationCwApp/confirmUser.html")
return render(request, 'authenticationCwApp/createUser.html', context)
# function to confirm new user
def confirmUser(request):
form = FoodFitnessForm(request.GET or None)
context = {
"form": form
}
if request.method == 'GET':
User.objects.create_user(request.GET["username"], "", request.GET["calories"], request.GET["date"])
form.save()
return HttpResponse("New Food Calorie Tracker Created!!!!!")
return render(request, "authenticationCwApp/confirmUser.html", context)
| 1,147 | 329 |
# Conta somente números pares
for c in range(2, 51, 2):
print(c, end=' ')
print("Acabou!")
| 98 | 46 |
from __future__ import print_function
# A script to help you with manipulating CSV-files. This is especially necessary when dealing with
# CSVs that have more than 65536 lines because those can not (yet) be opened in Excel or Numbers.
# This script works with two files from ourworldindata.org:
# https://ourworldindata.org/age-structure and https://ourworldindata.org/gender-ratio
# This script MERGES two CSVs.
#
# Usage:
# - Adjust filenames and delimiters.
# - Variable matchColumns: names of the matching columns in the first CSV
# - Variable withColumns: names of the matching columns in the second CSV
# - Variable copyColumns: which columns from the second CSV should be copied
# to the first. If copyColumns is [], it copies all cloumns except
# what's defined in the variable 'withColumn'
# Examples:
# copyColums = ['latitude', 'longitude'] Will copy those two columns
# copyColums = [] Will copy all columns
# ---------------------------------------------
# Change the parameters according to your task:
# Give the name of the CSV file where you want to add columns
readFileName1 = 'worlddata-median-age.csv' # <--- Adjust here
# What delimiter is used in this CSV? Usually ',' or ';'
readDelimiter1 = ',' # <--- Adjust here (have a look in your source CSV)
# Give the name of the CSV file that gives additional values
readFileName2 = 'worlddata-share-population-female.csv' # <--- Adjust here
# What delimiter is used in this CSV? Usually ',' or ';'
readDelimiter2 = ',' # <--- Adjust here (have a look in your source CSV)
# The result will be a new CSV file:
writeFileName = 'worlddata_merged.csv' # <--- Adjust here (has to be different than readFileName1)
# You can give a different delimiter for the result.
writeDelimiter = ',' # <--- Adjust here (';' is usually good)
matchColumns = ['Code', 'Year'] # <--- Adjust here
withColumns = ['Code', 'Year'] # <--- Adjust here
copyColumns = ['PercentFemale'] # <--- Adjust here
# # Second example for merging longitude/latitude data to a file with countries
# readFileName1 = 'wintergames_winners.csv'
# readDelimiter1 = ';'
# readFileName2 = 'longitude-latitude.csv'
# readDelimiter2 = ','
# writeFileName = 'wintergame_winners_merged.csv'
# writeDelimiter = ';'
# matchColumns = ['NOC']
# withColumns = ['IOC']
# copyColumns = ['latitude', 'longitude']
# ----------------------------------------------
# No need to change anything from here on ...
import csv
from collections import OrderedDict
readFile1 = open(readFileName1)
reader1 = csv.DictReader(readFile1, delimiter=readDelimiter1)
rows1 = list(reader1)
readFile2 = open(readFileName2)
reader2 = csv.DictReader(readFile2, delimiter=readDelimiter2)
rows2 = list(reader2)
writeFile = open(writeFileName, 'w')
writer = csv.writer(writeFile, delimiter=writeDelimiter)
# This writes the field names to the result.csv
headings1 = list(reader1.fieldnames)
if copyColumns == []:
copyColumns = list(filter(lambda x: x != withColumn, reader.fieldnames))
writer.writerow(headings1 + copyColumns)
# create dict from second csv to speed up finding stuff
print('Preparing merge')
print('----------------------')
dic = {}
unique = True
for row in rows2:
key = tuple(row[x] for x in withColumns)
# for col in withColumns:
# key = key + row[col] + '__'
if key != '':
if key in dic:
unique = False
else:
dic[key] = row
if (not unique):
print('Warning: The columns "%s" in the second CSV has duplicate values which could result in incorrect matching.' % withColumns)
print('----------------------')
print('Merging')
failed = []
numRows = 0
perc = 0
for i, row in enumerate(rows1):
if float(i) / len(rows1) > perc:
print('#', end='')
perc = perc + 0.01
values = []
val = tuple(row[x] for x in matchColumns)
# for col in matchColumns:
# val = val + row[col] + '__'
for key in headings1:
values.append(row[key])
for key in copyColumns:
try:
values.append(dic[val][key])
except:
if (not val in failed):
failed.append(val)
writer.writerow(values)
print('\n----------------------')
print('%d value(s) could not be found in the second CSV, so matching was not possible for every row.' % len(failed))
print("These values couldn't be matched:")
print(failed[:100])
if (len(failed) > 100):
print('... and %d more' % (len(failed) - 100))
| 4,763 | 1,388 |
go_to_tender_page = "Live Tenders"
search_bar = "#sr_buyer_chzn > a > span"
all_dept_names = "#sr_buyer_chzn > div > ul > li:nth-of-type(n+1)"
search_button = '#frm_sr > div.actionBtn > input[type="button"]:nth-child(1)'
type_name = '#sr_buyer_chzn > div > div > input[type="text"]'
scroll_down = "window.scrollTo(0, document.body.scrollHeight);"
lister_scope = "#tblSummary > tbody > tr:nth-of-type(2n+2)"
tender_count = "#uipage > div.bpanel > div.uisummary > form > div:nth-child(1)"
page_count = "#selMQ6_chzn > div > ul > li"
work_name_scope = "#tblSummary > tbody > tr:nth-of-type(2n+3)"
work_name = "td"
tender_no = "td:nth-child(4)"
action = "td:nth-child(2) > a"
show_form = "#action-links > ul > li:nth-child(1) > a"
details_page = "body > div.panel > div.bpanel.p_false > div.info > table > tbody > tr:nth-child(1) > td:nth-child(4) > a"
show_hidden_css = "body > div.panel > div.bpanel > div.summary > form > div.right > a"
random_click = "td:nth-child(3)"
details_scope = {
"Name of Work": "#descOfWorkspan",
"Tender No": "#tenderNumberspan",
"EMD": "#emdspan",
"Amount of Contract (PAC)": "#estimatedCostspan",
"Cost of Document": "#formFeespan",
"Purchase of Tender Start Date": "#recvOfAppFromDatespan",
"Purchase of Tender End Date": "#recvOfAppToDatespan",
"Bid Submission End Date": "#receiptOfTendToDatespan"
}
next_page = "#uipage > div.bpanel > div.uisummary > form > div.paginationLinks > div > a:nth-of-type(n+2)"
settings = "chrome://settings-frame/content"
enable_autodownload = "#content-settings-page > div.content-area > section:nth-child(13) > div > div:nth-child(1) > label > span > span:nth-child(1)"
finish = "#content-settings-overlay-confirm"
| 1,713 | 667 |
"""
Module serializes `Profile` model
:generates JSON from fields in `Profile` model
"""
import logging
from rest_framework import serializers
from authors.apps.authentication.serializers import UserSerializer
from authors.apps.profiles.models import Profile, Following
logger = logging.getLogger(__name__)
class ProfileSerializer(serializers.ModelSerializer):
"""
Generate JSON from `Profile model
"""
class Meta:
"""
Map fields in `Profile` model with serializer's JSON params
"""
model = Profile
# Collect all the fields in `Profile` model
fields = '__all__'
# read only fiels - not editable
read_only_fields = [
'user',
]
def update(self, instance, prof_data):
"""
Update profile items
"""
# For every item provided in the payload,
# amend the profile accordingly
for (key, value) in prof_data.items():
setattr(instance.profile, key, value)
instance.save()
return instance
class BasicProfileSerializer(serializers.ModelSerializer):
user = serializers.SerializerMethodField()
following = serializers.SerializerMethodField()
class Meta:
model = Profile
fields = ('user', 'bio', 'profile_photo', 'following')
def get_user(self, obj):
"""
return the username of user
:param obj:
:return:
"""
return obj.user.username
def get_following(self, obj):
"""
get current logged in user and verify if they are followers
:param obj:
:return:
"""
requester = self.context['user']
logger.debug("*" * 100)
logger.debug(requester)
# get or create a profile for the current user
# this will return a queryset of length 1
profile = Profile.objects.get_or_create(user=requester)
profile = profile[0]
return profile.is_followed(obj.user)
class FollowingSerializer(serializers.ModelSerializer):
follower = UserSerializer()
followed = UserSerializer()
class Meta:
model = Following
exclude = ('id', 'modified')
class FollowedSerializer(serializers.ModelSerializer):
followed = UserSerializer()
class Meta:
model = Following
exclude = ('id', 'modified', 'follower')
class FollowersSerializer(serializers.ModelSerializer):
follower = UserSerializer()
class Meta:
model = Following
exclude = ('id', 'modified', 'followed')
| 2,590 | 675 |
from django import forms
import cass
class LoginForm(forms.Form):
username = forms.CharField(max_length=30)
password = forms.CharField(widget=forms.PasswordInput(render_value=False))
def clean(self):
username = self.cleaned_data['username']
password = self.cleaned_data['password']
try:
user = cass.get_user_by_username(username)
except cass.DatabaseError:
raise forms.ValidationError(u'Invalid username and/or password')
if user.password != password:
raise forms.ValidationError(u'Invalid username and/or password')
return self.cleaned_data
def get_username(self):
return self.cleaned_data['username']
class RegistrationForm(forms.Form):
username = forms.RegexField(regex=r'^\w+$', max_length=30)
password1 = forms.CharField(widget=forms.PasswordInput(render_value=False))
password2 = forms.CharField(widget=forms.PasswordInput(render_value=False))
def clean_username(self):
username = self.cleaned_data['username']
try:
cass.get_user_by_username(username)
raise forms.ValidationError(u'Username is already taken')
except cass.DatabaseError:
pass
return username
def clean(self):
if ('password1' in self.cleaned_data and 'password2' in self.cleaned_data):
password1 = self.cleaned_data['password1']
password2 = self.cleaned_data['password2']
if password1 != password2:
raise forms.ValidationError(
u'You must type the same password each time')
return self.cleaned_data
def save(self):
username = self.cleaned_data['username']
password = self.cleaned_data['password1']
cass.save_user(username, password)
return username
| 1,849 | 506 |
import os
# os.environ["OMP_NUM_THREADS"] = "16"
import logging
logging.basicConfig(filename=snakemake.log[0], level=logging.INFO)
import pandas as pd
import numpy as np
# seak imports
from seak.data_loaders import intersect_ids, EnsemblVEPLoader, VariantLoaderSnpReader, CovariatesLoaderCSV
from seak.scoretest import ScoretestNoK
from seak.lrt import LRTnoK, pv_chi2mixture, fit_chi2mixture
from pysnptools.snpreader import Bed
import pickle
import sys
from util.association import BurdenLoaderHDF5
from util import Timer
class GotNone(Exception):
pass
# set up the covariatesloader
covariatesloader = CovariatesLoaderCSV(snakemake.params.phenotype,
snakemake.input.covariates_tsv,
snakemake.params.covariate_column_names,
sep='\t',
path_to_phenotypes=snakemake.input.phenotypes_tsv)
# initialize the null models
Y, X = covariatesloader.get_one_hot_covariates_and_phenotype('noK')
null_model_score = ScoretestNoK(Y, X)
null_model_lrt = LRTnoK(X, Y)
# set up function to filter variants:
def maf_filter(mac_report):
# load the MAC report, keep only observed variants with MAF below threshold
mac_report = pd.read_csv(mac_report, sep='\t', usecols=['SNP', 'MAF', 'Minor', 'alt_greater_ref'])
if snakemake.params.filter_highconfidence:
vids = mac_report.SNP[(mac_report.MAF < snakemake.params.max_maf) & (mac_report.Minor > 0) & ~(mac_report.alt_greater_ref.astype(bool)) & (mac_report.hiconf_reg.astype(bool))]
else:
vids = mac_report.SNP[(mac_report.MAF < snakemake.params.max_maf) & (mac_report.Minor > 0) & ~(mac_report.alt_greater_ref.astype(bool))]
# this has already been done in filter_variants.py
# load the variant annotation, keep only variants in high-confidece regions
# anno = pd.read_csv(anno_tsv, sep='\t', usecols=['Name', 'hiconf_reg'])
# vids_highconf = anno.Name[anno.hiconf_reg.astype(bool).values]
# vids = np.intersect1d(vids, vids_highconf)
return mac_report.set_index('SNP').loc[vids]
def get_regions():
# load the results, keep those below a certain p-value
results = pd.read_csv(snakemake.input.results_tsv, sep='\t')
kern = snakemake.params.kernels
if isinstance(kern, str):
kern = [kern]
pvcols_score = ['pv_score_' + k for k in kern ]
pvcols_lrt = ['pv_lrt_' + k for k in kern]
statcols = ['lrtstat_' + k for k in kern]
results = results[['gene', 'n_snp', 'cumMAC', 'nCarrier'] + statcols + pvcols_score + pvcols_lrt]
# get genes below threshold
genes = [results.gene[results[k] < 1e-7].values for k in pvcols_score + pvcols_lrt ]
genes = np.unique(np.concatenate(genes))
if len(genes) == 0:
return None
# set up the regions to loop over for the chromosome
regions = pd.read_csv(snakemake.input.regions_bed, sep='\t', header=None, usecols=[0 ,1 ,2 ,3, 5], dtype={0 :str, 1: np.int32, 2 :np.int32, 3 :str, 5:str})
regions.columns = ['chrom', 'start', 'end', 'name', 'strand']
regions['strand'] = regions.strand.map({'+': 'plus', '-': 'minus'})
regions = regions.set_index('name').loc[genes]
regions = regions.join(results.set_index('gene'), how='left').reset_index()
return regions
# genotype path, vep-path:
assert len(snakemake.params.ids) == len (snakemake.input.bed), 'Error: length of chromosome IDs does not match length of genotype files'
geno_vep = zip(snakemake.params.ids, snakemake.input.bed, snakemake.input.vep_tsv, snakemake.input.ensembl_vep_tsv, snakemake.input.mac_report, snakemake.input.h5_lof, snakemake.input.iid_lof, snakemake.input.gid_lof)
# get the top hits
regions_all = get_regions()
if regions_all is None:
logging.info('No genes pass significance threshold, exiting.')
sys.exit(0)
# where we store the results
stats = []
i_gene = 0
# enter the chromosome loop:
timer = Timer()
for i, (chromosome, bed, vep_tsv, ensembl_vep_tsv, mac_report, h5_lof, iid_lof, gid_lof) in enumerate(geno_vep):
if chromosome.replace('chr','') not in regions_all.chrom.unique():
continue
# set up the ensembl vep loader for the chromosome
spliceaidf = pd.read_csv(vep_tsv,
sep='\t',
usecols=['name', 'chrom', 'end', 'gene', 'max_effect', 'DS_AG', 'DS_AL', 'DS_DG', 'DS_DL', 'DP_AG', 'DP_AL', 'DP_DG', 'DP_DL'],
index_col='name')
# get set of variants for the chromosome:
mac_report = maf_filter(mac_report)
filter_vids = mac_report.index.values
# filter by MAF
keep = intersect_ids(filter_vids, spliceaidf.index.values)
spliceaidf = spliceaidf.loc[keep]
spliceaidf.reset_index(inplace=True)
# filter by impact:
spliceaidf = spliceaidf[spliceaidf.max_effect >= snakemake.params.min_impact]
# set up the regions to loop over for the chromosome
regions = regions_all.copy()
# discard all genes for which we don't have annotations
gene_ids = regions.name.str.split('_', expand=True) # table with two columns, ensembl-id and gene-name
regions['gene'] = gene_ids[1] # this is the gene name
regions['ensembl_id'] = gene_ids[0]
regions.set_index('gene', inplace=True)
genes = intersect_ids(np.unique(regions.index.values), np.unique(spliceaidf.gene)) # intersection of gene names
regions = regions.loc[genes].reset_index() # subsetting
regions = regions.sort_values(['chrom', 'start', 'end'])
# check if the variants are protein LOF variants, load the protein LOF variants:
ensemblvepdf = pd.read_csv(ensembl_vep_tsv, sep='\t', usecols=['Uploaded_variation', 'Gene'])
# this column will contain the gene names:
genes = intersect_ids(np.unique(ensemblvepdf.Gene.values), regions.ensembl_id) # intersection of ensembl gene ids
ensemblvepdf = ensemblvepdf.set_index('Gene').loc[genes].reset_index()
ensemblvepdf['gene'] = gene_ids.set_index(0).loc[ensemblvepdf.Gene.values].values
# set up the merge
ensemblvepdf.drop(columns=['Gene'], inplace=True) # get rid of the ensembl ids, will use gene names instead
ensemblvepdf.rename(columns={'Uploaded_variation': 'name'}, inplace=True)
ensemblvepdf['is_plof'] = 1.
ensemblvepdf = ensemblvepdf[~ensemblvepdf.duplicated()] # if multiple ensembl gene ids map to the same gene names, this prevents a crash.
# we add a column to the dataframe indicating whether the variant is already annotated as protein loss of function by the ensembl variant effect predictor
spliceaidf = pd.merge(spliceaidf, ensemblvepdf, on=['name', 'gene'], how='left', validate='one_to_one')
spliceaidf['is_plof'] = spliceaidf['is_plof'].fillna(0.).astype(bool)
# initialize the loader
# Note: we use "end" here because the start + 1 = end, and we need 1-based coordiantes (this would break if we had indels)
eveploader = EnsemblVEPLoader(spliceaidf['name'], spliceaidf['chrom'].astype('str') + ':' + spliceaidf['end'].astype('str'), spliceaidf['gene'], data=spliceaidf[['max_effect', 'is_plof', 'DS_AG', 'DS_AL', 'DS_DG', 'DS_DL', 'DP_AG', 'DP_AL', 'DP_DG', 'DP_DL']].values)
# set up the variant loader (splice variants) for the chromosome
plinkloader = VariantLoaderSnpReader(Bed(bed, count_A1=True, num_threads=4))
plinkloader.update_variants(eveploader.get_vids())
plinkloader.update_individuals(covariatesloader.get_iids())
# set up the protein LOF burden loader
bloader_lof = BurdenLoaderHDF5(h5_lof, iid_lof, gid_lof)
bloader_lof.update_individuals(covariatesloader.get_iids())
# set up the splice genotype + vep loading function
def get_splice(interval):
try:
V1 = eveploader.anno_by_interval(interval, gene=interval['name'].split('_')[1])
except KeyError:
raise GotNone
if V1.index.empty:
raise GotNone
vids = V1.index.get_level_values('vid')
V1 = V1.droplevel(['gene'])
temp_genotypes, temp_vids = plinkloader.genotypes_by_id(vids, return_pos=False)
temp_genotypes -= np.nanmean(temp_genotypes, axis=0)
G1 = np.ma.masked_invalid(temp_genotypes).filled(0.)
ncarrier = np.sum(G1 > 0.5, axis=0)
cummac = mac_report.loc[vids].Minor
# spliceAI max score
weights = V1[0].values.astype(np.float64)
is_plof = V1[1].values.astype(bool)
splice_preds_all = V1.iloc[:,2:]
splice_preds_all.columns = ['DS_AG', 'DS_AL', 'DS_DG', 'DS_DL', 'DP_AG', 'DP_AL', 'DP_DG', 'DP_DL']
# "standardized" positions -> codon start positions
# pos = V1[0].values.astype(np.int32)
return G1, vids, weights, ncarrier, cummac, is_plof, splice_preds_all
# set up the protein-LOF loading function
def get_plof(interval):
try:
G2 = bloader_lof.genotypes_by_id(interval['name']).astype(np.float)
except KeyError:
G2 = None
return G2
# set up the test-function for a single gene
def test_gene(interval, seed):
pval_dict = {}
pval_dict['gene'] = interval['name']
called = []
def pv_score(GV):
pv = null_model_score.pv_alt_model(GV)
if pv < 0.:
pv = null_model_score.pv_alt_model(GV, method='saddle')
return pv
def call_score(GV, name, vids=None):
if name not in pval_dict:
pval_dict[name] = {}
called.append(name)
pval_dict[name] = {}
# single-marker p-values
pval_dict[name]['pv_score'] = np.array([pv_score(GV[:,i,np.newaxis]) for i in range(GV.shape[1])])
# single-marker coefficients
beta = [ null_model_score.coef(GV[:,i,np.newaxis]) for i in range(GV.shape[1]) ]
pval_dict[name]['beta'] = np.array([x['beta'][0,0] for x in beta])
pval_dict[name]['betaSd'] = np.array([np.sqrt(x['var_beta'][0,0]) for x in beta])
if vids is not None:
pval_dict[name]['vid'] = vids
def call_lrt(GV, name, vids=None):
if name not in pval_dict:
pval_dict[name] = {}
called.append(name)
# get gene parameters, test statistics and and single-marker regression weights
lik = null_model_lrt.altmodel(GV)
pval_dict[name]['nLL'] = lik['nLL']
pval_dict[name]['sigma2'] = lik['sigma2']
pval_dict[name]['lrtstat'] = lik['stat']
pval_dict[name]['h2'] = lik['h2']
logdelta = null_model_lrt.model1.find_log_delta(GV.shape[1])
pval_dict[name]['log_delta'] = logdelta['log_delta']
pval_dict[name]['coef_random'] = null_model_lrt.model1.getPosteriorWeights(logdelta['beta'], logdelta=logdelta['log_delta'])
if vids is not None:
pval_dict[name]['vid'] = vids
# load splice variants
G1, vids, weights, ncarrier, cummac, is_plof, splice_preds_all = get_splice(interval)
# keep indicates which variants are NOT "protein LOF" variants, i.e. variants already identified by the ensembl VEP
keep = ~is_plof
# these are common to all kernels
pval_dict['vid'] = vids
pval_dict['weights'] = weights
pval_dict['MAC'] = cummac
pval_dict['nCarrier'] = ncarrier
pval_dict['not_LOF'] = keep
for col in splice_preds_all.columns:
pval_dict[col] = splice_preds_all[col].values.astype(np.float32)
# single-variant p-values:
call_score(G1, 'variant_pvals') # single variant p-values and coefficients estimated independently
call_lrt(G1.dot(np.diag(np.sqrt(weights), k=0)), 'variant_pvals') # single variant coefficients estimated *jointly* after weighting
# sanity checks
assert len(vids) == interval['n_snp'], 'Error: number of variants does not match! expected: {} got: {}'.format(interval['n_snp'], len(vids))
assert cummac.sum() == interval['cumMAC'], 'Error: cumMAC does not match! expeced: {}, got: {}'.format(interval['cumMAC'], cummac.sum())
# do a score burden test (max weighted), this is different than the baseline!
G1_burden = np.max(np.where(G1 > 0.5, np.sqrt(weights), 0.), axis=1, keepdims=True)
call_score(G1_burden, 'linwb')
call_lrt(G1_burden, 'linwb')
# linear weighted kernel
G1 = G1.dot(np.diag(np.sqrt(weights), k=0))
# do a score test (linear weighted)
call_score(G1, 'linw', vids=vids)
call_lrt(G1, 'linw')
# load plof burden
G2 = get_plof(interval)
if G2 is not None:
call_score(G2, 'LOF')
call_lrt(G2, 'LOF')
if np.any(keep):
# merged (single variable)
G1_burden_mrg = np.maximum(G2, G1_burden)
call_score(G1_burden_mrg, 'linwb_mrgLOF')
call_lrt(G1_burden_mrg, 'linwb_mrgLOF')
# concatenated ( >= 2 variables)
# we separate out the ones that are already part of the protein LOF variants!
G1 = np.concatenate([G1[:, keep], G2], axis=1)
call_score(G1, 'linw_cLOF', vids=np.array(vids[keep].tolist() + [-1]))
call_lrt(G1, 'linw_cLOF')
else:
logging.info('All Splice-AI variants for gene {} where already identified by the Ensembl variant effect predictor'.format(interval['name']))
return pval_dict, called
logging.info('loaders for chromosome {} initialized in {:.1f} seconds.'.format(chromosome, timer.check()))
# run tests for all genes on the chromosome
for _, region in regions.iterrows():
try:
gene_stats, called = test_gene(region, i_gene)
except GotNone:
continue
# build the single-variant datafame
single_var_columns = ['gene', 'vid', 'weights', 'MAC', 'nCarrier', 'not_LOF', 'DS_AG', 'DS_AL', 'DS_DG', 'DS_DL', 'DP_AG', 'DP_AL', 'DP_DG', 'DP_DL']
sv_df = pd.DataFrame.from_dict({k: gene_stats[k] for k in single_var_columns})
sv_df['pv_score'] = gene_stats['variant_pvals']['pv_score'] # single-variant p-values estimated independently
sv_df['coef_random'] = gene_stats['variant_pvals']['coef_random'] # single-variant coefficients estimated jointly after weighting
sv_df['beta'] = gene_stats['variant_pvals']['beta'] # single-variant coeffcients estimated independently *without* weighting
sv_df['betaSd'] = gene_stats['variant_pvals']['betaSd'] # standard errors for the single-variant coefficients estimated independently *without* weighting
sv_df['pheno'] = snakemake.params.phenotype
out_dir = os.path.join(snakemake.params.out_dir_stats, region['name'])
os.makedirs(out_dir, exist_ok=True)
sv_df.to_csv(out_dir + '/variants.tsv.gz', sep='\t', index=False)
for k in called:
if k == 'variant_pvals':
continue
results_dict = gene_stats[k]
df_cols = ['pv_score', 'coef_random', 'beta', 'betaSd', 'vid'] # parts of the dict that have lenght > 1
df = pd.DataFrame.from_dict(data={k: results_dict[k] for k in df_cols if k in results_dict})
df['gene'] = gene_stats['gene']
df['pheno'] = snakemake.params.phenotype
df.to_csv(out_dir + '/{}.tsv.gz'.format(k), sep='\t', index=False)
# other cols ['nLL', 'sigma2', 'lrtstat', 'h2', 'log_delta']
other_cols = {k: v for k, v in results_dict.items() if k not in df_cols}
other_cols['gene'] = gene_stats['gene']
other_cols['pheno'] = snakemake.params.phenotype
pickle.dump(other_cols, open(out_dir + '/{}_stats.pkl'.format(k), 'wb'))
i_gene += 1
logging.info('tested {} genes...'.format(i_gene))
timer.reset() | 16,047 | 5,667 |
#!/bin/env python
# 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.
import yaml
from utils.animation import Animation, run_main
from utils.audio import SpectroGram, AudioMod
p = """
formula: |
z.imag = fabs(z.imag);
z = cdouble_powr(z, mod);
z = cdouble_add(z, c);
z = cdouble_log(z);
kernel: mean-distance
kernel_params: "double mod"
kernel_params_mod:
- mod
mod: 1
xyinverted: True
gradient: render_data/Solankii Gradients for Gimp/Gradient-#21.ggr
c_imag: -0.13422671142194348
c_real: 0.298544669649099
i_step: 0.012438114469344182
julia: true
map_center_imag: 0.298544669649099
map_center_real: -0.1217885969525993
map_radius: 0.12438114469344182
r_step: 0.012438114469344182
radius: 51.16156978094776
"""
class Demo(Animation):
def __init__(self):
self.scenes = [
[4000, None],
[3500, self.ending],
[3286, self.zoom],
[2526, self.verse4],
[2025, self.verse3],
[1770, self.verse2],
[1520, self.tr1],
[754, self.verse1],
[0, self.intro],
]
super().__init__(yaml.load(p))
def setAudio(self, audio):
self.audio = audio
self.spectre = SpectroGram(audio.audio_frame_size)
self.audio_events = {
"low": AudioMod((0, 12), "max", decay=10),
"mid": AudioMod((152, 483), "max", decay=5),
"hgh": AudioMod((12, 456), "avg"),
}
def ending(self, frame):
self.params["c_imag"] -= 4e-5 * self.low + 1e-4 * self.mid + 1e-5
self.params["grad_freq"] += 2e-1 * self.hgh
def zoom(self, frame):
if self.scene_init:
self.imag_mod = self.logspace(self.params["c_imag"],
0.9187686207968877)
self.rad_mod = self.logspace(self.params["radius"], 0.03)
self.freq_mod = self.logspace(self.params["grad_freq"], 0.20)
self.params["grad_freq"] = self.freq_mod[self.scene_pos]
self.params["radius"] = self.rad_mod[self.scene_pos]
if frame < 3400:
self.params["c_imag"] = self.imag_mod[self.scene_pos]
else:
self.params["c_imag"] -= 4e-5 * self.low + 1e-4 * self.mid
def verse4(self, frame):
if self.scene_init:
self.rad_mod = self.logspace(self.params["radius"], 3606)
self.params["radius"] = self.rad_mod[self.scene_pos]
self.params["c_imag"] += 5e-6 * self.low
self.params["c_real"] -= 5e-6 * self.mid
def verse3(self, frame):
if self.scene_init:
self.rad_mod = self.logspace(self.params["radius"], 556)
self.params["radius"] = self.rad_mod[self.scene_pos]
self.params["c_imag"] += 8e-5 * self.mid
self.params["c_real"] -= 1e-5 * self.low
self.params["grad_freq"] += 1e-2 * self.hgh
def verse2(self, frame):
if self.scene_init:
self.base_real = self.params["c_real"]
self.params["c_imag"] -= 8e-5 * self.low
self.params["grad_freq"] += 1e-2 * self.mid
# self.params["c_real"] += 1e-4 * self.mid
# self.params["c_real"] += 1e-4 * self.mid
def tr1(self, frame):
if self.scene_init:
self.rad_mod = self.logspace(self.params["radius"], 129)
self.params["radius"] = self.rad_mod[self.scene_pos]
self.params["grad_freq"] -= 1e-2 * self.low
self.params["c_imag"] += 1e-4 * self.mid
def verse1(self, frame):
if self.scene_init:
self.rad_mod = self.linspace(self.params["radius"], 0.1)
self.params["radius"] = self.rad_mod[self.scene_pos]
self.params["c_imag"] += 4e-5 * self.low
self.params["c_real"] += 1e-4 * self.mid
self.params["grad_freq"] += 2e-2 * self.hgh
def intro(self, frame):
if self.scene_init:
self.base_real = self.params["c_real"]
self.rad_mod = self.linspace(self.params["radius"], 0.08)
self.params["radius"] = self.rad_mod[self.scene_pos]
self.params["c_imag"] += 4e-5 * self.low
self.params["c_real"] = self.base_real + 2e-4 * self.hgh
self.params["grad_freq"] += 3e-3 * self.mid
if __name__ == "__main__":
run_main(Demo())
| 4,741 | 1,861 |
from abc import ABC, abstractmethod
class Pizza(ABC):
@abstractmethod
def prepare(self):
pass
def bake(self):
print("baking pizza for 12min in 400 degrees..")
def cut(self):
print("cutting pizza in pieces")
def box(self):
print("putting pizza in box")
class NYStyleCheesePizza(Pizza):
def prepare(self):
print("preparing a New York style cheese pizza..")
class ChicagoStyleCheesePizza(Pizza):
def prepare(self):
print("preparing a Chicago style cheese pizza..")
class NYStyleGreekPizza(Pizza):
def prepare(self):
print("preparing a New York style greek pizza..")
class ChicagoStyleGreekPizza(Pizza):
def prepare(self):
print("preparing a Chicago style greek pizza..")
# This time, PizzaStore is abstract
class PizzaStore(ABC):
# We brought createPizza back into the PizzaStore (instead of the SimpleFactory)
# However, it is declared as abstract. This time, instead of having
# a factory class, we have a factory method:
@abstractmethod
def _createPizza(self, pizzaType: str) -> Pizza:
pass
def orderPizza(self, pizzaType):
pizza: Pizza
pizza = self._createPizza(pizzaType)
pizza.prepare()
pizza.bake()
pizza.cut()
pizza.box()
class NYPizzaStore(PizzaStore):
def _createPizza(self, pizzaType: str) -> Pizza:
pizza: Pizza = None
if pizzaType == 'Greek':
pizza = NYStyleGreekPizza()
elif pizzaType == 'Cheese':
pizza = NYStyleCheesePizza()
else:
print("No matching pizza found in the NY pizza store...")
return pizza
class ChicagoPizzaStore(PizzaStore):
def _createPizza(self, pizzaType: str) -> Pizza:
pizza: Pizza = None
if pizzaType == 'Greek':
pizza = ChicagoStyleGreekPizza()
elif pizzaType == 'Cheese':
pizza = ChicagoStyleCheesePizza()
else:
print("No matching pizza found in the Chicago pizza store...")
return pizza
nyPizzaStore = NYPizzaStore()
chPizzaStore = ChicagoPizzaStore()
nyPizzaStore.orderPizza('Greek')
print("\n")
chPizzaStore.orderPizza('Cheese')
| 2,240 | 710 |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db_url = 'postgresql://postgres:postgres@localhost:5432/postgres'
db = SQLAlchemy()
def create_app():
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = db_url
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# initialize database
db.init_app(app)
return app
| 366 | 135 |
#!/usr/bin/python
# -*- coding: utf8 -*-
# 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.
import logging
from clize import run
from utils import download_file
import re
from os.path import basename, splitext
from icalendar import Calendar
import datetime
import pytz
import csv
stopwords = [
"breakfast",
"registration",
"sponsor showcase",
"coffee break",
"lunch"
"barcamp",
"keynote",
"morning run",
"attendee reception"
"BarCampApache"
]
def ics2csv(ics, name=None):
"""
Transforms a ICS files to CSV
ics: ics path or url
name: conference name (optional)
"""
logging.basicConfig(level=logging.DEBUG, format="\033[1m%(name)s\033[0m %(message)s")
logging.getLogger("requests").setLevel(logging.WARNING)
log = logging.getLogger("tac")
if name is None:
name = splitext(basename(ics))[0]
csv_path = "%s.csv" % name
ics_path = "%s.ics" % name
if ics.startswith("http") or ics.startswith("http"):
ics_path = download_file(ics, ics_path)
log.debug("Downloaded %s at %s", ics, ics_path)
slots = []
with open(ics_path, 'r') as g:
gcal = Calendar.from_ical(g.read())
for component in gcal.walk():
if component.name == "VEVENT":
title = component.get('summary')
start_time_utc = component.get('dtstart').dt
local_tz = pytz.timezone('US/Eastern') # TODO: arg
start_time_local = start_time_utc.astimezone(local_tz)
start = start_time_local.strftime("%Y-%m-%d %H:%M")
location = re.sub(', Miami, FL, United States$', '', component.get('location')) # TODO: arg
if not any(stopword in title.lower() for stopword in stopwords):
slots.append((title, location, start))
with open(csv_path, "w") as f:
writer = csv.writer(f, quoting=csv.QUOTE_ALL)
#writer.writerow(["talk", "room", "time", "volunteer", "backup"])
for slot in slots:
writer.writerow(slot)
log.info("Exported %d talks to %s", len(slots), csv_path)
if __name__ == "__main__":
run(ics2csv)
| 2,677 | 886 |
"""Describe how you could use a single array to implement three stacks."""
class StackManager:
def __init__(self):
self.stacks = []
self.top = {
1: None,
2: None,
3: None,
}
self.length = {
1: 0,
2: 0,
3: 0,
}
def push(self, stack: int, data):
assert stack in self.top
if stack == 1:
if self.top[1] is not None:
self.top[1] += 1
if self.top[2] is not None:
self.top[2] += 1
if self.top[3] is not None:
self.top[3] += 1
else:
self.top[1] = 0
elif stack == 2:
if self.top[2] is not None:
self.top[2] += 1
if self.top[3] is not None:
self.top[3] += 1
else:
if self.top[1] is not None:
self.top[2] = self.top[1] + 1
else:
self.top[2] = 0
else:
if self.top[3] is not None:
self.top[3] += 1
else:
self.top[3] = len(self.stacks)
self.stacks.insert(self.top[stack], data)
self.length[stack] += 1
def pop(self, stack: int):
assert stack in self.top
if self.top[stack] is None:
return None
top = self.stacks.pop(self.top[stack])
self.top[stack] -= 1
self.length[stack] -= 1
if self.length[stack] == 0:
self.top[stack] = None
if stack == 1:
if self.top[2] is not None:
self.top[2] -= 1
if self.top[3] is not None:
self.top[3] -= 1
elif stack == 2:
if self.top[3] is not None:
self.top[3] -= 1
return top
| 1,925 | 609 |
__author__ = 'chenshuai'
cast = ["Cleese", "Plain", "Jones", "Idle"]
print cast
print len(cast)
print cast[1]
cast.append("Gilliam")
print cast
cast.pop()
print cast
cast.extend(["Gilliam", "Chapman"])
print cast
cast.remove("Chapman")
print cast
cast.insert(0, "Chapman")
print cast
movies = ["The Holy Grail", "The Life of Brian", "The Meaning of Life"]
movies.insert(1, 1975)
movies.insert(3, 1979)
movies.append(1983)
fav_movies = ["The Holy Grail", "The Life of Brain"]
for each_flick in fav_movies:
print(each_flick)
# movies = [[],[],[]]
print movies[4][1][3]
print isinstance(movies, list) # True
print isinstance(len(movies), list) # False
# nester.py
# default value is not necessary
def print_lol(the_list, indent=False, level=0, fh=sys.stdou):
for each_item in the_list:
if isinstance(each_item, list):
print_lol(each_item, indent, level+1, fh)
else:
if indent:
for tab_stop in range(level):
print "\t"
print each_item
# print(each_item, end='', file=fh) python3
# python PyPI
# perl CPAN
"""This is the standard way to include a multiple-line comment in your code."""
"""import sys; print(sys.path); the location of python lib"""
"""pyc file === java class file"""
# list()
# range()
# enumerate()
# int()
# id()
# next()
import os
print os.chdir("../")
print os.getcwd()
data = open("sketch.txt")
print data.readline()
data.seek(0)
# Man: Is this the right room for an argument?
# Other Man: I've told you once.
# Man: No you haven't!
# Other Man: Yes I have.
# Man: When?
# Other Man: Just now.
# Man: No you didn't
if os.path.exists("readme.txt"):
data = open("readme.txt")
for each_line in data:
if not each_line.find(":") == -1:
try:
# split: Immutable parameters
(role, line_spoken) = each_line.split(":", 1)
print role
print line_spoken
# focus your job's content
except ValueError:
pass
data.close()
else:
print "The data file is missing !"
# try/except/finally
man = []
other = []
try:
data = open("sketch.txt")
for each_line in data:
try:
(role, line_spoken) = each_line.split(":", 1)
line_spoken = line_spoken.strip()
if role == "Man":
man.append(line_spoken)
elif role == 'Other Man':
other.append(line_spoken)
except ValueError as err:
print "File error: " + str(err)
pass
# call locals() before call close()
# locals() BIF
finally:
if 'data' in locals():
data.close()
except IOError:
print "The datafile is missing !"
print man
print other
"""with is equals try/except/finally, with use a kind of context management protocol python tech"""
try:
with open("its.txt", "w") as data:
data.write("It's...")
except IOError as err:
print "File error: " + str(err)
"""||"""
"""||"""
"""||"""
"""with is equals try/except/finally, with use a kind of context management protocol python tech"""
try:
data = open("its.txt", "w")
data.write("It's...")
except IOError as err:
print "File error: " + str(err)
finally:
if "data" in locals():
data.close()
with open("man_data.txt", "w") as man_file, open("other_data.txt", "w") as other_file:
# data in memory
print man_file.readlines()
# data in memory
print other_file.readlines()
# dump load; must use binary
import pickle
try:
with open("mydata.pickle", "wb") as mysavedata:
pickle.dump([1, 2, 'three'], mysavedata)
with open("mydata.pickle", "rb") as myrestoredata:
a_list = pickle.load(myrestoredata)
print a_list
except IOError as err:
print "File error: " + str(err)
except pickle.PickleError as pickle_err:
print "Pickling error: " + str(pickle_perr)
# In-place sorting
print data.sort()
# Copied sorting
print sorted(data)
def sanitize(time_string):
if "-" in time_string:
splitter = "-"
elif ":" in time_string:
splitter = ":"
else:
return time_string
mins, secs = time_string.split(splitter)
return mins + "." + secs
# create convert iterate append
clean_mikey = [sanitize(each_t) for each_t in mikey]
print sorted(set([sanitize(each_t) for each_t in mikey]), reverse=True)[0:3]
# pop
def get_coach_data(filename):
try:
with open(filename) as f:
data = f.readline()
templ = data.strip().split(",")
return {
"name": templ.pop(0),
"dob": templ.pop(0),
"times": str(sorted(set(sanitize(t) for t in sarah_data["times"]))[0:3])
}
except IOError as ioerr:
print "File error: " + str(ioerr)
return None
# class
class Athlete:
def __init__(self, a_name, a_dob=None, a_times=[]):
self.name = a_name
self.dob = a_dob
self.times = a_times
def top3(self):
return sorted(set([sanitize(t) for t in self.times]))[0:3]
def add_time(self, time_value):
self.times.append(time_value)
def add_times(self, list_of_times):
self.times.extend(list_of_times)
sarah = Athlete("Sarah Sweeney", "2002-6-17", ["2:58", "2.58", "1.56"])
james = Athlete("James Jones")
print str(sarah.top3())
print str(james.top3())
| 5,434 | 1,898 |
from SQLPythonGenerator import SQLPythonGenerator
class SQLitePythonGenerator(SQLPythonGenerator):
pass
| 110 | 25 |
from toee import *
def OnBeginSpellCast(spell):
print "Dirge OnBeginSpellCast"
print "spell.target_list=", spell.target_list
print "spell.caster=", spell.caster, " caster.level= ", spell.caster_level
def OnSpellEffect(spell):
print "Dirge OnSpellEffect"
targetsToRemove = []
spell.duration = 1 * spell.caster_level # 1 round/cl
#spellTarget = spell.target_list[0]
for spellTarget in spell.target_list:
targetsToRemove.append(spellTarget.obj)
dirgeObject = game.obj_create(OBJECT_SPELL_GENERIC, spell.target_loc)
casterInitiative = spell.caster.get_initiative()
dirgeObject.d20_status_init()
dirgeObject.set_initiative(casterInitiative)
dirgeObject.condition_add_with_args('sp-Dirge', spell.id, spell.duration, spell.dc)
spell.target_list.remove_list(targetsToRemove)
#spell.spell_end(spell.id)
def OnBeginRound(spell):
print "Dirge OnBeginRound"
def OnEndSpellCast(spell):
print "Dirge OnEndSpellCast" | 994 | 365 |
from OMIEData.Downloaders.general_omie_downloader import GeneralOMIEDownloader
class MarginalPriceDownloader(GeneralOMIEDownloader):
url_year = 'AGNO_YYYY'
url_month = '/MES_MM/TXT/'
url_name = 'INT_PBC_EV_H_1_DD_MM_YYYY_DD_MM_YYYY.TXT'
output_mask = 'PMD_YYYYMMDD.txt'
def __init__(self):
url1 = self.url_year + self.url_month + self.url_name
GeneralOMIEDownloader.__init__(self, url_mask=url1, output_mask=self.output_mask)
| 468 | 188 |
from struct import unpack
from os.path import getsize
# 第一步 读取 out 文件的 二进制 内容
def un_sub_400CC0() -> tuple:
"""
:return: 返回一个元祖,内容是从 out 文件中读取的内容
"""
# 读取 out 文件
outFilePath = "./out"
outLength = getsize(outFilePath)
with open(outFilePath, 'rb') as outFile:
# B = unsigned char
return unpack(''.join(['B' * outLength]), outFile.read())
# 第二步 处理 out 的内容
def un_sub_400DB4(t: tuple) -> list:
"""
:param t: out 中读取的内容
:return: 返回一个列表,是 out 中内容对 sub_400DB4 函数的逆变换
"""
# 按 byte 读取,所以 & 0xFF
v3 = (t[-1] << 5 | t[0] >> 3) & 0xFF
_list = [v3]
for i in range(len(t) - 1):
_list.append(((t[i] << 5) | t[i + 1] >> 3) & 0xFF)
return _list
# 第三步 读取 that_girl
def un_sub_400AAA() -> dict:
"""
:return: 返回一个字典,内容为经过 sub_400936 函数变换后的 that_girl 的内容每个字符与其出现的次数
"""
# sub_400936 对每个字符的处理
def sub_400936(char: str) -> int:
"""
:param char: 读取的字符
:return: 变换对应的整数
"""
char = ord(char)
result = char - 10
if char is 10:
result = char + 35 # 10 -> 45 : '\n' -> '-'
elif char is 32 or char is 33 or char is 34:
# 其实只有 ' '
result = char + 10 # 32 33 34 -> 42 43 44 : ' ' or '!' or '"' -> '*' or '+' or ','
elif char is 39:
result = char + 2 # 39 -> 41 : '\'' -> ')'
# 经测试,下面这几个分支没用
# elif char is 44:
# result = char - 4 # 44 -> 40 : ',' -> '('
# elif char is 46:
# result = char - 7 # 46 -> 39 : '.' -> '\''
# elif char is 58 or char is 59: # 58 59 -> 37 38 : ':' or ';' -> '%' '&'
# result = char - 21
# elif char is 63:
# result = char - 27 # 63 -> 37 : '?' -> '%'
elif char is 95:
result = char - 49 # 95 -> 46 : '_' -> '.'
else:
if char <= 47 or char > 48: # not 48('0')
if char <= 64 or char > 90:
if 96 < char <= 122:
result = char - 87 # a ~ z -> 10 ~ 35
else:
result = char - 55 # [A ~ Z] -> 10 ~ 35
else:
# 这个也是不存在的
result = char - 48 # '0' -> 0
return result
songFilePath = "./that_girl"
# 原来的操作是 ++*(_DWORD *)(4LL * v2 + ptr); 但其实它的指针类型是 __int64,而实际的数据类型为 byte,我们可以不需要乘这个4
# 经过测试命中区域处于 40 ~ 184 之间, (184 - 40) / 4 = 36
_list = [0] * 37
with open(songFilePath, "r") as song:
for c in song.read():
v2 = sub_400936(c)
_list[v2 - 10] += 1
"""
观察 sub_400936 函数我们不难发现其实就是一个映射关系
不分大小写
a~z(A~Z) 映射到 _list[0~25]
剩下的依次是
'\'' -> 31
' ' -> 32
'\\n'' -> 35
'_' -> 36
其他的都是无效的
我们可以只返回有效的数据
"""
ret = _list[:26]
ret.append(_list[31])
ret.append(_list[32])
ret.append(_list[35])
ret.append(_list[36])
return dict(zip("abcdefghijklmnopqrstuvwxyz' \n_", ret))
# 第四步 获取flag
def getFlag(_list: list, mapping: dict) -> str:
"""
:param _list: 这个列表带着处理后的 out 的内容
:param mapping: 这个字典带着 字符 与 出现次数 的映射
:return:
"""
def un_sub_400D33() -> None:
"""
处理 getFlag 传进来的 _list
"""
# 直接用外面传进来的列表
nonlocal _list
dword_6020A0 = [
0x16, 0x00, 0x06, 0x02, 0x1e,
0x18, 0x09, 0x01, 0x15, 0x07,
0x12, 0x0a, 0x08, 0x0c, 0x11,
0x17, 0x0d, 0x04, 0x03, 0x0e,
0x13, 0x0b, 0x14, 0x10, 0x0f,
0x05, 0x19, 0x24, 0x1b, 0x1c,
0x1d, 0x25, 0x1f, 0x20, 0x21,
0x1a, 0x22, 0x23
]
"""
dword_6020A0 = [
22, 0, 6, 2, 30,
24, 9, 1, 21, 7,
18, 10, 8, 12, 17,
23, 13, 4, 3, 14,
19, 11, 20, 16, 15,
5, 25, 36, 27, 28,
29, 37, 31, 32, 33,
26, 34, 35
]
index -> dword_6020A0[index]
0 -> [22] = 20
20 -> [20] = 19
19 -> [19] = 14
14 -> [14] = 17
17 -> [17] = 4
4 -> [4] = 30
30 -> [30] = 29
29 -> [29] = 28
28 -> [28] = 27
27 -> [27] = 36
36 -> [36] = 34
34 -> [34] = 33
33 -> [33] = 32
32 -> [32] = 31
31 -> [31] = 37
37 -> [37] = 35
35 -> [35] = 26
26 -> [26] = 25
25 -> [25] = 5
5 -> [5] = 24
24 -> [24] = 15
15 -> [15] = 23
23 -> [23] = 16
16 -> [16] = 13
13 -> [13] = 12
12 -> [12] = 8
8 -> [8] = 21
21 -> [21] = 11
11 -> [11] = 10
10 -> [10] = 18
18 -> [18] = 3
3 -> [3] = 2
2 -> [2] = 6
6 -> [6] = 9
9 -> [9] = 7
7 -> [7] = 1
1 -> [1] = 0
没有重复,没有覆盖,可以还原
"""
v2 = 37
while dword_6020A0.index(v2) is not 37:
_list[v2] = _list[dword_6020A0.index(v2)]
v2 = dword_6020A0.index(v2)
un_sub_400D33()
flag = []
mappingKey = list(mapping.keys())
mappingValue = list(mapping.values())
for i in _list:
index = mappingValue.index(i)
flag.append(mappingKey[index])
return f"QCTF{{{''.join(flag)}}}"
print(getFlag(un_sub_400DB4(un_sub_400CC0()), un_sub_400AAA()))
| 5,556 | 2,768 |
from textblob import TextBlob
from textblob import Word
import nltk
nltk.download('punkt')
nltk.download('wordnet')
#getting correct sentences
words = ['Machin','Learnin','corect']
corrected_words = []
for i in words:
corrected_words.append(TextBlob(i))
print('worng words :', words)
print('Corrected words :')
for i in corrected_words:
print(i.correct())
# Getting sentiment analysis
test = TextBlob('Usman is a great machine learning developer and also have some cloud knowledge')
print(test.sentiment)
print('Polarity :',test.sentiment.polarity)
# Add space before dot inorder to get in as a sentence
token = TextBlob("Usman is a great machine learning. "
"developer and also. "
"have some cloud knowledge.")
# printing seperate words and sentences
print('Word :',token.words)
print('Sentences', token.sentences)
# Getting sentiments of those sentences
print('Sentences sentiments ::')
for i in token.sentences:
print(i.sentiment)
# Words singularization and pluralization
sentence = TextBlob('we bought 5 tomatos from shop today')
print(sentence.words[5].pluralize())
print(sentence.words[3].singularize())
#for i in sentence.words:
# print(i)
# correcting nouns
word = Word('speling')
print(word.correct())
zen =TextBlob('beautiful is better')
print(zen.upper())
| 1,345 | 420 |
import os
from os import path
old_sample_rate = float(input("What was the original sample rate? "))
new_sample_rate = float(input("What is the new sample rate? "))
for file in os.listdir(os.getcwd()):
name = file.rsplit(".",1)[0]
if file.rsplit(".",1)[-1] == "opus" and path.exists(name + ".opus.txt"):
print('\n')
print(name)
f = open(name + ".opus.txt", "r")
lines = f.readlines()
f.close()
new_lines = []
for line in lines:
args = line.split('=')
command = args[0].strip()
samples = int(args[1].strip())
new_samples = int(samples * (new_sample_rate / old_sample_rate))
new_line = f'{command}={new_samples}'
print(f'Converting {line.strip()} to {new_line.strip()}')
new_lines.append(new_line)
f = open(name + ".opus.txt", "w")
f.write('\n'.join(new_lines))
f.close() | 942 | 310 |
from django import template
from django.conf import settings
from django.template.loader import render_to_string
from djblets.util.decorators import basictag
from reviewboard.extensions.hooks import DiffViewerActionHook, \
NavigationBarHook, \
ReviewRequestActionHook, \
ReviewRequestDropdownActionHook
register = template.Library()
def action_hooks(context, hookcls, action_key="action",
template_name="extensions/action.html"):
"""Displays all registered action hooks from the specified ActionHook."""
s = ""
for hook in hookcls.hooks:
for actions in hook.get_actions(context):
if actions:
new_context = {
action_key: actions
}
context.update(new_context)
s += render_to_string(template_name, new_context)
return s
@register.tag
@basictag(takes_context=True)
def diffviewer_action_hooks(context):
"""Displays all registered action hooks for the diff viewer."""
return action_hooks(context, DiffViewerActionHook)
@register.tag
@basictag(takes_context=True)
def review_request_action_hooks(context):
"""Displays all registered action hooks for review requests."""
return action_hooks(context, ReviewRequestActionHook)
@register.tag
@basictag(takes_context=True)
def review_request_dropdown_action_hooks(context):
"""Displays all registered action hooks for review requests."""
return action_hooks(context,
ReviewRequestDropdownActionHook,
"actions",
"extensions/action_dropdown.html")
@register.tag
@basictag(takes_context=True)
def navigation_bar_hooks(context):
"""Displays all registered navigation bar entries."""
s = ""
for hook in NavigationBarHook.hooks:
for nav_info in hook.get_entries(context):
if nav_info:
context.push()
context['entry'] = nav_info
s += render_to_string("extensions/navbar_entry.html", context)
context.pop()
return s
| 2,221 | 592 |
from abc import ABC, abstractmethod
from typing import Dict, Any
import tensorflow as tf
import numpy as np
from opengnn.utils.data import diverse_batch, batch_and_bucket_by_size
from opengnn.utils.data import filter_examples_by_size, truncate_examples_by_size
def optimize(loss: tf.Tensor, params: Dict[str, Any]):
global_step = tf.train.get_or_create_global_step()
optimizer = params.get('optimizer', 'Adam')
if optimizer != 'Adam':
optimizer_class = getattr(tf.train, optimizer, None)
if optimizer_class is None:
raise ValueError("Unsupported optimizer %s" % optimizer)
optimizer_params = params.get("optimizer_params", {})
def optimizer(lr): return optimizer_class(lr, **optimizer_params)
learning_rate = params['learning_rate']
if params.get('decay_rate') is not None:
learning_rate = tf.train.exponential_decay(
learning_rate,
global_step,
decay_steps=params.get('decay_steps', 1),
decay_rate=params['decay_rate'],
staircase=True)
return tf.contrib.layers.optimize_loss(
loss=loss,
global_step=global_step,
learning_rate=learning_rate,
clip_gradients=params['clip_gradients'],
summaries=[
"learning_rate",
"global_gradient_norm",
],
optimizer=optimizer,
name="optimizer")
class Model(ABC):
def __init__(self,
name: str,
features_inputter=None,
labels_inputter=None) -> None:
self.name = name
self.features_inputter = features_inputter
self.labels_inputter = labels_inputter
def model_fn(self):
def _model_fn(features, labels, mode, params, config=None):
if mode == tf.estimator.ModeKeys.TRAIN:
with tf.variable_scope(self.name):
# build models graph
outputs, predictions = self.__call__(
features, labels, mode, params, config)
# compute loss, tb_loss and train_op
loss, tb_loss = self.compute_loss(
features, labels, outputs, params, mode)
train_op = optimize(loss, params)
return tf.estimator.EstimatorSpec(
mode, loss=tb_loss, train_op=train_op)
elif mode == tf.estimator.ModeKeys.EVAL:
with tf.variable_scope(self.name):
# build models graph
outputs, predictions = self.__call__(
features, labels, mode, params, config)
# compute loss, tb_loss and metric ops
loss, tb_loss = self.compute_loss(
features, labels, outputs, params, mode)
metrics = self.compute_metrics(
features, labels, predictions)
# TODO: this assumes that the loss across validation can be
# calculated as the average over the loss of the minibatch
# which is not always the case (cross entropy averaged over time an batch)
# but if minibatch a correctly shuffled, this is a good aproximation for now
return tf.estimator.EstimatorSpec(
mode, loss=tb_loss, eval_metric_ops=metrics)
elif mode == tf.estimator.ModeKeys.PREDICT:
with tf.variable_scope(self.name):
# build models graph
_, predictions = self.__call__(
features, labels, mode, params, config)
return tf.estimator.EstimatorSpec(
mode, predictions=predictions)
return _model_fn
def input_fn(self,
mode: tf.estimator.ModeKeys,
batch_size: int,
metadata,
features_file,
labels_file=None,
sample_buffer_size=None,
maximum_features_size=None,
maximum_labels_size=None,
features_bucket_width=None,
labels_bucket_width=None,
num_threads=None):
assert not (mode != tf.estimator.ModeKeys.PREDICT and
labels_file is None)
# the function returned
def _input_fn():
self.initialize(metadata)
feat_dataset, feat_process_fn, feat_batch_fn, features_size_fn =\
self.get_features_builder(features_file, mode)
if labels_file is not None:
labels_dataset, labels_process_fn, \
labels_batch_fn, labels_size_fn = \
self.get_labels_builder(labels_file, mode)
dataset = tf.data.Dataset.zip((feat_dataset, labels_dataset))
def process_fn(features, labels):
return feat_process_fn(features), labels_process_fn(labels, features)
def batch_fn(dataset, batch_size):
return diverse_batch(
dataset, batch_size,
(feat_batch_fn, labels_batch_fn))
example_size_fns = [features_size_fn, labels_size_fn]
bucket_widths = [features_bucket_width, labels_bucket_width]
maximum_example_size = (maximum_features_size, maximum_labels_size)
else:
dataset = feat_dataset
process_fn = feat_process_fn
batch_fn = feat_batch_fn
example_size_fns = features_size_fn
bucket_widths = features_bucket_width
maximum_example_size = maximum_features_size
# shuffle, process batch and allow repetition
# TODO: Fix derived seed (bug in tensorflow)
seed = np.random.randint(np.iinfo(np.int64).max)
if sample_buffer_size is not None:
dataset = dataset.shuffle(
sample_buffer_size,
reshuffle_each_iteration=False,
seed=seed)
dataset = dataset.map(process_fn, num_parallel_calls=num_threads or 4)
dataset = dataset.apply(filter_examples_by_size(
example_size_fns=example_size_fns,
maximum_example_sizes=maximum_example_size))
dataset = dataset.apply(batch_and_bucket_by_size(
batch_size=batch_size,
batch_fn=batch_fn,
bucket_widths=bucket_widths,
example_size_fns=example_size_fns))
if mode == tf.estimator.ModeKeys.TRAIN:
dataset = dataset.repeat()
return dataset.prefetch(None)
return _input_fn
def initialize(self, metadata):
"""
Runs model specific initialization (e.g. vocabularies loading).
Args:
metadata: A dictionary containing additional metadata set
by the user.
"""
if self.features_inputter is not None:
self.features_inputter.initialize(metadata)
if self.labels_inputter is not None:
self.labels_inputter.initialize(metadata)
@abstractmethod
def __call__(self, features, labels, mode, params, config=None):
raise NotImplementedError()
@abstractmethod
def compute_loss(self, features, labels, outputs, params, mode):
raise NotImplementedError()
@abstractmethod
def compute_metrics(self, features, labels, predictions):
raise NotImplementedError()
def get_features_builder(self, features_file, mode):
if self.features_inputter is None:
raise NotImplementedError()
dataset = self.features_inputter.make_dataset(features_file, mode)
process_fn = self.features_inputter.process
batch_fn = self.features_inputter.batch
size_fn = self.features_inputter.get_example_size
return dataset, process_fn, batch_fn, size_fn
def get_labels_builder(self, labels_file, mode):
if self.labels_inputter is None:
raise NotImplementedError()
dataset = self.labels_inputter.make_dataset(labels_file, mode)
process_fn = self.labels_inputter.process
batch_fn = self.labels_inputter.batch
size_fn = self.labels_inputter.get_example_size
return dataset, process_fn, batch_fn, size_fn
| 8,671 | 2,411 |
from pathlib import Path
from .ast import NodeVisitor
class Output(NodeVisitor):
def __init__(self, context: dict, path: Path, templates: dict):
self.context = context
self.path = path
self.templates = {}
for filename, template in templates.items():
self.templates[path / filename] = context['jinja'].get_template(template)
def write(self):
if self.context['dry_run']:
print('######################################## Create Dir', self.path)
else:
self.path.mkdir(exist_ok=True)
for path, template in self.templates.items():
content = template.render(self.context)
if self.context['dry_run']:
print('======================================== Write file', path)
print(content)
else:
path.write_text(content)
| 894 | 225 |
import imp
import os
from functools import wraps
from ansible.errors import AnsibleAuthenticationFailure
from ansible.plugins import connection
# HACK: workaround to import the SSH connection plugin
_ssh_mod = os.path.join(os.path.dirname(connection.__file__), "ssh.py")
_ssh = imp.load_source("_ssh", _ssh_mod)
# Use same options as the builtin Ansible SSH plugin
DOCUMENTATION = _ssh.DOCUMENTATION
# Add an option `ansible_ssh_altpassword` to represent an alternative password
# to try if `ansible_ssh_password` is invalid
DOCUMENTATION += """
altpassword:
description: Alternative authentication password for the C(remote_user). Can be supplied as CLI option.
vars:
- name: ansible_altpassword
- name: ansible_ssh_altpass
- name: ansible_ssh_altpassword
""".lstrip("\n")
def _password_retry(func):
"""
Decorator to retry ssh/scp/sftp in the case of invalid password
Will retry for password in (ansible_password, ansible_altpassword):
"""
@wraps(func)
def wrapped(self, *args, **kwargs):
password = self.get_option("password") or self._play_context.password
conn_passwords = [password]
altpassword = self.get_option("altpassword")
if altpassword:
conn_passwords.append(altpassword)
while conn_passwords:
conn_password = conn_passwords.pop(0)
# temporarily replace `password` for this trial
self.set_option("password", conn_password)
self._play_context.password = conn_password
try:
return func(self, *args, **kwargs)
except AnsibleAuthenticationFailure:
# if there is no more altpassword to try, raise
if not conn_passwords:
raise
finally:
# reset `password` to its original state
self.set_option("password", password)
self._play_context.password = password
# retry here, need create a new pipe for sshpass
self.sshpass_pipe = os.pipe()
return wrapped
class Connection(_ssh.Connection):
@_password_retry
def _run(self, *args, **kwargs):
return super(Connection, self)._run(*args, **kwargs)
@_password_retry
def _file_transport_command(self, *args, **kwargs):
return super(Connection, self)._file_transport_command(*args, **kwargs)
| 2,449 | 664 |
import os
import json
def rel_fn(fn):
dir_name = os.path.dirname(os.path.realpath(__file__))
return os.path.join(dir_name, fn)
def mock_json(fn):
with open(rel_fn(fn)) as f:
return json.load(f)
| 218 | 87 |
"""
This file aims to simulate the Belousov–Zhabotinsky reaction,
is a chemical mixture which, when heated, undergoes a series
of reactions that cause the chemical concentrations in the
mixture to oscillate between two extremes (x, y).
"""
import numpy as np
import matplotlib.pyplot as plt
## Constants
a = 1
b = 3
x0 = 0 # x concentration level (M)
y0 = 0 # y concentration level (M)
targetAcc = 10 ** -10 # target accuracy for BS method
start = 0 # start time (s)
end = 20 # end time (s)
def f(r):
"""
This function calculates the equations for the BZ reaction
"""
x = r[0]
y = r[1]
dxdt = 1 - ((b + 1) * x) + (a * (x ** 2) * y)
dydt = (b * x) - (a * (x ** 2) * y)
return np.array([dxdt, dydt], float)
def midpoint(r, n, H):
"""
This function calculates the modified mid-point method
given in the textbook
"""
r2 = np.copy(r)
h = H / n
r1 = r + 0.5 * h * f(r)
r2 += h * f(r1)
for _ in range(n - 1):
r1 += h * f(r2)
r2 += h * f(r1)
return 0.5 * (r1 + r2 + 0.5 * h * f(r2))
def BZ_reaction():
"""
This function simulates the entire Belousov–Zhabotinsky reaction
from start time to end time with the given constants at the
beginning of the file using the Bulirsch–Stoer method with
recursion instead of a while loop.
"""
r = np.array([x0, y0], float)
tpoints = [start]
xpoints = [r[0]]
ypoints = [r[1]]
def BS(r, t, H):
"""
This function is just a shell for the following recursive
function if n, the number of recursive calls, exceeds 8.
Then we will redo the calculation with a smaller H.
"""
def BS_row(R1, n):
"""
This function calculates the row of extrapolation estimates.
Then it calculates the error and check if it falls under
our desired accuracy. If not, it will recurse on itself
with a larger n. If yes, then it will update the list of
variables.
"""
if n > 8:
r1 = BS(r, t, H / 2)
return BS(r1, t + H / 2, H / 2)
else:
R2 = [midpoint(r, n, H)]
for m in range(1, n):
R2.append(R2[m - 1] + (R2[m - 1] - R1[m - 1]) / ((n / (n - 1)) ** (2 * (m)) - 1))
R2 = np.array(R2, float)
error_vector = (R2[n - 2] - R1[n - 2]) / ((n / (n - 1)) ** (2 * (n - 1)) - 1)
error = np.sqrt(error_vector[0] ** 2 + error_vector[1] ** 2)
target_accuracy = H * targetAcc
if error < target_accuracy:
tpoints.append(t + H)
xpoints.append(R2[n - 1][0])
ypoints.append(R2[n - 1][1])
return R2[n - 1]
else:
return BS_row(R2, n + 1)
return BS_row(np.array([midpoint(r, 1, H)], float), 2)
BS(r, start, end - start)
return tpoints, xpoints, ypoints
#plotting our results
t, x, y = BZ_reaction()
fig, graph = plt.subplots()
graph.plot(t, x, 'r', label="x")
graph.plot(t, y, 'b', label="y")
graph.plot(t, x, 'r.')
graph.plot(t, y, 'b.')
graph.set(xlabel='time (s)', ylabel='concentration level (M)',
title='Belousov–Zhabotinsky concentration level over time')
graph.grid()
graph.legend()
fig.savefig("q3.png")
plt.show() | 3,423 | 1,243 |
import pysolr
from django.conf import settings
from django.core.management import call_command
from django.test import TestCase
from haystack import indexes
from haystack.sites import SearchSite
from core.models import MockModel
class SolrMockSearchIndex(indexes.SearchIndex):
text = indexes.CharField(document=True, use_template=True)
name = indexes.CharField(model_attr='author', faceted=True)
pub_date = indexes.DateField(model_attr='pub_date')
class ManagementCommandTestCase(TestCase):
fixtures = ['bulk_data.json']
def setUp(self):
super(ManagementCommandTestCase, self).setUp()
self.solr = pysolr.Solr(settings.HAYSTACK_SOLR_URL)
self.site = SearchSite()
self.site.register(MockModel, SolrMockSearchIndex)
# Stow.
import haystack
self.old_site = haystack.site
haystack.site = self.site
def tearDown(self):
import haystack
haystack.site = self.old_site
super(ManagementCommandTestCase, self).tearDown()
def test_basic_commands(self):
call_command('clear_index', interactive=False, verbosity=0)
self.assertEqual(self.solr.search('*:*').hits, 0)
call_command('update_index', verbosity=0)
self.assertEqual(self.solr.search('*:*').hits, 23)
call_command('clear_index', interactive=False, verbosity=0)
self.assertEqual(self.solr.search('*:*').hits, 0)
call_command('rebuild_index', interactive=False, verbosity=0)
self.assertEqual(self.solr.search('*:*').hits, 23)
def test_remove(self):
call_command('clear_index', interactive=False, verbosity=0)
self.assertEqual(self.solr.search('*:*').hits, 0)
call_command('update_index', verbosity=0)
self.assertEqual(self.solr.search('*:*').hits, 23)
# Remove a model instance.
MockModel.objects.get(pk=1).delete()
self.assertEqual(self.solr.search('*:*').hits, 23)
# Plain ``update_index`` doesn't fix it.
call_command('update_index', verbosity=0)
self.assertEqual(self.solr.search('*:*').hits, 23)
# With the remove flag, it's gone.
call_command('update_index', remove=True, verbosity=0)
self.assertEqual(self.solr.search('*:*').hits, 22)
def test_multiprocessing(self):
call_command('clear_index', interactive=False, verbosity=0)
self.assertEqual(self.solr.search('*:*').hits, 0)
# Watch the output, make sure there are multiple pids.
call_command('update_index', verbosity=2, workers=2, batchsize=5)
self.assertEqual(self.solr.search('*:*').hits, 23)
| 2,747 | 899 |
"""
Copyright 2020 Jackpine Technologies Corporation
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.
"""
# coding: utf-8
"""
cons3rt - Copyright Jackpine Technologies Corp.
NOTE: This file is auto-generated. Do not edit the file manually.
"""
import pprint
import re # noqa: F401
import six
from cons3rt.configuration import Configuration
__author__ = 'Jackpine Technologies Corporation'
__copyright__ = 'Copyright 2020, Jackpine Technologies Corporation'
__license__ = 'Apache 2.0',
__version__ = '1.0.0'
__maintainer__ = 'API Support'
__email__ = 'support@cons3rt.com'
class User(object):
"""NOTE: This class is auto-generated. Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'created_at': 'int',
'updated_at': 'int',
'administered_clouds': 'list[Cloud]',
'administered_virt_realms': 'list[VirtualizationRealm]',
'certificates': 'list[Certificate]',
'comment': 'str',
'default_project': 'Project',
'email': 'str',
'firstname': 'str',
'id': 'int',
'lastname': 'str',
'log_entries': 'list[LogEntry]',
'organization': 'str',
'project_count': 'int',
'state': 'str',
'terms_of_service_accepted': 'bool',
'username': 'str'
}
attribute_map = {
'created_at': 'createdAt',
'updated_at': 'updatedAt',
'administered_clouds': 'administeredClouds',
'administered_virt_realms': 'administeredVirtRealms',
'certificates': 'certificates',
'comment': 'comment',
'default_project': 'defaultProject',
'email': 'email',
'firstname': 'firstname',
'id': 'id',
'lastname': 'lastname',
'log_entries': 'logEntries',
'organization': 'organization',
'project_count': 'projectCount',
'state': 'state',
'terms_of_service_accepted': 'termsOfServiceAccepted',
'username': 'username'
}
def __init__(self, created_at=None, updated_at=None, administered_clouds=None, administered_virt_realms=None, certificates=None, comment=None, default_project=None, email=None, firstname=None, id=None, lastname=None, log_entries=None, organization=None, project_count=None, state=None, terms_of_service_accepted=None, username=None, local_vars_configuration=None): # noqa: E501
"""User - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._created_at = None
self._updated_at = None
self._administered_clouds = None
self._administered_virt_realms = None
self._certificates = None
self._comment = None
self._default_project = None
self._email = None
self._firstname = None
self._id = None
self._lastname = None
self._log_entries = None
self._organization = None
self._project_count = None
self._state = None
self._terms_of_service_accepted = None
self._username = None
self.discriminator = None
if created_at is not None:
self.created_at = created_at
if updated_at is not None:
self.updated_at = updated_at
if administered_clouds is not None:
self.administered_clouds = administered_clouds
if administered_virt_realms is not None:
self.administered_virt_realms = administered_virt_realms
if certificates is not None:
self.certificates = certificates
if comment is not None:
self.comment = comment
if default_project is not None:
self.default_project = default_project
if email is not None:
self.email = email
if firstname is not None:
self.firstname = firstname
if id is not None:
self.id = id
if lastname is not None:
self.lastname = lastname
if log_entries is not None:
self.log_entries = log_entries
if organization is not None:
self.organization = organization
if project_count is not None:
self.project_count = project_count
if state is not None:
self.state = state
if terms_of_service_accepted is not None:
self.terms_of_service_accepted = terms_of_service_accepted
if username is not None:
self.username = username
@property
def created_at(self):
"""Gets the created_at of this User. # noqa: E501
:return: The created_at of this User. # noqa: E501
:rtype: int
"""
return self._created_at
@created_at.setter
def created_at(self, created_at):
"""Sets the created_at of this User.
:param created_at: The created_at of this User. # noqa: E501
:type: int
"""
self._created_at = created_at
@property
def updated_at(self):
"""Gets the updated_at of this User. # noqa: E501
:return: The updated_at of this User. # noqa: E501
:rtype: int
"""
return self._updated_at
@updated_at.setter
def updated_at(self, updated_at):
"""Sets the updated_at of this User.
:param updated_at: The updated_at of this User. # noqa: E501
:type: int
"""
self._updated_at = updated_at
@property
def administered_clouds(self):
"""Gets the administered_clouds of this User. # noqa: E501
:return: The administered_clouds of this User. # noqa: E501
:rtype: list[Cloud]
"""
return self._administered_clouds
@administered_clouds.setter
def administered_clouds(self, administered_clouds):
"""Sets the administered_clouds of this User.
:param administered_clouds: The administered_clouds of this User. # noqa: E501
:type: list[Cloud]
"""
self._administered_clouds = administered_clouds
@property
def administered_virt_realms(self):
"""Gets the administered_virt_realms of this User. # noqa: E501
:return: The administered_virt_realms of this User. # noqa: E501
:rtype: list[VirtualizationRealm]
"""
return self._administered_virt_realms
@administered_virt_realms.setter
def administered_virt_realms(self, administered_virt_realms):
"""Sets the administered_virt_realms of this User.
:param administered_virt_realms: The administered_virt_realms of this User. # noqa: E501
:type: list[VirtualizationRealm]
"""
self._administered_virt_realms = administered_virt_realms
@property
def certificates(self):
"""Gets the certificates of this User. # noqa: E501
:return: The certificates of this User. # noqa: E501
:rtype: list[Certificate]
"""
return self._certificates
@certificates.setter
def certificates(self, certificates):
"""Sets the certificates of this User.
:param certificates: The certificates of this User. # noqa: E501
:type: list[Certificate]
"""
self._certificates = certificates
@property
def comment(self):
"""Gets the comment of this User. # noqa: E501
:return: The comment of this User. # noqa: E501
:rtype: str
"""
return self._comment
@comment.setter
def comment(self, comment):
"""Sets the comment of this User.
:param comment: The comment of this User. # noqa: E501
:type: str
"""
self._comment = comment
@property
def default_project(self):
"""Gets the default_project of this User. # noqa: E501
:return: The default_project of this User. # noqa: E501
:rtype: Project
"""
return self._default_project
@default_project.setter
def default_project(self, default_project):
"""Sets the default_project of this User.
:param default_project: The default_project of this User. # noqa: E501
:type: Project
"""
self._default_project = default_project
@property
def email(self):
"""Gets the email of this User. # noqa: E501
:return: The email of this User. # noqa: E501
:rtype: str
"""
return self._email
@email.setter
def email(self, email):
"""Sets the email of this User.
:param email: The email of this User. # noqa: E501
:type: str
"""
self._email = email
@property
def firstname(self):
"""Gets the firstname of this User. # noqa: E501
:return: The firstname of this User. # noqa: E501
:rtype: str
"""
return self._firstname
@firstname.setter
def firstname(self, firstname):
"""Sets the firstname of this User.
:param firstname: The firstname of this User. # noqa: E501
:type: str
"""
self._firstname = firstname
@property
def id(self):
"""Gets the id of this User. # noqa: E501
:return: The id of this User. # noqa: E501
:rtype: int
"""
return self._id
@id.setter
def id(self, id):
"""Sets the id of this User.
:param id: The id of this User. # noqa: E501
:type: int
"""
self._id = id
@property
def lastname(self):
"""Gets the lastname of this User. # noqa: E501
:return: The lastname of this User. # noqa: E501
:rtype: str
"""
return self._lastname
@lastname.setter
def lastname(self, lastname):
"""Sets the lastname of this User.
:param lastname: The lastname of this User. # noqa: E501
:type: str
"""
self._lastname = lastname
@property
def log_entries(self):
"""Gets the log_entries of this User. # noqa: E501
:return: The log_entries of this User. # noqa: E501
:rtype: list[LogEntry]
"""
return self._log_entries
@log_entries.setter
def log_entries(self, log_entries):
"""Sets the log_entries of this User.
:param log_entries: The log_entries of this User. # noqa: E501
:type: list[LogEntry]
"""
self._log_entries = log_entries
@property
def organization(self):
"""Gets the organization of this User. # noqa: E501
:return: The organization of this User. # noqa: E501
:rtype: str
"""
return self._organization
@organization.setter
def organization(self, organization):
"""Sets the organization of this User.
:param organization: The organization of this User. # noqa: E501
:type: str
"""
self._organization = organization
@property
def project_count(self):
"""Gets the project_count of this User. # noqa: E501
:return: The project_count of this User. # noqa: E501
:rtype: int
"""
return self._project_count
@project_count.setter
def project_count(self, project_count):
"""Sets the project_count of this User.
:param project_count: The project_count of this User. # noqa: E501
:type: int
"""
self._project_count = project_count
@property
def state(self):
"""Gets the state of this User. # noqa: E501
:return: The state of this User. # noqa: E501
:rtype: str
"""
return self._state
@state.setter
def state(self, state):
"""Sets the state of this User.
:param state: The state of this User. # noqa: E501
:type: str
"""
allowed_values = ["REQUESTED", "ACTIVE", "INACTIVE"] # noqa: E501
if self.local_vars_configuration.client_side_validation and state not in allowed_values: # noqa: E501
raise ValueError(
"Invalid value for `state` ({0}), must be one of {1}" # noqa: E501
.format(state, allowed_values)
)
self._state = state
@property
def terms_of_service_accepted(self):
"""Gets the terms_of_service_accepted of this User. # noqa: E501
:return: The terms_of_service_accepted of this User. # noqa: E501
:rtype: bool
"""
return self._terms_of_service_accepted
@terms_of_service_accepted.setter
def terms_of_service_accepted(self, terms_of_service_accepted):
"""Sets the terms_of_service_accepted of this User.
:param terms_of_service_accepted: The terms_of_service_accepted of this User. # noqa: E501
:type: bool
"""
self._terms_of_service_accepted = terms_of_service_accepted
@property
def username(self):
"""Gets the username of this User. # noqa: E501
:return: The username of this User. # noqa: E501
:rtype: str
"""
return self._username
@username.setter
def username(self, username):
"""Sets the username of this User.
:param username: The username of this User. # noqa: E501
:type: str
"""
self._username = username
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, User):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, User):
return True
return self.to_dict() != other.to_dict()
| 15,633 | 4,831 |
from __future__ import print_function
import json
import boto3
print('Loading function')
s3 = boto3.client('s3')
bucket_of_interest = "secretcatpics"
# For a PutObjectAcl API Event, gets the bucket and key name from the event
# If the object is not private, then it makes the object private by making a
# PutObjectAcl call.
def lambda_handler(event, context):
# Get bucket name from the event
bucket = event['Records'][0]['s3']['bucket']['name']
if (bucket != bucket_of_interest):
print("Doing nothing for bucket = " + bucket)
return
# Get key name from the event
key = event['Records'][0]['s3']['object']['key']
# If object is not private then make it private
if not (is_private(bucket, key)):
print("Object with key=" + key + " in bucket=" + bucket + " is not private!")
make_private(bucket, key)
else:
print("Object with key=" + key + " in bucket=" + bucket + " is already private.")
# Checks an object with given bucket and key is private
def is_private(bucket, key):
# Get the object ACL from S3
acl = s3.get_object_acl(Bucket=bucket, Key=key)
# Private object should have only one grant which is the owner of the object
if (len(acl['Grants']) > 1):
return False
# If canonical owner and grantee ids do no match, then conclude that the object
# is not private
owner_id = acl['Owner']['ID']
grantee_id = acl['Grants'][0]['Grantee']['ID']
if (owner_id != grantee_id):
return False
return True
# Makes an object with given bucket and key private by calling the PutObjectAcl API.
def make_private(bucket, key):
s3.put_object_acl(Bucket=bucket, Key=key, ACL="private")
print("Object with key=" + key + " in bucket=" + bucket + " is marked as private.")
| 1,703 | 566 |
import unittest
from apiclient.errors import HttpError
from google.appengine.ext import testbed, ndb
from mock import patch, Mock
from src.commons.big_query.copy_job_async.copy_job.copy_job_request \
import CopyJobRequest
from src.commons.big_query.copy_job_async.copy_job.copy_job_service \
import CopyJobService
from src.commons.big_query.copy_job_async.post_copy_action_request import \
PostCopyActionRequest
from src.commons.big_query.copy_job_async.result_check.result_check_request \
import ResultCheckRequest
from src.commons.big_query.copy_job_async.task_creator import TaskCreator
from src.commons.big_query.big_query import BigQuery
from src.commons.big_query.big_query_job_reference import BigQueryJobReference
from src.commons.big_query.big_query_table import BigQueryTable
class TestCopyJobService(unittest.TestCase):
def setUp(self):
self.testbed = testbed.Testbed()
self.testbed.activate()
ndb.get_context().clear_cache()
patch('googleapiclient.discovery.build').start()
patch(
'oauth2client.client.GoogleCredentials.get_application_default') \
.start()
self._create_http = patch.object(BigQuery, '_create_http').start()
self.example_source_bq_table = BigQueryTable('source_project_id_1',
'source_dataset_id_1',
'source_table_id_1')
self.example_target_bq_table = BigQueryTable('target_project_id_1',
'target_dataset_id_1',
'target_table_id_1')
def tearDown(self):
patch.stopall()
self.testbed.deactivate()
@patch.object(BigQuery, 'insert_job',
return_value=BigQueryJobReference(
project_id='test_project',
job_id='job123',
location='EU'))
@patch.object(TaskCreator, 'create_copy_job_result_check')
def test_that_post_copy_action_request_is_passed(
self, create_copy_job_result_check, _):
# given
post_copy_action_request = \
PostCopyActionRequest(url='/my/url', data={'key1': 'value1'})
# when
CopyJobService().run_copy_job_request(
CopyJobRequest(
task_name_suffix='task_name_suffix',
copy_job_type_id='test-process',
source_big_query_table=self.example_source_bq_table,
target_big_query_table=self.example_target_bq_table,
create_disposition="CREATE_IF_NEEDED",
write_disposition="WRITE_EMPTY",
retry_count=0,
post_copy_action_request=post_copy_action_request
)
)
# then
create_copy_job_result_check.assert_called_once_with(
ResultCheckRequest(
task_name_suffix='task_name_suffix',
copy_job_type_id='test-process',
job_reference=BigQueryJobReference(
project_id='test_project',
job_id='job123',
location='EU'),
retry_count=0,
post_copy_action_request=post_copy_action_request
)
)
@patch.object(BigQuery, 'insert_job',
return_value=BigQueryJobReference(
project_id='test_project',
job_id='job123',
location='EU'))
@patch.object(TaskCreator, 'create_copy_job_result_check')
def test_that_create_and_write_disposition_are_passed_to_result_check(
self, create_copy_job_result_check, _):
# given
create_disposition = "SOME_CREATE_DISPOSITION"
write_disposition = "SOME_WRITE_DISPOSITION"
# when
CopyJobService().run_copy_job_request(
CopyJobRequest(
task_name_suffix='task_name_suffix',
copy_job_type_id='test-process',
source_big_query_table=self.example_source_bq_table,
target_big_query_table=self.example_target_bq_table,
create_disposition=create_disposition,
write_disposition=write_disposition,
retry_count=0,
post_copy_action_request=None
)
)
# then
create_copy_job_result_check.assert_called_once_with(
ResultCheckRequest(
task_name_suffix='task_name_suffix',
copy_job_type_id='test-process',
job_reference=BigQueryJobReference(
project_id='test_project',
job_id='job123',
location='EU'),
retry_count=0,
post_copy_action_request=None
)
)
@patch.object(BigQuery, 'insert_job')
@patch('time.sleep', side_effect=lambda _: None)
def test_that_copy_table_should_throw_error_after_exception_not_being_http_error_thrown_on_copy_job_creation(
self, _, insert_job):
# given
error_message = 'test exception'
insert_job.side_effect = Exception(error_message)
request = CopyJobRequest(
task_name_suffix=None,
copy_job_type_id=None,
source_big_query_table=self.example_source_bq_table,
target_big_query_table=self.example_target_bq_table,
create_disposition="CREATE_IF_NEEDED",
write_disposition="WRITE_EMPTY"
)
# when
with self.assertRaises(Exception) as context:
CopyJobService().run_copy_job_request(request)
# then
self.assertTrue(error_message in context.exception)
@patch.object(BigQuery, 'insert_job')
@patch('time.sleep', side_effect=lambda _: None)
def test_that_copy_table_should_throw_unhandled_errors(self, _, insert_job):
# given
exception = HttpError(Mock(status=500), 'internal error')
exception._get_reason = Mock(return_value='internal error')
insert_job.side_effect = exception
request = CopyJobRequest(
task_name_suffix=None,
copy_job_type_id=None,
source_big_query_table=self.example_source_bq_table,
target_big_query_table=self.example_target_bq_table,
create_disposition="CREATE_IF_NEEDED",
write_disposition="WRITE_EMPTY"
)
# when
with self.assertRaises(HttpError) as context:
CopyJobService().run_copy_job_request(request)
# then
self.assertEqual(context.exception, exception)
@patch.object(BigQuery, 'insert_job')
@patch.object(TaskCreator, 'create_post_copy_action')
def test_that_copy_table_should_create_correct_post_copy_action_if_404_http_error_thrown_on_copy_job_creation(
self, create_post_copy_action, insert_job):
# given
error = HttpError(Mock(status=404), 'not found')
error._get_reason = Mock(return_value='not found')
insert_job.side_effect = error
post_copy_action_request = PostCopyActionRequest(url='/my/url', data={'key1': 'value1'})
request = CopyJobRequest(
task_name_suffix='task_name_suffix',
copy_job_type_id='test-process',
source_big_query_table=self.example_source_bq_table,
target_big_query_table=self.example_target_bq_table,
create_disposition="CREATE_IF_NEEDED",
write_disposition="WRITE_EMPTY",
retry_count=0,
post_copy_action_request=post_copy_action_request
)
# when
CopyJobService().run_copy_job_request(request)
# then
create_post_copy_action.assert_called_once_with(
copy_job_type_id='test-process',
post_copy_action_request=post_copy_action_request,
job_json={
'status': {
'state': 'DONE',
'errors': [
{
'reason': 'Invalid',
'message': (
"404 while creating Copy Job from {} to {}".format(
self.example_source_bq_table, self.example_target_bq_table))
}
]
},
'configuration': {
'copy': {
'sourceTable': {
'projectId': self.example_source_bq_table.get_project_id(),
'tableId': self.example_source_bq_table.get_table_id(),
'datasetId': self.example_source_bq_table.get_dataset_id()
},
'destinationTable': {
'projectId': self.example_target_bq_table.get_project_id(),
'tableId': self.example_target_bq_table.get_table_id(),
'datasetId': self.example_target_bq_table.get_dataset_id()
}
}
}
}
)
@patch.object(BigQuery, 'insert_job')
@patch.object(TaskCreator, 'create_post_copy_action')
def test_that_copy_table_should_create_correct_post_copy_action_if_access_denied_http_error_thrown_on_copy_job_creation(
self, create_post_copy_action, insert_job):
# given
http_error_content = "{\"error\": " \
" {\"errors\": [" \
" {\"reason\": \"Access Denied\"," \
" \"message\": \"Access Denied\"," \
" \"location\": \"US\"" \
" }]," \
" \"code\": 403," \
" \"message\": \"Access Denied\"}}"
insert_job.side_effect = HttpError(Mock(status=403), http_error_content)
post_copy_action_request = PostCopyActionRequest(url='/my/url', data={
'key1': 'value1'})
request = CopyJobRequest(
task_name_suffix='task_name_suffix',
copy_job_type_id='test-process',
source_big_query_table=self.example_source_bq_table,
target_big_query_table=self.example_target_bq_table,
create_disposition="CREATE_IF_NEEDED",
write_disposition="WRITE_EMPTY",
retry_count=0,
post_copy_action_request=post_copy_action_request
)
# when
CopyJobService().run_copy_job_request(request)
# then
create_post_copy_action.assert_called_once_with(
copy_job_type_id='test-process',
post_copy_action_request=post_copy_action_request,
job_json={
'status': {
'state': 'DONE',
'errors': [
{
'reason': 'Invalid',
'message': (
"Access Denied while creating Copy Job from {} to {}".format(
self.example_source_bq_table, self.example_target_bq_table))
}
]
},
'configuration': {
'copy': {
'sourceTable': {
'projectId': self.example_source_bq_table.get_project_id(),
'tableId': self.example_source_bq_table.get_table_id(),
'datasetId': self.example_source_bq_table.get_dataset_id()
},
'destinationTable': {
'projectId': self.example_target_bq_table.get_project_id(),
'tableId': self.example_target_bq_table.get_table_id(),
'datasetId': self.example_target_bq_table.get_dataset_id()
}
}
}
}
)
@patch.object(BigQuery, 'get_job')
@patch.object(BigQuery, 'insert_job')
@patch.object(TaskCreator, 'create_copy_job_result_check')
def test_that_copy_table_will_try_to_wait_if_deadline_exceeded(
self, create_copy_job_result_check, insert_job, get_job):
# given
http_error_content = "{\"error\": " \
" {\"errors\": [" \
" {\"reason\": \"Deadline exceeded\"," \
" \"message\": \"Deadline exceeded\"," \
" \"location\": \"US\"" \
" }]," \
" \"code\": 500," \
" \"message\": \"Deadline exceeded\"}}"
successful_job_json = {
'status': {
'state': 'DONE'
},
'jobReference': {
'projectId': self.example_target_bq_table.get_project_id(),
'location': 'EU',
'jobId': 'job123',
},
'configuration': {
'copy': {
'sourceTable': {
'projectId': self.example_source_bq_table.get_project_id(),
'tableId': self.example_source_bq_table.get_table_id(),
'datasetId': self.example_source_bq_table.get_dataset_id()
},
'destinationTable': {
'projectId': self.example_target_bq_table.get_project_id(),
'tableId': self.example_target_bq_table.get_table_id(),
'datasetId': self.example_target_bq_table.get_dataset_id()
}
}
}
}
insert_job.side_effect = HttpError(Mock(status=500), http_error_content)
get_job.return_value = successful_job_json
request = CopyJobRequest(
task_name_suffix='task_name_suffix',
copy_job_type_id='test-process',
source_big_query_table=self.example_source_bq_table,
target_big_query_table=self.example_target_bq_table,
create_disposition="CREATE_IF_NEEDED",
write_disposition="WRITE_EMPTY",
retry_count=0,
post_copy_action_request=None
)
# when
CopyJobService().run_copy_job_request(request)
# then
create_copy_job_result_check.assert_called_once_with(
ResultCheckRequest(
task_name_suffix='task_name_suffix',
copy_job_type_id='test-process',
job_reference=BigQueryJobReference(
project_id=self.example_target_bq_table.get_project_id(),
job_id='job123',
location='EU'
),
retry_count=0,
post_copy_action_request=None
)
)
@patch('src.commons.big_query.big_query_table_metadata.BigQueryTableMetadata')
@patch.object(TaskCreator, 'create_copy_job_result_check')
@patch.object(CopyJobService, '_create_random_job_id',
return_value='random_job_123')
@patch.object(BigQuery, 'insert_job',
side_effect=[HttpError(Mock(status=503), 'internal error'),
HttpError(Mock(status=409), 'job exists')])
@patch('time.sleep', side_effect=lambda _: None)
def test_bug_regression_job_already_exists_after_internal_error(
self, _, insert_job, _create_random_job_id,
create_copy_job_result_check, table_metadata
):
# given
post_copy_action_request = \
PostCopyActionRequest(url='/my/url', data={'key1': 'value1'})
table_metadata._BigQueryTableMetadata__get_table_or_partition.return_value.get_location.return_value='EU'
# when
CopyJobService().run_copy_job_request(
CopyJobRequest(
task_name_suffix='task_name_suffix',
copy_job_type_id='test-process',
source_big_query_table=self.example_source_bq_table,
target_big_query_table=self.example_target_bq_table,
create_disposition="CREATE_IF_NEEDED",
write_disposition="WRITE_EMPTY",
retry_count=0,
post_copy_action_request=post_copy_action_request
)
)
# then
self.assertEqual(insert_job.call_count, 2)
create_copy_job_result_check.assert_called_once_with(
ResultCheckRequest(
task_name_suffix='task_name_suffix',
copy_job_type_id='test-process',
job_reference=BigQueryJobReference(
project_id='target_project_id_1',
job_id='random_job_123',
location='EU'),
retry_count=0,
post_copy_action_request=post_copy_action_request
)
)
| 17,156 | 4,890 |
import cv2
import numpy as np
import matplotlib.pyplot as plt
image = np.flip(cv2.imread('../img/dog_muffin.jpg'), axis=2)
mask = np.zeros(image.shape[:2], dtype="uint8")
cv2.rectangle(mask, (90, 120), (160, 190), 255, -1)
masked = cv2.bitwise_and(image, image, mask=mask)
plt.figure(figsize=(20, 10))
plt.imshow(np.flip(masked, axis =2))
plt.title('Masked Image'), plt.xticks([]), plt.yticks([])
| 399 | 182 |
from __future__ import annotations
from typing import Any, Dict, List
from abc import ABC, abstractmethod
from datetime import datetime
from collections import namedtuple
from lazy_property import LazyProperty
from .sqlalchemy_tables import ObjectDefinition
import wysdom
from jetavator.services import ComputeServiceABC
from .ProjectABC import ProjectABC
VaultObjectKey = namedtuple('VaultObjectKey', ['type', 'name'])
HubKeyColumn = namedtuple('HubKeyColumn', ['name', 'source'])
class VaultObject(wysdom.UserObject, wysdom.RegistersSubclasses, ABC):
name: str = wysdom.UserProperty(str)
type: str = wysdom.UserProperty(str)
optional_yaml_properties = []
def __init__(
self,
project: ProjectABC,
sqlalchemy_object: ObjectDefinition
) -> None:
self.project = project
self._sqlalchemy_object = sqlalchemy_object
super().__init__(self.definition)
def __repr__(self) -> str:
class_name = type(self).__name__
return f'{class_name}({self.name})'
@classmethod
def subclass_instance(
cls,
project: ProjectABC,
definition: ObjectDefinition
) -> VaultObject:
return cls.registered_subclass_instance(
definition.type,
project,
definition
)
@LazyProperty
def key(self) -> VaultObjectKey:
return VaultObjectKey(self.type, self.name)
@property
def definition(self) -> Dict[str, Any]:
return self._sqlalchemy_object.definition
def export_sqlalchemy_object(self) -> ObjectDefinition:
if self._sqlalchemy_object.version != str(self.project.version):
raise ValueError(
"ObjectDefinition version must match project version "
"and cannot be updated."
)
self._sqlalchemy_object.deploy_dt = str(datetime.now())
return self._sqlalchemy_object
@abstractmethod
def validate(self) -> None:
pass
@property
def compute_service(self) -> ComputeServiceABC:
return self.project.compute_service
@property
def full_name(self) -> str:
return f'{self.type}_{self.name}'
@property
def checksum(self) -> str:
return str(self._sqlalchemy_object.checksum)
@property
def dependent_satellites(self) -> List[VaultObject]:
return [
satellite
for satellite in self.project.satellites.values()
if any(
dependency.type == self.type
and dependency.name == self.name
for dependency in satellite.pipeline.dependencies
)
]
| 2,676 | 747 |
from .abstract import Kernel
from .auto import AutoKernel
from .numpy import *
| 79 | 22 |
from django import forms
from .models import Announcement
# from .models import Role
from .models import Assignment
from .models import CourseMaterial
from .models import Grade
from .models import StudentUploadFile
from .models import Syllabus
from .models import Assistant
from django.forms import ClearableFileInput
# from .models import Instructor
# from .models import Student
# from .models import Assistant
class LoginForm (forms.Form):
username = forms.EmailField()
password = forms.CharField(widget=forms.PasswordInput, label="Password")
class AnnouncementForm (forms.ModelForm):
class Meta:
model = Announcement
fields = ('title', 'content')
class AssignmentForm(forms.ModelForm):
class Meta:
model = Assignment
fields = ('title', 'content', 'doc_file', 'due_date')
class CourseMaterialForm(forms.ModelForm):
print("CourseMaterialForm")
class Meta:
model = CourseMaterial
fields = ('title', 'doc_file')
class GradeForm(forms.ModelForm):
print("GradeForm")
class Meta:
model = Grade
fields = ('title', 'doc_file')
class StudentUploadFileForm(forms.ModelForm):
class Meta:
model = StudentUploadFile
fields = ('doc_file', )
class SyllabusForm(forms.ModelForm):
class Meta:
model = Syllabus
fields = ('doc_file', )
# class AssistantForm(forms.ModelForm):
# class Meta:
# model = Assistant
# fields = ('assistant_id', ) | 1,500 | 429 |
#
# plots.py -- classes for plots added to Ginga canvases.
#
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
import sys
import numpy as np
from ginga.canvas.CanvasObject import (CanvasObjectBase, _color,
register_canvas_types,
colors_plus_none)
from ginga.misc import Bunch
from ginga.canvas.types.layer import CompoundObject
from .basic import Path
from ginga.misc.ParamSet import Param
class XYPlot(CanvasObjectBase):
"""
Plotable object that defines a single path representing an X/Y line plot.
Like a Path, but has some optimization to reduce the actual numbers of
points in the path, depending on the scale and pan of the viewer.
"""
@classmethod
def get_params_metadata(cls):
return [
Param(name='linewidth', type=int, default=2,
min=0, max=20, widget='spinbutton', incr=1,
description="Width of outline"),
Param(name='linestyle', type=str, default='solid',
valid=['solid', 'dash'],
description="Style of outline (default: solid)"),
Param(name='color',
valid=colors_plus_none, type=_color, default='black',
description="Color of text"),
Param(name='alpha', type=float, default=1.0,
min=0.0, max=1.0, widget='spinfloat', incr=0.05,
description="Opacity of outline"),
]
def __init__(self, name=None, color='black',
linewidth=1, linestyle='solid',
alpha=1.0, x_acc=None, y_acc=None, **kwargs):
super(XYPlot, self).__init__(color=color, linewidth=linewidth,
linestyle=linestyle, alpha=alpha,
**kwargs)
self.name = name
self.kind = 'xyplot'
self.x_func = None
nul_arr = np.array([])
if x_acc is not None:
self.x_func = lambda arr: nul_arr if arr.size == 0 else x_acc(arr)
if y_acc is None:
y_acc = np.mean
self.y_func = lambda arr: nul_arr if arr.size == 0 else y_acc(arr)
self.points = np.copy(nul_arr)
self.limits = np.array([(0.0, 0.0), (0.0, 0.0)])
self.plot_xlim = (None, None)
self.path = Path([], color=color, linewidth=linewidth,
linestyle=linestyle, alpha=alpha, coord='data')
self.path.get_cpoints = self.get_cpoints
def plot_xy(self, xpts, ypts):
"""Convenience function for plotting X and Y points that are in
separate arrays.
"""
self.plot(np.asarray((xpts, ypts)).T)
def plot(self, points, limits=None):
"""Plot `points`, a list, tuple or array of (x, y) points.
Parameter
---------
points : array-like
list, tuple or array of (x, y) points
limits : array-like, optional
array of (xmin, ymin), (xmax, ymax)
Limits will be calculated if not passed in.
"""
self.points = np.asarray(points)
self.plot_xlim = (None, None)
# set or calculate limits
if limits is not None:
# passing limits saves costly min/max calculation
self.limits = np.asarray(limits)
else:
self._calc_limits(self.points)
def _calc_limits(self, points):
"""Internal routine to calculate the limits of `points`.
"""
# TODO: what should limits be if there are no points?
if len(points) == 0:
self.limits = np.array([[0.0, 0.0], [0.0, 0.0]])
else:
x_vals, y_vals = points.T
self.limits = np.array([(x_vals.min(), y_vals.min()),
(x_vals.max(), y_vals.max())])
def calc_points(self, viewer, start_x, stop_x):
"""Called when recalculating our path's points.
"""
# in case X axis is flipped
start_x, stop_x = min(start_x, stop_x), max(start_x, stop_x)
new_xlim = (start_x, stop_x)
if new_xlim == self.plot_xlim:
# X limits are the same, no need to recalculate points
return
self.plot_xlim = new_xlim
points = self.get_data_points(points=self.points)
if len(points) == 0:
self.path.points = points
return
x_data, y_data = points.T
# if we can determine the visible region shown on the plot
# limit the points to those within the region
if np.all(np.isfinite([start_x, stop_x])):
idx = np.logical_and(x_data >= start_x, x_data <= stop_x)
points = points[idx]
if self.x_func is not None:
# now find all points position in canvas X coord
cpoints = self.get_cpoints(viewer, points=points)
cx, cy = cpoints.T
# Reduce each group of Y points that map to a unique X via a
# function that reduces to a single value. The desirable function
# will depend on the function of the plot, but mean() would be a
# sensible default
_, i = np.unique(cx, return_index=True)
gr_pts = np.split(points, i)
x_data = np.array([self.x_func(a.T[0]) for a in gr_pts
if len(a) > 0])
y_data = np.array([self.y_func(a.T[1]) for a in gr_pts
if len(a) > 0])
assert len(x_data) == len(y_data)
points = np.array((x_data, y_data)).T
self.path.points = points
def recalc(self, viewer):
"""Called when recalculating our path's points.
"""
# select only points within range of the current pan/zoom
bbox = viewer.get_pan_rect()
if bbox is None:
self.path.points = []
return
start_x, stop_x = bbox[0][0], bbox[2][0]
self.calc_points(viewer, start_x, stop_x)
def get_cpoints(self, viewer, points=None, no_rotate=False):
"""Mostly internal routine used to calculate the native positions
to draw the plot.
"""
# If points are passed, they are assumed to be in data space
if points is None:
points = self.path.get_points()
return viewer.tform['data_to_plot'].to_(points)
def update_resize(self, viewer, dims):
"""Called when the viewer is resized."""
self.recalc(viewer)
def get_latest(self):
"""Get the latest (last) point on the plot. Returns None if there
are no points.
"""
if len(self.points) == 0:
return None
return self.points[-1]
def get_limits(self, lim_type):
"""Get the limits of the data or the visible part of the plot.
If `lim_type` == 'data' returns the limits of all the data points.
Otherwise returns the limits of the visibly plotted area. Limits
are returned in the form ((xmin, ymin), (xmax, ymax)), as an array.
"""
if lim_type == 'data':
# data limits
return np.asarray(self.limits)
# plot limits
self.path.crdmap = self.crdmap
if len(self.path.points) > 0:
llur = self.path.get_llur()
llur = [llur[0:2], llur[2:4]]
else:
llur = [(0.0, 0.0), (0.0, 0.0)]
return np.asarray(llur)
def draw(self, viewer):
"""Draw the plot. Normally not called by the user, but by the viewer
as needed.
"""
self.path.crdmap = self.crdmap
self.recalc(viewer)
if len(self.path.points) > 0:
self.path.draw(viewer)
class Axis(CompoundObject):
"""
Base class for axis plotables.
"""
def __init__(self, title=None, num_labels=4, font='sans',
fontsize=10.0):
super(Axis, self).__init__()
self.aide = None
self.num_labels = num_labels
self.title = title
self.font = font
self.fontsize = fontsize
self.grid_alpha = 1.0
self.format_value = self._format_value
def register_decor(self, aide):
self.aide = aide
def _format_value(self, v):
"""Default formatter for XAxis labels.
"""
return "%.4g" % v
def set_grid_alpha(self, alpha):
"""Set the transparency (alpha) of the XAxis grid lines.
`alpha` should be between 0.0 and 1.0
"""
for i in range(self.num_labels):
grid = self.grid[i]
grid.alpha = alpha
def get_data_xy(self, viewer, pt):
arr_pts = np.asarray(pt)
x, y = viewer.tform['data_to_plot'].from_(arr_pts).T[:2]
flips = viewer.get_transforms()
if flips[2]:
x, y = y, x
return (x, y)
def get_title(self):
titles_d = self.aide.get_axes_titles()
return titles_d[self.kind]
def add_plot(self, viewer, plot_src):
# Axis objects typically do not need to do anything when a
# plot is added--they recalculate labels in update_elements()
pass
def delete_plot(self, viewer, plot_src):
# Axis objects typically do not need to do anything when a
# plot is deleted--they recalculate labels in update_elements()
pass
class XAxis(Axis):
"""
Plotable object that defines X axis labels and grid lines.
"""
def __init__(self, title=None, num_labels=4, font='sans',
fontsize=10.0):
super(XAxis, self).__init__(title=title, num_labels=num_labels,
font=font, fontsize=fontsize)
self.kind = 'axis_x'
self.txt_ht = 0
self.title_wd = 0
self.pad_px = 5
def register_decor(self, aide):
self.aide = aide
# add X grid
self.grid = Bunch.Bunch()
for i in range(self.num_labels):
self.grid[i] = aide.dc.Line(0, 0, 0, 0, color=aide.grid_fg,
linestyle='dash', linewidth=1,
alpha=self.grid_alpha,
coord='window')
self.objects.append(self.grid[i])
self.axis_bg = aide.dc.Rectangle(0, 0, 100, 100, color=aide.norm_bg,
fill=True, fillcolor=aide.axis_bg,
coord='window')
self.objects.append(self.axis_bg)
self.lbls = Bunch.Bunch()
for i in range(self.num_labels):
self.lbls[i] = aide.dc.Text(0, 0, text='', color='black',
font=self.font,
fontsize=self.fontsize,
coord='window')
self.objects.append(self.lbls[i])
self._title = aide.dc.Text(0, 0, text='', color='black',
font=self.font, fontsize=self.fontsize,
alpha=0.0,
coord='window')
self.objects.append(self._title)
def update_elements(self, viewer):
"""This method is called if the plot is set with new points,
or is scaled or panned with existing points.
Update the XAxis labels to reflect the new values and/or pan/scale.
"""
for i in range(self.num_labels):
lbl = self.lbls[i]
# get data coord equivalents
x, y = self.get_data_xy(viewer, (lbl.x, lbl.y))
# format according to user's preference
lbl.text = self.format_value(x)
def update_bbox(self, viewer, dims):
"""This method is called if the viewer's window is resized.
Update all the XAxis elements to reflect the new dimensions.
"""
title = self.get_title()
self._title.text = title if title is not None else '555.55'
self.title_wd, self.txt_ht = viewer.renderer.get_dimensions(self._title)
wd, ht = dims[:2]
y_hi = ht
if title is not None:
# remove Y space for X axis title
y_hi -= self.txt_ht + 4
# remove Y space for X axis labels
y_hi -= self.txt_ht + self.pad_px
self.aide.update_plot_bbox(y_hi=y_hi)
def update_resize(self, viewer, dims, xy_lim):
"""This method is called if the viewer's window is resized.
Update all the XAxis elements to reflect the new dimensions.
"""
x_lo, y_lo, x_hi, y_hi = xy_lim
wd, ht = dims[:2]
# position axis title
title = self.get_title()
cx, cy = wd // 2 - self.title_wd // 2, ht - 4
if title is not None:
self._title.x = cx
self._title.y = cy
self._title.alpha = 1.0
cy = cy - self.txt_ht
else:
self._title.alpha = 0.0
# set X labels/grid as needed
# calculate evenly spaced interval on X axis in window coords
a = (x_hi - x_lo) // (self.num_labels - 1)
cx = x_lo
for i in range(self.num_labels):
lbl = self.lbls[i]
lbl.x, lbl.y = cx, cy
# get data coord equivalents
x, y = self.get_data_xy(viewer, (cx, cy))
# convert to formatted label
lbl.text = self.format_value(x)
grid = self.grid[i]
grid.x1 = grid.x2 = cx
grid.y1, grid.y2 = y_lo, y_hi
cx += a
self.axis_bg.x1, self.axis_bg.x2 = 0, wd
self.axis_bg.y1, self.axis_bg.y2 = y_hi, ht
class YAxis(Axis):
"""
Plotable object that defines Y axis labels and grid lines.
"""
def __init__(self, title=None, num_labels=4, font='sans', fontsize=10.0):
super(YAxis, self).__init__(title=title, num_labels=num_labels,
font=font, fontsize=fontsize)
self.kind = 'axis_y'
self.title_wd = 0
self.txt_wd = 0
self.txt_ht = 0
self.pad_px = 4
def register_decor(self, aide):
self.aide = aide
# add Y grid
self.grid = Bunch.Bunch()
for i in range(self.num_labels):
self.grid[i] = aide.dc.Line(0, 0, 0, 0, color=aide.grid_fg,
linestyle='dash', linewidth=1,
alpha=self.grid_alpha,
coord='window')
self.objects.append(self.grid[i])
# bg for RHS Y axis labels
self.axis_bg = aide.dc.Rectangle(0, 0, 100, 100, color=aide.norm_bg,
fill=True, fillcolor=aide.axis_bg,
coord='window')
self.objects.append(self.axis_bg)
# bg for LHS Y axis title
self.axis_bg2 = aide.dc.Rectangle(0, 0, 100, 100, color=aide.norm_bg,
fill=True, fillcolor=aide.axis_bg,
coord='window')
self.objects.append(self.axis_bg2)
# Y grid (tick) labels
self.lbls = Bunch.Bunch()
for i in range(self.num_labels):
self.lbls[i] = aide.dc.Text(0, 0, text='', color='black',
font=self.font,
fontsize=self.fontsize,
coord='window')
self.objects.append(self.lbls[i])
# Y title
self._title = aide.dc.Text(0, 0, text=self.title, color='black',
font=self.font,
fontsize=self.fontsize,
alpha=0.0,
rot_deg=90.0,
coord='window')
self.objects.append(self._title)
def update_elements(self, viewer):
"""This method is called if the plot is set with new points,
or is scaled or panned with existing points.
Update the YAxis labels to reflect the new values and/or pan/scale.
"""
# set Y labels/grid as needed
for i in range(self.num_labels):
lbl = self.lbls[i]
# get data coord equivalents
x, y = self.get_data_xy(viewer, (lbl.x, lbl.y))
lbl.text = self.format_value(y)
def update_bbox(self, viewer, dims):
"""This method is called if the viewer's window is resized.
Update all the YAxis elements to reflect the new dimensions.
"""
title = self.get_title()
self._title.text = title if title is not None else '555.55'
wd, ht = dims[:2]
self.title_wd, self.txt_ht = viewer.renderer.get_dimensions(self._title)
# TODO: not sure this will give us the maximum length of number
text = self.format_value(sys.float_info.max)
t = self.aide.dc.Text(0, 0, text=text,
fontsize=self.fontsize, font=self.font)
self.txt_wd, _ = viewer.renderer.get_dimensions(t)
if title is not None:
x_lo = self.txt_ht + 2 + self.pad_px
else:
x_lo = 0
x_hi = wd - (self.txt_wd + 4) - self.pad_px
self.aide.update_plot_bbox(x_lo=x_lo, x_hi=x_hi)
def update_resize(self, viewer, dims, xy_lim):
"""This method is called if the viewer's window is resized.
Update all the YAxis elements to reflect the new dimensions.
"""
x_lo, y_lo, x_hi, y_hi = xy_lim
wd, ht = dims[:2]
# position axis title
title = self.get_title()
cx = self.txt_ht + 2
cy = ht // 2 + self.title_wd // 2
if title is not None:
self._title.x = cx
self._title.y = cy
self._title.alpha = 1.0
else:
self._title.alpha = 0.0
cx = x_hi + self.pad_px
cy = y_hi
# set Y labels/grid as needed
a = (y_hi - y_lo) // (self.num_labels - 1)
for i in range(self.num_labels):
lbl = self.lbls[i]
# calculate evenly spaced interval on Y axis in window coords
lbl.x, lbl.y = cx, cy
# get data coord equivalents
x, y = self.get_data_xy(viewer, (cx, cy))
lbl.text = self.format_value(y)
grid = self.grid[i]
grid.x1, grid.x2 = x_lo, x_hi
grid.y1 = grid.y2 = cy
cy -= a
self.axis_bg.x1, self.axis_bg.x2 = x_hi, wd
self.axis_bg.y1, self.axis_bg.y2 = y_lo, y_hi
self.axis_bg2.x1, self.axis_bg2.x2 = 0, x_lo
self.axis_bg2.y1, self.axis_bg2.y2 = y_lo, y_hi
class PlotBG(CompoundObject):
"""
Plotable object that defines the plot background.
Can include a warning line and an alert line. If the last Y value
plotted exceeds the warning line then the background changes color.
For example, you might be plotting detector values and want to set
a warning if a certain threshold is crossed and an alert if the
detector has saturated (alerts are higher than warnings).
"""
def __init__(self, warn_y=None, alert_y=None, linewidth=1):
super(PlotBG, self).__init__()
self.y_lbl_info = [warn_y, alert_y]
self.warn_y = warn_y
self.alert_y = alert_y
self.linewidth = linewidth
# default warning check
self.check_warning = self._check_warning
self.norm_bg = 'white'
self.warn_bg = 'lightyellow'
self.alert_bg = 'mistyrose2'
self.kind = 'plot_bg'
self.pickable = True
self.opaque = True
def register_decor(self, aide):
self.aide = aide
# add a backdrop that we can change color for visual warnings
self.bg = aide.dc.Rectangle(0, 0, 100, 100, color=aide.norm_bg,
fill=True, fillcolor=aide.norm_bg,
fillalpha=1.0,
coord='window')
self.objects.append(self.bg)
# add warning and alert lines
self.ln_warn = aide.dc.Line(0, self.warn_y, 1, self.warn_y,
color='gold3', linewidth=self.linewidth,
alpha=0.0, coord='window')
self.objects.append(self.ln_warn)
self.ln_alert = aide.dc.Line(0, self.alert_y, 1, self.alert_y,
color='red', linewidth=self.linewidth,
alpha=0.0, coord='window')
self.objects.append(self.ln_alert)
def warning(self):
self.bg.fillcolor = self.warn_bg
def alert(self):
self.bg.fillcolor = self.alert_bg
def normal(self):
self.bg.fillcolor = self.norm_bg
def _check_warning(self):
max_y = None
for i, plot_src in enumerate(self.aide.plots.values()):
limits = plot_src.get_limits('data')
y = limits[1][1]
max_y = y if max_y is None else max(max_y, y)
if max_y is not None:
if self.alert_y is not None and max_y > self.alert_y:
self.alert()
elif self.warn_y is not None and max_y > self.warn_y:
self.warning()
else:
self.normal()
def update_elements(self, viewer):
"""This method is called if the plot is set with new points,
or is scaled or panned with existing points.
Update the XAxis labels to reflect the new values and/or pan/scale.
"""
y_lo, y_hi = self.aide.bbox.T[1].min(), self.aide.bbox.T[1].max()
# adjust warning/alert lines
if self.warn_y is not None:
x, y = self.get_canvas_xy(viewer, (0, self.warn_y))
if y_lo <= y <= y_hi:
self.ln_warn.alpha = 1.0
else:
# y out of range of plot area, so make it invisible
self.ln_warn.alpha = 0.0
self.ln_warn.y1 = self.ln_warn.y2 = y
if self.alert_y is not None:
x, y = self.get_canvas_xy(viewer, (0, self.alert_y))
if y_lo <= y <= y_hi:
self.ln_alert.alpha = 1.0
else:
# y out of range of plot area, so make it invisible
self.ln_alert.alpha = 0.0
self.ln_alert.y1 = self.ln_alert.y2 = y
self.check_warning()
def update_bbox(self, viewer, dims):
# this object does not adjust the plot bbox at all
pass
def update_resize(self, viewer, dims, xy_lim):
"""This method is called if the viewer's window is resized.
Update all the PlotBG elements to reflect the new dimensions.
"""
# adjust bg to window size, in case it changed
x_lo, y_lo, x_hi, y_hi = xy_lim
wd, ht = dims[:2]
self.bg.x1, self.bg.y1 = x_lo, y_lo
self.bg.x2, self.bg.y2 = x_hi, y_hi
# adjust warning/alert lines
if self.warn_y is not None:
x, y = self.get_canvas_xy(viewer, (0, self.warn_y))
self.ln_warn.x1, self.ln_warn.x2 = x_lo, x_hi
self.ln_warn.y1 = self.ln_warn.y2 = y
if self.alert_y is not None:
x, y = self.get_canvas_xy(viewer, (0, self.alert_y))
self.ln_alert.x1, self.ln_alert.x2 = x_lo, x_hi
self.ln_alert.y1 = self.ln_alert.y2 = y
def add_plot(self, viewer, plot_src):
pass
def delete_plot(self, viewer, plot_src):
pass
def get_canvas_xy(self, viewer, pt):
arr_pts = np.asarray(pt)
return viewer.tform['data_to_plot'].to_(arr_pts).T[:2]
class PlotTitle(CompoundObject):
"""
Plotable object that defines the plot title and keys.
"""
def __init__(self, title='', font='sans', fontsize=12.0):
super(PlotTitle, self).__init__()
self.font = font
self.fontsize = fontsize
self.title = title
self.txt_ht = 0
self.kind = 'plot_title'
self.format_label = self._format_label
self.pad_px = 5
def register_decor(self, aide):
self.aide = aide
self.title_bg = aide.dc.Rectangle(0, 0, 100, 100, color=aide.norm_bg,
fill=True, fillcolor=aide.axis_bg,
coord='window')
self.objects.append(self.title_bg)
self.lbls = dict()
self.lbls[0] = aide.dc.Text(0, 0, text=self.title, color='black',
font=self.font,
fontsize=self.fontsize,
coord='window')
self.objects.append(self.lbls[0])
def _format_label(self, lbl, plot_src):
"""Default formatter for PlotTitle labels.
"""
lbl.text = "{0:}".format(plot_src.name)
def update_elements(self, viewer):
"""This method is called if the plot is set with new points,
or is scaled or panned with existing points.
Update the PlotTitle labels to reflect the new values.
"""
for i, plot_src in enumerate(self.aide.plots.values()):
lbl = self.lbls[plot_src]
self.format_label(lbl, plot_src)
def update_bbox(self, viewer, dims):
"""This method is called if the viewer's window is resized.
Update all the PlotTitle elements to reflect the new dimensions.
"""
wd, ht = dims[:2]
if self.txt_ht == 0:
_, self.txt_ht = viewer.renderer.get_dimensions(self.lbls[0])
y_lo = self.txt_ht + self.pad_px
self.aide.update_plot_bbox(y_lo=y_lo)
def update_resize(self, viewer, dims, xy_lim):
"""This method is called if the viewer's window is resized.
Update all the PlotTitle elements to reflect the new dimensions.
"""
x_lo, y_lo, x_hi, y_hi = xy_lim
wd, ht = dims[:2]
nplots = len(list(self.aide.plots.keys())) + 1
# set title labels as needed
a = wd // (nplots + 1)
cx, cy = 4, self.txt_ht
lbl = self.lbls[0]
lbl.x, lbl.y = cx, cy
for i, plot_src in enumerate(self.aide.plots.values()):
cx += a
lbl = self.lbls[plot_src]
lbl.x, lbl.y = cx, cy
self.format_label(lbl, plot_src)
self.title_bg.x1, self.title_bg.x2 = 0, wd
self.title_bg.y1, self.title_bg.y2 = 0, y_lo
def add_plot(self, viewer, plot_src):
text = plot_src.name
color = plot_src.color
lbl = self.aide.dc.Text(0, 0, text=text, color=color,
font=self.font,
fontsize=self.fontsize,
coord='window')
self.lbls[plot_src] = lbl
self.objects.append(lbl)
lbl.crdmap = self.lbls[0].crdmap
self.format_label(lbl, plot_src)
# reorder and place labels
dims = viewer.get_window_size()
self.update_resize(viewer, dims, self.aide.llur)
def delete_plot(self, viewer, plot_src):
lbl = self.lbls[plot_src]
del self.lbls[plot_src]
self.objects.remove(lbl)
# reorder and place labels
dims = viewer.get_window_size()
self.update_resize(viewer, dims, self.aide.llur)
class CalcPlot(XYPlot):
def __init__(self, name=None, x_fn=None, y_fn=None, color='black',
linewidth=1, linestyle='solid', alpha=1.0, **kwdargs):
super(CalcPlot, self).__init__(name=name,
color=color, linewidth=linewidth,
linestyle=linestyle, alpha=alpha,
**kwdargs)
self.kind = 'calcplot'
if x_fn is None:
x_fn = lambda x: x # noqa
self.x_fn = x_fn
if y_fn is None:
y_fn = lambda y: y # noqa
self.y_fn = y_fn
def plot(self, y_fn, x_fn=None):
if x_fn is not None:
self.x_fn = x_fn
self.y_fn = y_fn
self.plot_xlim = (None, None)
def calc_points(self, viewer, start_x, stop_x):
# in case X axis is flipped
start_x, stop_x = min(start_x, stop_x), max(start_x, stop_x)
new_xlim = (start_x, stop_x)
if new_xlim == self.plot_xlim:
# X limits are the same, no need to recalculate points
return
self.plot_xlim = new_xlim
wd, ht = self.viewer.get_window_size()
x_pts = self.x_fn(np.linspace(start_x, stop_x, wd, dtype=np.float))
y_pts = self.y_fn(x_pts)
points = np.array((x_pts, y_pts)).T
self.path.points = points
def get_limits(self, lim_type):
try:
llur = self.path.get_llur()
limits = [llur[0:2], llur[2:4]]
return np.array(limits)
except Exception:
return np.array(((0.0, 0.0), (0.0, 0.0)))
# register our types
register_canvas_types(dict(xyplot=XYPlot, calcplot=CalcPlot))
| 29,172 | 9,367 |
import csv
import os
import sys
from collections import defaultdict
PERSONS_OUTPUT_FILENAME_TEMPLATE = "persons_data_%s.csv"
DISQUALIFICATIONS_FILENAME_TEMPLATE = "disqualifications_data_%s.csv"
EXEMPTIONS_FILENAME_TEMPLATE = 'exemptions_data_%s.csv'
SNAPSHOT_HEADER_IDENTIFIER = "DISQUALS"
TRAILER_RECORD_IDENTIFIER = "DISQUALS"
PERSON_RECORD_TYPE = '1'
DISQUALIFICATION_RECORD_TYPE = '2'
EXEMPTION_RECORD_TYPE = '3'
def process_header_row(row):
header_identifier = row[0:8]
print(header_identifier)
run_number = row[8:12]
production_date = row[12:20]
if header_identifier != SNAPSHOT_HEADER_IDENTIFIER:
print(
"Unsuported file type from header: '%s'. Expecting a snapshot header: '%s'"
% (header_identifier, SNAPSHOT_HEADER_IDENTIFIER))
sys.exit(1)
print("Processing snapshot file with run number %s from date %s" %
(run_number, production_date))
def process_person_row(row, output_writer):
record_type = row[0]
person_number = str(row[1:13])
person_dob = row[13:21]
person_postcode = row[21:29]
person_variable_ind = int(row[29:33])
person_details = row[33:33 + person_variable_ind]
person_details = person_details.split('<')
title = person_details[0]
forenames = person_details[1]
surname = person_details[2]
honours = person_details[3]
address_line_1 = person_details[4]
address_line_2 = person_details[5]
posttown = person_details[6]
county = person_details[7]
country = person_details[8]
nationality = person_details[9]
corporate_number = person_details[10]
country_registration = person_details[11]
output_writer.writerow([
record_type, person_number, person_dob, person_postcode,
person_details, title, forenames, surname, honours, address_line_1,
address_line_2, posttown, county, country, nationality,
corporate_number, country_registration
])
def process_disqualification_row(row, output_writer):
record_type = row[0]
person_number = str(row[1:13])
disqual_start_date = row[13:21]
disqual_end_date = row[21:29]
section_of_act = row[29:49]
disqual_type = row[49:79]
disqual_order_date = row[79:87]
case_number = row[87:117]
company_name = row[117:277]
court_name_variable_ind = int(row[277:281])
court_name = row[281:281 + court_name_variable_ind]
output_writer.writerow([
record_type, person_number, disqual_start_date, disqual_end_date,
section_of_act, disqual_type, disqual_order_date, case_number,
company_name, court_name
])
def process_exemption_row(row, output_writer):
record_type = row[0]
person_number = str(row[1:9])
exemption_start_date = row[13:21]
exemption_end_date = row[21:29]
exemption_purpose = int(row[29:39])
exemption_purpose_dict = defaultdict(
lambda: '', {
1: 'Promotion',
2: 'Formation',
3:
'Directorships or other participation in management of a company',
4:
'Designated member/member or other participation in management of an LLP',
5: 'Receivership in relation to a company or LLP'
})
exemption_purpose = exemption_purpose_dict[exemption_purpose]
exemption_company_name_ind = int(row[39:43])
exemption_company_name = row[43:43 + exemption_company_name_ind]
output_writer.writerow([
record_type, person_number, exemption_start_date, exemption_end_date,
exemption_purpose, exemption_company_name
])
def init_person_output_file(filename):
output_persons_file = open(filename, 'w')
persons_writer = csv.writer(output_persons_file, delimiter=",")
persons_writer.writerow([
"record_type", "person_number", "person_dob", "person_postcode",
"person_details", 'title', 'forenames', 'surname', 'honours',
'address_line_1', 'address_line_2', 'posttown', 'county', 'country',
'nationality', 'corporate_number', 'country_registration'
])
return output_persons_file, persons_writer
def init_disquals_output_file(filename):
output_disquals_file = open(filename, 'w')
disqauls_writer = csv.writer(output_disquals_file, delimiter=",")
disqauls_writer.writerow([
"record_type", "person_number", "disqual_start_date",
"disqual_end_date", "section_of_act", "disqual_type",
"disqual_order_date", "case_number", "company_name", "court_name"
])
return output_disquals_file, disqauls_writer
def init_exemptions_output_file(filename):
output_exemptions_file = open(filename, 'w')
exemptions_writer = csv.writer(output_exemptions_file, delimiter=",")
exemptions_writer.writerow([
"record_type", "person_number", "exemption_start_date",
"exemption_end_date", "exemption_purpose", "exemption_company_name"
])
return output_exemptions_file, exemptions_writer
def init_input_files(output_folder, base_input_name):
persons_output_filename = os.path.join(
output_folder, PERSONS_OUTPUT_FILENAME_TEMPLATE % (base_input_name))
disquals_output_filename = os.path.join(
output_folder, DISQUALIFICATIONS_FILENAME_TEMPLATE % (base_input_name))
exemptions_output_filename = os.path.join(
output_folder, EXEMPTIONS_FILENAME_TEMPLATE % (base_input_name))
print("Saving companies data to %s" % persons_output_filename)
print("Saving persons data to %s" % disquals_output_filename)
print("Saving persons data to %s" % exemptions_output_filename)
output_persons_file, output_persons_writer = init_person_output_file(
persons_output_filename)
output_disquals_file, output_disquals_writer = init_disquals_output_file(
disquals_output_filename)
output_exemptions_file, output_exemptions_writer = init_exemptions_output_file(
exemptions_output_filename)
return output_persons_file, output_persons_writer, output_disquals_file, output_disquals_writer, output_exemptions_file, output_exemptions_writer
def process_company_appointments_data(input_file, output_folder,
base_input_name):
persons_processed = 0
disquals_processed = 0
exemptions_processed = 0
output_persons_file, output_persons_writer, output_disquals_file, output_disquals_writer, output_exemptions_file, output_exemptions_writer = init_input_files(
output_folder, base_input_name)
for row_num, row in enumerate(input_file):
if row_num == 0:
process_header_row(row)
elif row[0:8] == TRAILER_RECORD_IDENTIFIER:
# End of file
record_count = int(row[45:53])
print(
"Reached end of file. Processed %s == %s records: %s persons, %s disquals, %s exemptions."
% (record_count, persons_processed + disquals_processed +
exemptions_processed, persons_processed, disquals_processed,
exemptions_processed))
output_persons_file.close()
output_disquals_file.close()
output_exemptions_file.close()
sys.exit(0)
elif row[0] == PERSON_RECORD_TYPE:
process_person_row(row, output_persons_writer)
persons_processed += 1
elif row[0] == DISQUALIFICATION_RECORD_TYPE:
process_disqualification_row(row, output_disquals_writer)
disquals_processed += 1
elif row[0] == EXEMPTION_RECORD_TYPE:
process_exemption_row(row, output_exemptions_writer)
exemptions_processed += 1
if __name__ == '__main__':
if len(sys.argv) < 3:
print(
'Usage: python process_disqualified_directors_data.py input_file output_folder\n',
'E.g. python process_disqualified_directors_data.py Prod195_1111_ni_sample.dat ./output/'
)
sys.exit(1)
input_filename = sys.argv[1]
output_folder = sys.argv[2]
input_file = open(input_filename, 'r')
base_input_name = os.path.basename(input_filename)
# Do not include the extension in the base input name
base_input_name = os.path.splitext(base_input_name)[0]
process_company_appointments_data(input_file, output_folder,
base_input_name) | 8,305 | 2,821 |
from os import makedirs, errno
from os.path import exists, join
import numpy as np
from matplotlib import pyplot as plt
import itertools
from sklearn import preprocessing
def makeDir(path):
'''
To create output path if doesn't exist
see: https://stackoverflow.com/questions/273192/how-can-i-create-a-directory-if-it-does-not-exist
:param path: path to be created
:return: none
'''
try:
if not exists(path):
makedirs(path)
print("\nCreated '{}' folder\n".format(path))
except OSError as e:
if e.errno != errno.EEXIST:
raise
def split_train_test(data, test_ratio):
shuffled_indices = np.random.permutation(len(data))
test_set_size = int(len(data) * test_ratio)
test_indices = shuffled_indices[:test_set_size]
train_indices = shuffled_indices[test_set_size:]
train_set = [data[i] for i in train_indices]
test_set = [data[i] for i in test_indices]
return np.asarray(train_set), np.asarray(test_set)
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Greens):
'''
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
:param cm: confusion matrix
:param classes: array of classes' names
:param normalize: boolean
:param title: plot title
:param cmap: colour of matrix background
:return: plot confusion matrix
'''
# plt_name = altsep.join((plot_path,"".join((title,".png"))))
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
print(cm)
print('\nSum of main diagonal')
print(np.trace(cm))
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j], fmt),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label', labelpad=0)
# plt.savefig(plt_name)
plt.show()
def normalize(data):
'''
Normalize input data [0, 1]
:param data: input data
:return: normalized data
'''
scaler = preprocessing.MinMaxScaler()
data_min_max = scaler.fit_transform(data)
return data_min_max
| 2,875 | 983 |
import os
import torch
import torch.utils.data
from PIL import Image
import sys
import numpy as np
if sys.version_info[0] == 2:
import xml.etree.cElementTree as ET
else:
import xml.etree.ElementTree as ET
from maskrcnn_benchmark.structures.bounding_box import BoxList
from maskrcnn_benchmark.structures.bounding_box import ObjectList
def read_calib(calib_file_path):
data = {}
with open(calib_file_path, 'r') as f:
for line in f.readlines():
line = line.rstrip()
if len(line)==0: continue
key, value = line.split(':', 1)
data[key] = np.array([float(x) for x in value.split()])
return data
class KittiDataset(torch.utils.data.Dataset):
CLASSES = (
"__background__ ",
"car",
)
def __init__(self, data_dir, split, use_difficult=False, transforms=None):
self.root = data_dir
self.image_set = split
self.keep_difficult = use_difficult
self.transforms = transforms
self._annopath = os.path.join(self.root, "label_3d", "%s.xml")
self._image_left_path = os.path.join(self.root, "image_2", "%s.png")
self._image_right_path = os.path.join(self.root, "image_3", "%s.png")
self._calib_path = os.path.join(self.root, "calib", "%s.txt")
self._imgsetpath = os.path.join(self.root, "splits", "%s.txt")
with open(self._imgsetpath % self.image_set) as f:
self.ids = f.readlines()
self.ids = [x.strip("\n") for x in self.ids]
self.id_to_img_map = {k: v for k, v in enumerate(self.ids)}
cls = KittiDataset.CLASSES
self.class_to_ind = dict(zip(cls, range(len(cls))))
self.categories = dict(zip(range(len(cls)), cls))
def __getitem__(self, index):
img_id = self.ids[index]
img_left = Image.open(self._image_left_path % img_id).convert("RGB")
img_right = Image.open(self._image_right_path % img_id).convert("RGB")
target = self.get_groundtruth(index)
target_object = self.get_groundtruth(index)
target_left = target_object.get_field("left_box")
target_right = target_object.get_field("right_box")
target_left = target_left.clip_to_image(remove_empty=True)
target_right = target_right.clip_to_image(remove_empty=True)
if self.transforms is not None:
img_left, target_left = self.transforms(img_left, target_left)
img_right, target_right = self.transforms(img_right, target_right)
target_object.add_field("left_box", target_left)
target_object.add_field("right_box", target_right)
calib = self.preprocess_calib(index)
return img_left, img_right, target, calib, index
def __len__(self):
return len(self.ids)
def get_groundtruth(self, index):
img_id = self.ids[index]
anno = ET.parse(self._annopath % img_id).getroot()
anno = self._preprocess_annotation(anno)
height, width = anno["im_info"]
left_target = BoxList(anno["left_boxes"], (width, height), mode="xyxy")
left_target.add_field("labels", anno["labels"])
left_target.add_field("difficult", anno["difficult"])
right_target = BoxList(anno["right_boxes"], (width, height), mode="xyxy")
right_target.add_field("labels", anno["labels"])
right_target.add_field("difficult", anno["difficult"])
object_target = ObjectList()
object_target.add_field("left_box", left_target)
object_target.add_field("right_box", right_target)
object_target.add_field("labels", anno["labels"])
object_target.add_field("left_centers", anno["left_centers"])
object_target.add_field("right_centers", anno["right_centers"])
object_target.add_field("positions_xy", anno["positions_xy"])
object_target.add_field("positions_z", anno["positions_z"])
object_target.add_field("dimensions", anno["dimensions"])
object_target.add_field("alpha", anno["alpha"])
object_target.add_field("beta", anno["beta"])
object_target.add_field("corners", anno["corners"])
assert object_target.is_equal()
return object_target
def preprocess_calib(self, index):
img_id = self.ids[index]
calib_path = self._calib_path % img_id
calib = read_calib(calib_path)
P2 = np.reshape(calib['P2'], [3,4])
P3 = np.reshape(calib['P3'], [3,4])
c_u = P2[0,2]
c_v = P2[1,2]
f_u = P2[0,0]
f_v = P2[1,1]
b_x_2 = P2[0,3]/(f_u) # relative
b_y_2 = P2[1,3]/(f_v)
b_x_3 = P3[0,3]/(f_u) # relative
b_y_3 = P3[1,3]/(f_v)
b = abs(b_x_3 - b_x_2)
return {
"cu": c_u, "cv": c_v,
"fu": f_u, "fv": f_v,
"b": b,
"bx2":b_x_2,
}
def _preprocess_annotation(self, target):
left_boxes = []
right_boxes = []
gt_classes = []
difficult_boxes = []
TO_REMOVE = 0
#3d parameters
left_centers = []
right_centers = []
dimensions = []
positions_xy = []
positions_z = []
rotations = []
alphas = []
pconers = []
#occluded = []
#truncted = []
for obj in target.iter("object"):
difficult = int(obj.find("difficult").text) == 1
if not self.keep_difficult and difficult:
continue
name = obj.find("name").text.lower().strip()
left_bb = obj.find("left_bndbox")
left_box = [
left_bb.find("xmin").text,
left_bb.find("ymin").text,
left_bb.find("xmax").text,
left_bb.find("ymax").text,
]
left_bndbox = tuple(
map(lambda x: x - TO_REMOVE, list(map(float, left_box)))
)
left_boxes.append(left_bndbox)
left_center = [
left_bb.find("center").find("x").text,
left_bb.find("center").find("y").text,
]
left_center = list(map(float, left_center))
left_centers.append(left_center)
right_bb = obj.find("right_bndbox")
right_box = [
right_bb.find("xmin").text,
right_bb.find("ymin").text,
right_bb.find("xmax").text,
right_bb.find("ymax").text,
]
right_bndbox = tuple(
map(lambda x: x - TO_REMOVE, list(map(float, right_box)))
)
right_boxes.append(right_bndbox)
right_center = [
right_bb.find("center").find("x").text,
right_bb.find("center").find("y").text,
]
right_center = list(map(float, right_center))
right_centers.append(right_center)
gt_classes.append(self.class_to_ind[name])
difficult_boxes.append(difficult)
position_xy = [
obj.find("position").find("x").text,
obj.find("position").find("y").text,
]
position_xy = list(map(float, position_xy))
positions_xy.append(position_xy)
position_z = [
obj.find("position").find("z").find("depth").text,
obj.find("position").find("z").find("disp").text,
]
position_z = list(map(float, position_z))
positions_z.append(position_z)
dimension = [
obj.find("dimensions").find("h").text,
obj.find("dimensions").find("w").text,
obj.find("dimensions").find("l").text,
]
dimension = list(map(float, dimension))
dimensions.append(dimension)
alp = float(obj.find("alpha").text)
alphas.append(alp)
rot = float(obj.find("rotation").text)
rotations.append(rot)
pc = []
corners = obj.find("corners")
for i in range(8):
pc_str = corners.find("pc%d"%i).text
pc_i = [float(pc_s) for pc_s in pc_str.split(',')]
pc.append(pc_i)
pconers.append(pc)
size = target.find("size")
im_info = tuple(map(int, (size.find("height").text, size.find("width").text)))
res = {
"left_boxes": torch.tensor(left_boxes, dtype=torch.float32).view(-1,4),
"right_boxes": torch.tensor(right_boxes, dtype=torch.float32).view(-1,4),
"labels": torch.tensor(gt_classes),
"difficult": torch.tensor(difficult_boxes),
"left_centers": torch.tensor(left_centers, dtype=torch.float32).view(-1,2),
"right_centers": torch.tensor(right_centers, dtype=torch.float32).view(-1,2),
"positions_xy": torch.tensor(positions_xy, dtype=torch.float32).view(-1,2),
"positions_z": torch.tensor(positions_z, dtype=torch.float32).view(-1,2),
"dimensions": torch.tensor(dimensions, dtype=torch.float32).view(-1,3),
"alpha": torch.tensor(alphas, dtype=torch.float32),
"beta": torch.tensor(rotations, dtype=torch.float32),
"corners": torch.tensor(pconers, dtype=torch.float32).view(-1,8,7),
"im_info": im_info,
}
return res
def get_img_info(self, index):
img_id = self.ids[index]
anno = ET.parse(self._annopath % img_id).getroot()
size = anno.find("size")
im_info = tuple(map(int, (size.find("height").text, size.find("width").text)))
return {"height": im_info[0], "width": im_info[1]}
def map_class_id_to_class_name(self, class_id):
return KittiDataset.CLASSES[class_id]
| 9,802 | 3,252 |
##############################################################################
#
# Copyright (c) 2003-2020 by The University of Queensland
# http://www.uq.edu.au
#
# Primary Business: Queensland, Australia
# Licensed under the Apache License, version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
#
# Development until 2012 by Earth Systems Science Computational Center (ESSCC)
# Development 2012-2013 by School of Earth Sciences
# Development from 2014 by Centre for Geoscience Computing (GeoComp)
# Development from 2019 by School of Earth and Environmental Sciences
#
##############################################################################
from __future__ import print_function, division
__copyright__="""Copyright (c) 2003-2020 by The University of Queensland
http://www.uq.edu.au
Primary Business: Queensland, Australia"""
__license__="""Licensed under the Apache License, version 2.0
http://www.apache.org/licenses/LICENSE-2.0"""
__url__="https://launchpad.net/escript-finley"
#from esys.escript import sqrt, EPSILON, cos, sin, Lsup, atan, length, matrixmult, wherePositive, matrix_mult, inner, Scalar, whereNonNegative, whereNonPositive, maximum, minimum, sign, whereNegative, whereZero
import esys.escriptcore.pdetools as pdt
#from .util import *
from . import util as es
import numpy
import math
__all__= ['FaultSystem']
class FaultSystem(object):
"""
The FaultSystem class defines a system of faults in the Earth's crust.
A fault system is defined by set of faults index by a tag. Each fault is defined by a starting point V0 and a list of
strikes ``strikes`` and length ``l``. The strikes and the length is used to define a polyline with points ``V[i]`` such that
- ``V[0]=V0``
- ``V[i]=V[i]+ls[i]*array(cos(strikes[i]),sin(strikes[i]),0)``
So ``strikes`` defines the angle between the direction of the fault segment and the x0 axis. ls[i]==0 is allowed.
In case of a 3D model a fault plane is defined through a dip and depth.
The class provides a mechanism to parametrise each fault with the domain [0,w0_max] x [0, w1_max] (to [0,w0_max] in the 2D case).
"""
NOTAG="__NOTAG__"
MIN_DEPTH_ANGLE=0.1
def __init__(self,dim=3):
"""
Sets up the fault system
:param dim: spatial dimension
:type dim: ``int`` of value 2 or 3
"""
if not (dim == 2 or dim == 3):
raise ValueError("only dimension2 2 and 3 are supported.")
self.__dim=dim
self.__top={}
self.__ls={}
self.__strikes={}
self.__strike_vectors={}
self.__medDepth={}
self.__total_length={}
if dim ==2:
self.__depths=None
self.__depth_vectors=None
self.__dips=None
self.__bottom=None
self.__normals=None
else:
self.__depths={}
self.__depth_vectors={}
self.__dips={}
self.__bottom={}
self.__normals={}
self.__offsets={}
self.__w1_max={}
self.__w0_max={}
self.__center=None
self.__orientation = None
def getStart(self,tag=None):
"""
returns the starting point of fault ``tag``
:rtype: ``numpy.array``.
"""
return self.getTopPolyline(tag)[0]
def getTags(self):
"""
returns a list of the tags used by the fault system
:rtype: ``list``
"""
return list(self.__top.keys())
def getDim(self):
"""
returns the spatial dimension
:rtype: ``int``
"""
return self.__dim
def getTopPolyline(self, tag=None):
"""
returns the polyline used to describe fault tagged by ``tag``
:param tag: the tag of the fault
:type tag: ``float`` or ``str``
:return: the list of vertices defining the top of the fault. The coordinates are ``numpy.array``.
"""
if tag is None: tag=self.NOTAG
return self.__top[tag]
def getStrikes(self, tag=None):
"""
:return: the strike of the segements in fault ``tag``
:rtype: ``list`` of ``float``
"""
if tag is None: tag=self.NOTAG
return self.__strikes[tag]
def getStrikeVectors(self, tag=None):
"""
:return: the strike vectors of fault ``tag``
:rtype: ``list`` of ``numpy.array``.
"""
if tag is None: tag=self.NOTAG
return self.__strike_vectors[tag]
def getLengths(self, tag=None):
"""
:return: the lengths of segments in fault ``tag``
:rtype: ``list`` of ``float``
"""
if tag is None: tag=self.NOTAG
return self.__ls[tag]
def getTotalLength(self, tag=None):
"""
:return: the total unrolled length of fault ``tag``
:rtype: ``float``
"""
if tag is None: tag=self.NOTAG
return self.__total_length[tag]
def getMediumDepth(self,tag=None):
"""
returns the medium depth of fault ``tag``
:rtype: ``float``
"""
if tag is None: tag=self.NOTAG
return self.__medDepth[tag]
def getDips(self, tag=None):
"""
returns the list of the dips of the segements in fault ``tag``
:param tag: the tag of the fault
:type tag: ``float`` or ``str``
:return: the list of segment dips. In the 2D case None is returned.
"""
if tag is None: tag=self.NOTAG
if self.getDim()==3:
return self.__dips[tag]
else:
return None
def getBottomPolyline(self, tag=None):
"""
returns the list of the vertices defining the bottom of the fault ``tag``
:param tag: the tag of the fault
:type tag: ``float`` or ``str``
:return: the list of vertices. In the 2D case None is returned.
"""
if tag is None: tag=self.NOTAG
if self.getDim()==3:
return self.__bottom[tag]
else:
return None
def getSegmentNormals(self, tag=None):
"""
returns the list of the normals of the segments in fault ``tag``
:param tag: the tag of the fault
:type tag: ``float`` or ``str``
:return: the list of vectors normal to the segments. In the 2D case None is returned.
"""
if tag is None: tag=self.NOTAG
if self.getDim()==3:
return self.__normals[tag]
else:
return None
def getDepthVectors(self, tag=None):
"""
returns the list of the depth vector at top vertices in fault ``tag``.
:param tag: the tag of the fault
:type tag: ``float`` or ``str``
:return: the list of segment depths. In the 2D case None is returned.
"""
if tag is None: tag=self.NOTAG
if self.getDim()==3:
return self.__depth_vectors[tag]
else:
return None
def getDepths(self, tag=None):
"""
returns the list of the depths of the segements in fault ``tag``.
:param tag: the tag of the fault
:type tag: ``float`` or ``str``
:return: the list of segment depths. In the 2D case None is returned.
"""
if tag is None: tag=self.NOTAG
if self.getDim()==3:
return self.__depths[tag]
else:
return None
def getW0Range(self,tag=None):
"""
returns the range of the parameterization in ``w0``
:rtype: two ``float``
"""
return self.getW0Offsets(tag)[0], self.getW0Offsets(tag)[-1]
def getW1Range(self,tag=None):
"""
returns the range of the parameterization in ``w1``
:rtype: two ``float``
"""
if tag is None: tag=self.NOTAG
return -self.__w1_max[tag],0
def getW0Offsets(self, tag=None):
"""
returns the offsets for the parametrization of fault ``tag``.
:return: the offsets in the parametrization
:rtype: ``list`` of ``float``
"""
if tag is None: tag=self.NOTAG
return self.__offsets[tag]
def getCenterOnSurface(self):
"""
returns the center point of the fault system at the surface
:rtype: ``numpy.array``
"""
if self.__center is None:
self.__center=numpy.zeros((3,),numpy.float)
counter=0
for t in self.getTags():
for s in self.getTopPolyline(t):
self.__center[:2]+=s[:2]
counter+=1
self.__center/=counter
return self.__center[:self.getDim()]
def getOrientationOnSurface(self):
"""
returns the orientation of the fault system in RAD on the surface around the fault system center
:rtype: ``float``
"""
if self.__orientation is None:
center=self.getCenterOnSurface()
covariant=numpy.zeros((2,2))
for t in self.getTags():
for s in self.getTopPolyline(t):
covariant[0,0]+=(center[0]-s[0])**2
covariant[0,1]+=(center[1]-s[1])*(center[0]-s[0])
covariant[1,1]+=(center[1]-s[1])**2
covariant[1,0]+=(center[1]-s[1])*(center[0]-s[0])
e, V=numpy.linalg.eigh(covariant)
if e[0]>e[1]:
d=V[:,0]
else:
d=V[:,1]
if abs(d[0])>0.:
self.__orientation=es.atan(d[1]/d[0])
else:
self.__orientation=math.pi/2
return self.__orientation
def transform(self, rot=0, shift=numpy.zeros((3,))):
"""
applies a shift and a consecutive rotation in the x0x1 plane.
:param rot: rotation angle in RAD
:type rot: ``float``
:param shift: shift vector to be applied before rotation
:type shift: ``numpy.array`` of size 2 or 3
"""
if self.getDim() == 2:
mat=numpy.array([[es.cos(rot), -es.sin(rot)], [es.sin(rot), es.cos(rot)] ])
else:
mat=numpy.array([[es.cos(rot), -es.sin(rot),0.], [es.sin(rot), es.cos(rot),0.], [0.,0.,1.] ])
for t in self.getTags():
strikes=[ s+ rot for s in self.getStrikes(t) ]
V0=self.getStart(t)
self.addFault(strikes = [ s+ rot for s in self.getStrikes(t) ], \
ls = self.getLengths(t), \
V0=numpy.dot(mat,self.getStart(t)+shift), \
tag =t, \
dips=self.getDips(t),\
depths=self.getDepths(t), \
w0_offsets=self.getW0Offsets(t), \
w1_max=-self.getW1Range(t)[0])
def addFault(self, strikes, ls, V0=[0.,0.,0.],tag=None, dips=None, depths= None, w0_offsets=None, w1_max=None):
"""
adds a new fault to the fault system. The fault is named by ``tag``.
The fault is defined by a starting point V0 and a list of ``strikes`` and length ``ls``. The strikes and the length
is used to define a polyline with points ``V[i]`` such that
- ``V[0]=V0``
- ``V[i]=V[i]+ls[i]*array(cos(strikes[i]),sin(strikes[i]),0)``
So ``strikes`` defines the angle between the direction of the fault segment and the x0 axis. In 3D ``ls[i]`` ==0 is allowed.
In case of a 3D model a fault plane is defined through a dip ``dips`` and depth ``depths``.
From the dip and the depth the polyline ``bottom`` of the bottom of the fault is computed.
Each segment in the fault is decribed by the for vertices ``v0=top[i]``, ``v1==top[i+1]``, ``v2=bottom[i]`` and ``v3=bottom[i+1]``
The segment is parametrized by ``w0`` and ``w1`` with ``w0_offsets[i]<=w0<=w0_offsets[i+1]`` and ``-w1_max<=w1<=0``. Moreover
- ``(w0,w1)=(w0_offsets[i] , 0)->v0``
- ``(w0,w1)=(w0_offsets[i+1], 0)->v1``
- ``(w0,w1)=(w0_offsets[i] , -w1_max)->v2``
- ``(w0,w1)=(w0_offsets[i+1], -w1_max)->v3``
If no ``w0_offsets`` is given,
- ``w0_offsets[0]=0``
- ``w0_offsets[i]=w0_offsets[i-1]+L[i]``
where ``L[i]`` is the length of the segments on the top in 2D and in the middle of the segment in 3D.
If no ``w1_max`` is given, the average fault depth is used.
:param strikes: list of strikes. This is the angle of the fault segment direction with x0 axis. Right hand rule applies.
:type strikes: ``list`` of ``float``
:param ls: list of fault lengths. In the case of a 3D fault a segment may have length 0.
:type ls: ``list`` of ``float``
:param V0: start point of the fault
:type V0: ``list`` or ``numpy.array`` with 2 or 3 components. ``V0[2]`` must be zero.
:param tag: the tag of the fault. If fault ``tag`` already exists it is overwritten.
:type tag: ``float`` or ``str``
:param dips: list of dip angles. Right hand rule around strike direction applies.
:type dips: ``list`` of ``float``
:param depths: list of segment depth. Value mut be positive in the 3D case.
:type depths: ``list`` of ``float``
:param w0_offsets: ``w0_offsets[i]`` defines the offset of the segment ``i`` in the fault to be used in the parametrization of the fault. If not present the cumulative length of the fault segments is used.
:type w0_offsets: ``list`` of ``float`` or ``None``
:param w1_max: the maximum value used for parametrization of the fault in the depth direction. If not present the mean depth of the fault segments is used.
:type w1_max: ``float``
:note: In the three dimensional case the lists ``dip`` and ``top`` must have the same length.
"""
if tag is None:
tag=self.NOTAG
else:
if self.NOTAG in self.getTags():
raise ValueError('Attempt to add a fault with no tag to a set of existing faults')
if not isinstance(strikes, list): strikes=[strikes, ]
n_segs=len(strikes)
if not isinstance(ls, list): ls=[ ls for i in range(n_segs) ]
if not n_segs==len(ls):
raise ValueError("number of strike direction and length must match.")
if len(V0)>2:
if abs(V0[2])>0: raise Value("start point needs to be surface (3rd component ==0)")
if self.getDim()==2 and not (dips is None and depths is None) :
raise ValueError('Spatial dimension two does not support dip and depth for faults.')
if not dips is None:
if not isinstance(dips, list): dips=[dips for i in range(n_segs) ]
if n_segs != len(dips):
raise ValueError('length of dips must be one less than the length of top.')
if not depths is None:
if not isinstance(depths, list): depths=[depths for i in range(n_segs+1) ]
if n_segs+1 != len(depths):
raise ValueError('length of depths must be one less than the length of top.')
if w0_offsets != None:
if len(w0_offsets) != n_segs+1:
raise ValueError('expected length of w0_offsets is %s'%(n_segs))
self.__center=None
self.__orientation = None
#
# in the 2D case we don't allow zero length:
#
if self.getDim() == 2:
for l in ls:
if l<=0: raise ValueError("length must be positive")
else:
for l in ls:
if l<0: raise ValueError("length must be non-negative")
for i in range(n_segs+1):
if depths[i]<0: raise ValueError("negative depth.")
#
# translate start point to numarray
#
V0= numpy.array(V0[:self.getDim()],numpy.double)
#
# set strike vectors:
#
strike_vectors=[]
top_polyline=[V0]
total_length=0
for i in range(n_segs):
v=numpy.zeros((self.getDim(),))
v[0]=es.cos(strikes[i])
v[1]=es.sin(strikes[i])
strike_vectors.append(v)
top_polyline.append(top_polyline[-1]+ls[i]*v)
total_length+=ls[i]
#
# normal and depth direction
#
if self.getDim()==3:
normals=[]
for i in range(n_segs):
normals.append(numpy.array([es.sin(dips[i])*strike_vectors[i][1],-es.sin(dips[i])*strike_vectors[i][0], es.cos(dips[i])]) )
d=numpy.cross(strike_vectors[0],normals[0])
if d[2]>0:
f=-1
else:
f=1
depth_vectors=[f*depths[0]*d/numpy.linalg.norm(d) ]
for i in range(1,n_segs):
d=-numpy.cross(normals[i-1],normals[i])
d_l=numpy.linalg.norm(d)
if d_l<=0:
d=numpy.cross(strike_vectors[i],normals[i])
d_l=numpy.linalg.norm(d)
else:
for L in [ strike_vectors[i], strike_vectors[i-1]]:
if numpy.linalg.norm(numpy.cross(L,d)) <= self.MIN_DEPTH_ANGLE * numpy.linalg.norm(L) * d_l:
raise ValueError("%s-th depth vector %s too flat."%(i, d))
if d[2]>0:
f=-1
else:
f=1
depth_vectors.append(f*d*depths[i]/d_l)
d=numpy.cross(strike_vectors[n_segs-1],normals[n_segs-1])
if d[2]>0:
f=-1
else:
f=1
depth_vectors.append(f*depths[n_segs]*d/numpy.linalg.norm(d))
bottom_polyline=[ top_polyline[i]+depth_vectors[i] for i in range(n_segs+1) ]
#
# calculate offsets if required:
#
if w0_offsets is None:
w0_offsets=[0.]
for i in range(n_segs):
if self.getDim()==3:
w0_offsets.append(w0_offsets[-1]+(float(numpy.linalg.norm(bottom_polyline[i+1]-bottom_polyline[i]))+ls[i])/2.)
else:
w0_offsets.append(w0_offsets[-1]+ls[i])
w0_max=max(w0_offsets)
if self.getDim()==3:
self.__normals[tag]=normals
self.__depth_vectors[tag]=depth_vectors
self.__depths[tag]=depths
self.__dips[tag]=dips
self.__bottom[tag]=bottom_polyline
self.__ls[tag]=ls
self.__strikes[tag]=strikes
self.__strike_vectors[tag]=strike_vectors
self.__top[tag]=top_polyline
self.__total_length[tag]=total_length
self.__offsets[tag]=w0_offsets
if self.getDim()==2:
self.__medDepth[tag]=0.
else:
self.__medDepth[tag]=sum([ numpy.linalg.norm(v) for v in depth_vectors])/len(depth_vectors)
if w1_max is None or self.getDim()==2: w1_max=self.__medDepth[tag]
self.__w0_max[tag]=w0_max
self.__w1_max[tag]=w1_max
def getMaxValue(self,f, tol=es.sqrt(es.EPSILON)):
"""
returns the tag of the fault of where ``f`` takes the maximum value and a `Locator` object which can be used to collect values from `Data` class objects at the location where the minimum is taken.
:param f: a distribution of values
:type f: `escript.Data`
:param tol: relative tolerance used to decide if point is on fault
:type tol: ``tol``
:return: the fault tag the maximum is taken, and a `Locator` object to collect the value at location of maximum value.
"""
ref=-es.Lsup(f)*2
f_max=ref
t_max=None
loc_max=None
x=f.getFunctionSpace().getX()
for t in self.getTags():
p,m=self.getParametrization(x,tag=t, tol=tol)
loc=((m*f)+(1.-m)*ref).internal_maxGlobalDataPoint()
f_t=f.getTupleForGlobalDataPoint(*loc)[0]
if f_t>f_max:
f_max=f_t
t_max=t
loc_max=loc
if loc_max is None:
return None, None
else:
return t_max, pdt.Locator(x.getFunctionSpace(),x.getTupleForGlobalDataPoint(*loc_max))
def getMinValue(self,f, tol=es.sqrt(es.EPSILON)):
"""
returns the tag of the fault of where ``f`` takes the minimum value and a `Locator` object which can be used to collect values from `Data` class objects at the location where the minimum is taken.
:param f: a distribution of values
:type f: `escript.Data`
:param tol: relative tolerance used to decide if point is on fault
:type tol: ``tol``
:return: the fault tag the minimum is taken, and a `Locator` object to collect the value at location of minimum value.
"""
ref=es.Lsup(f)*2
f_min=ref
t_min=None
loc_min=None
x=f.getFunctionSpace().getX()
for t in self.getTags():
p,m=self.getParametrization(x,tag=t, tol=tol)
loc=((m*f)+(1.-m)*ref).internal_minGlobalDataPoint()
f_t=f.getTupleForGlobalDataPoint(*loc)[0]
if f_t<f_min:
f_min=f_t
t_min=t
loc_min=loc
if loc_min is None:
return None, None
else:
return t_min, pdt.Locator(x.getFunctionSpace(),x.getTupleForGlobalDataPoint(*loc_min))
def getParametrization(self,x,tag=None, tol=es.sqrt(es.EPSILON), outsider=None):
"""
returns the parametrization of the fault ``tag`` in the fault system. In fact the values of the parametrization for at given coordinates ``x`` is returned. In addition to the value of the parametrization a mask is returned indicating if the given location is on the fault with given tolerance ``tol``.
Typical usage of the this method is
dom=Domain(..)
x=dom.getX()
fs=FaultSystem()
fs.addFault(tag=3,...)
p, m=fs.getParametrization(x, outsider=0,tag=3)
saveDataCSV('x.csv',p=p, x=x, mask=m)
to create a file with the coordinates of the points in ``x`` which are on the fault (as ``mask=m``) together with their location ``p`` in the fault coordinate system.
:param x: location(s)
:type x: `escript.Data` object or ``numpy.array``
:param tag: the tag of the fault
:param tol: relative tolerance to check if location is on fault.
:type tol: ``float``
:param outsider: value used for parametrization values outside the fault. If not present an appropriate value is choosen.
:type outsider: ``float``
:return: the coordinates ``x`` in the coordinate system of the fault and a mask indicating coordinates in the fault by 1 (0 elsewhere)
:rtype: `escript.Data` object or ``numpy.array``
"""
offsets=self.getW0Offsets(tag)
w1_range=self.getW1Range(tag)
w0_range=self.getW0Range(tag)[1]-self.getW0Range(tag)[0]
if outsider is None:
outsider=min(self.getW0Range(tag)[0],self.getW0Range(tag)[1])-abs(w0_range)/es.sqrt(es.EPSILON)
if isinstance(x,list): x=numpy.array(x, numpy.double)
updated=x[0]*0
if self.getDim()==2:
#
#
p=x[0]*0 + outsider
top=self.getTopPolyline(tag)
for i in range(1,len(top)):
d=top[i]-top[i-1]
h=x-top[i-1]
h_l=es.length(h)
d_l=es.length(d)
s=es.inner(h,d)/d_l**2
s=s*es.whereNonPositive(s-1.-tol)*es.whereNonNegative(s+tol)
m=es.whereNonPositive(es.length(h-s*d)-tol*es.maximum(h_l,d_l))*(1.-updated)
p=(1.-m)*p+m*(offsets[i-1]+(offsets[i]-offsets[i-1])*s)
updated=es.wherePositive(updated+m)
else:
p=x[:2]*0 + outsider
top=self.getTopPolyline(tag)
bottom=self.getBottomPolyline(tag)
n=self.getSegmentNormals(tag)
for i in range(len(top)-1):
h=x-top[i]
R=top[i+1]-top[i]
r=bottom[i+1]-bottom[i]
D0=bottom[i]-top[i]
D1=bottom[i+1]-top[i+1]
s_upper=es.matrix_mult(numpy.linalg.pinv(numpy.vstack((R,D1)).T),h)
s_lower=es.matrix_mult(numpy.linalg.pinv(numpy.vstack((r,D0)).T),h)
m_ul=es.wherePositive(s_upper[0]-s_upper[1])
s=s_upper*m_ul+s_lower*(1-m_ul)
s0=s[0]
s1=s[1]
m=es.whereNonNegative(s0+tol)*es.whereNonPositive(s0-1.-tol)*es.whereNonNegative(s1+tol)*es.whereNonPositive(s1-1.-tol)
s0=s0*m
s1=s1*m
atol=tol*es.maximum(es.length(h),es.length(top[i]-bottom[i+1]))
m=es.whereNonPositive(es.length(h-s0*R-s1*D1)*m_ul+(1-m_ul)*es.length(h-s0*r-s1*D0)-atol)
p[0]=(1.-m)*p[0]+m*(offsets[i]+(offsets[i+1]-offsets[i])*s0)
p[1]=(1.-m)*p[1]+m*(w1_range[1]+(w1_range[0]-w1_range[1])*s1)
updated=es.wherePositive(updated+m)
return p, updated
def getSideAndDistance(self,x,tag=None):
"""
returns the side and the distance at ``x`` from the fault ``tag``.
:param x: location(s)
:type x: `escript.Data` object or ``numpy.array``
:param tag: the tag of the fault
:return: the side of ``x`` (positive means to the right of the fault, negative to the left) and the distance to the fault. Note that a value zero for the side means that that the side is undefined.
"""
d=None
side=None
if self.getDim()==2:
mat=numpy.array([[0., 1.], [-1., 0.] ])
s=self.getTopPolyline(tag)
for i in range(1,len(s)):
q=(s[i]-s[i-1])
h=x-s[i-1]
q_l=es.length(q)
qt=es.matrixmult(mat,q) # orthogonal direction
t=es.inner(q,h)/q_l**2
t=es.maximum(es.minimum(t,1,),0.)
p=h-t*q
dist=es.length(p)
lside=es.sign(es.inner(p,qt))
if d is None:
d=dist
side=lside
else:
m=es.whereNegative(d-dist)
m2=es.wherePositive(es.whereZero(abs(lside))+m)
d=dist*(1-m)+d*m
side=lside*(1-m2)+side*m2
else:
ns=self.getSegmentNormals(tag)
top=self.getTopPolyline(tag)
bottom=self.getBottomPolyline(tag)
for i in range(len(top)-1):
h=x-top[i]
R=top[i+1]-top[i]
r=bottom[i+1]-bottom[i]
D0=bottom[i]-top[i]
D1=bottom[i+1]-top[i+1]
s_upper=es.matrix_mult(numpy.linalg.pinv(numpy.vstack((R,D1)).T),h)
s_lower=es.matrix_mult(numpy.linalg.pinv(numpy.vstack((r,D0)).T),h)
m_ul=es.wherePositive(s_upper[0]-s_upper[1])
s=s_upper*m_ul+s_lower*(1-m_ul)
s=es.maximum(es.minimum(s,1.),0)
p=h-(m_ul*R+(1-m_ul)*r)*s[0]-(m_ul*D1+(1-m_ul)*D0)*s[1]
dist=es.length(p)
lside=es.sign(es.inner(p,ns[i]))
if d is None:
d=dist
side=lside
else:
m=es.whereNegative(d-dist)
m2=es.wherePositive(es.whereZero(abs(lside))+m)
d=dist*(1-m)+d*m
side=lside*(1-m2)+side*m2
return side, d
| 25,744 | 9,034 |
"""
:copyright: (c)Copyright 2013, Intel Corporation All Rights Reserved.
The source code contained or described here in and all documents related
to the source code ("Material") are owned by Intel Corporation or its
suppliers or licensors. Title to the Material remains with Intel Corporation
or its suppliers and licensors. The Material contains trade secrets and
proprietary and confidential information of Intel or its suppliers and
licensors.
The Material is protected by worldwide copyright and trade secret laws and
treaty provisions. No part of the Material may be used, copied, reproduced,
modified, published, uploaded, posted, transmitted, distributed, or disclosed
in any way without Intel's prior express written permission.
No license under any patent, copyright, trade secret or other intellectual
property right is granted to or conferred upon you by disclosure or delivery
of the Materials, either expressly, by implication, inducement, estoppel or
otherwise. Any license under such intellectual property rights must be express
and approved by Intel in writing.
:organization: INTEL MCG PSI
:summary: Implements file parsing manager
:since: 05/03/2013
:author: vdechefd
"""
import os
import lxml.etree as et
from acs.ErrorHandling.AcsConfigException import AcsConfigException
from acs.Core.Report.ACSLogging import LOGGER_FWK
from acs.Core.PathManager import Paths
import acs.UtilitiesFWK.Utilities as Utils
class FileParsingManager:
""" FileParsingManager
This class implements the File Parsing Manager.
This manager takes XML files as inputs and parses them into dictionaries.
It will parse:
- use case catalog
- bench config
- equipment catalog
- campaign
"""
def __init__(self, bench_config_name, equipment_catalog, global_config):
self._file_extention = ".xml"
self._execution_config_path = Paths.EXECUTION_CONFIG
self._equipment_catalog_path = Paths.EQUIPMENT_CATALOG
self._bench_config_name = (bench_config_name if os.path.isfile(bench_config_name) else
os.path.join(self._execution_config_path, bench_config_name + self._file_extention))
self._equipment_catalog_name = equipment_catalog + self._file_extention
self._global_config = global_config
self._ucase_catalogs = None
self._logger = LOGGER_FWK
def parse_bench_config(self):
"""
This function parses the bench config XML file into a dictionary.
"""
def __parse_node(node):
"""
This private function parse a node from bench_config parsing.
:rtype: dict
:return: Data stocked into a dictionnary.
"""
dico = {}
name = node.get('name', "")
if name:
# store all keys (except 'name')/value in a dict
for key in [x for x in node.attrib if x != "name"]:
dico[key] = node.attrib[key]
node_list = node.xpath('./*')
if node_list:
for node_item in node_list:
name = node_item.get('name', "")
if name:
dico[name] = __parse_node(node_item)
return dico
def __parse_bench_config(document):
"""
Last version of function parsing bench_config adapted for Multiphone.
:type document: object
:param document: xml document parsed by etree
:rtype: dict
:return: Data stocked into a dictionary.
"""
# parse bench_config (dom method)
bench_config = {}
node_list = document.xpath('/BenchConfig/*/*')
for node in node_list:
name = node.get('name', "")
if name:
bench_config[name] = __parse_node(node)
return bench_config
# body of the parse_bench_config() function.
if not os.path.isfile(self._bench_config_name):
error_msg = "Bench config file : %s does not exist" % self._bench_config_name
raise AcsConfigException(AcsConfigException.FILE_NOT_FOUND, error_msg)
try:
document = et.parse(self._bench_config_name)
except et.XMLSyntaxError:
_, error_msg, _ = Utils.get_exception_info()
error_msg = "{}; {}".format(self._bench_config_name, error_msg)
raise AcsConfigException(AcsConfigException.XML_PARSING_ERROR, error_msg)
result = __parse_bench_config(document)
bench_config_parameters = Utils.BenchConfigParameters(dictionnary=result,
bench_config_file=self._bench_config_name)
return bench_config_parameters
def parse_equipment_catalog(self):
"""
This function parses the equipment catalog XML file into a dictionary.
"""
# Instantiate empty dictionaries
eqt_type_dic = {}
# Get the xml doc
equipment_catalog_path = os.path.join(self._equipment_catalog_path, self._equipment_catalog_name)
if not os.path.isfile(equipment_catalog_path):
error_msg = "Equipment catalog file : %s does not exist" % equipment_catalog_path
raise AcsConfigException(AcsConfigException.FILE_NOT_FOUND, error_msg)
try:
equipment_catalog_doc = et.parse(equipment_catalog_path)
except et.XMLSyntaxError:
_, error_msg, _ = Utils.get_exception_info()
error_msg = "{}; {}".format(equipment_catalog_path, error_msg)
raise AcsConfigException(AcsConfigException.XML_PARSING_ERROR, error_msg)
root_node = equipment_catalog_doc.xpath('/Equipment_Catalog')
if not root_node:
raise AcsConfigException(AcsConfigException.FILE_NOT_FOUND,
"Wrong XML: could not find expected document root node: "
"'Equipment_Catalog'")
# Parse EquipmentTypes
list_eq_types = root_node[0].xpath('./EquipmentType')
for eq_type in list_eq_types:
eqt_type_dic.update(self._load_equipment_type(eq_type))
self._global_config.equipmentCatalog = eqt_type_dic.copy()
def _load_equipment_type(self, node):
"""
This function parses an "EquipmentType" XML Tag into a dictionary
:type node: Etree node
:param node: the "EquipmentType" node
:rtype dic: dict
:return: a dictionary of equipment
"""
dic = {}
eqt_type_name = node.get("name", "")
if eqt_type_name:
dic[eqt_type_name] = self._load_equipments(node)
return dic
def _load_equipments(self, node):
"""
This function parses "Equipment" XML Tags into a dictionary
:type node: Etree node
:param node: the node containing "Equipment" nodes
"""
# Get common equipment type parameters
dic = {}
dic.update(self._get_parameters(node))
eqt_nodes = node.xpath('./Equipment')
for sub_node in eqt_nodes:
eqt_model = sub_node.get("name", "")
if eqt_model:
dic[eqt_model] = self._get_parameters(sub_node)
dic[eqt_model].update(self._load_transport(sub_node))
dic[eqt_model].update(self._load_features(sub_node))
dic[eqt_model].update(self._load_controllers(sub_node))
return dic
def _load_transport(self, node):
"""
This function parses a "Transport" XML Tags from a node into a dictionary
:type node: DOM node
:param node: the node from which to get all parameters value
:rtype dic: dict
:return: a dictionary of transports
"""
dic = {}
transport_node = node.xpath('./Transports')
if transport_node:
dic["Transports"] = self._get_parameters(transport_node[0])
return dic
def _load_controllers(self, node):
"""
This function parses a "Controllers" XML Tags from a node into a dictionary
:type node: DOM node
:param node: the node from which to get all parameters value
:rtype dic: dict
:return: the dictionary of controllers
"""
dic = {}
transport_node = node.xpath('./Controllers')
if transport_node:
dic["Controllers"] = self._get_parameters(transport_node[0])
return dic
def _load_features(self, node):
"""
This function parses a "Features" XML Tags from a node into a dictionary
:type node: Element node
:param node: the node from which to get all parameters value
:rtype dic: dict
:return: a dictionary of features
"""
dic = {}
transport_node = node.xpath('./Features')
if transport_node:
dic["Features"] = self._get_parameters(transport_node[0])
return dic
def _get_parameters(self, node):
"""
This function parses all "Parameter" XML Tags from a node into a dictionary
:type node: Element node
:param node: the node from which to get all parameters value
:rtype dic: dict
:return: a dictionary of parameters
"""
dic = {}
parameters = node.xpath('./Parameter')
for parameter in parameters:
name = parameter.get("name", "")
value = parameter.get("value", "")
if name:
dic[name] = value
return dic
| 9,680 | 2,666 |
'''
Austin Richards 4/14/21
excel_to_csv.py automates the conversion of many xlsx
files into csv files. This program names the csv file
in the format <filename>_<sheetname>.csv
'''
import logging
import os, csv, openpyxl
from pathlib import Path
from openpyxl.utils import get_column_letter
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s: %(message)s')
def get_all_paths(directory):
'''
returns all paths in a directory (and it's sub-directories)
in a list type
'''
file_paths = []
for path, dirs, files in os.walk(directory):
for filename in files:
filepath = os.path.join(path, filename)
file_paths.append(filepath)
return file_paths
def excel_to_csv(directory):
# get the absolute path, make a folder within it to save converted files, get files to convert
directory = os.path.abspath(directory)
new_dir = os.path.join(directory, 'converted_csv_files')
os.makedirs(new_dir, exist_ok=True)
all_paths = [path for path in get_all_paths(directory) if path.endswith('.xlsx')]
for excel_file in all_paths:
workbook = openpyxl.load_workbook(excel_file)
excel_filename = Path(excel_file).stem
print(f'copying {excel_filename}...')
for sheet_name in workbook.sheetnames:
print(f' copying {sheet_name}...')
# create a csv filename with the excel filename and sheetname, put in new folder
csv_filename = f'{excel_filename}_{sheet_name}.csv'
csv_filepath = os.path.join(new_dir, csv_filename)
new_file = open(csv_filepath, 'w', newline='')
csv_writer = csv.writer(new_file)
# get data from the xlsx file and write it to the new csv
sheet = workbook[sheet_name]
for row_num in range(1, sheet.max_row + 1):
row_data = []
for col_num in range(1, sheet.max_column + 1):
col_letter = get_column_letter(col_num)
row_data.append(sheet[col_letter + str(row_num)].value)
# write data to the new csv
csv_writer.writerow(row_data)
new_file.close()
print('files copied.')
excel_to_csv('Chapter 16') | 2,256 | 697 |
# Checks for an XXX error ### @replace "XXX", ('absolute/relative' if has_rel else 'absolute')
# with an error of at most 1e-XXX ### @replace "XXX", prec
# Don't edit this file. Edit real_abs_rel_template.py instead, and then run _real_check_gen.py
# Oh, actually, you're editing the correct file. Go on. ### @if False
raise Exception("You're not supposed to run this!!!") ### @if False
from itertools import zip_longest
from decimal import Decimal, InvalidOperation
from kg.checkers import * ### @keep @import
EPS = 0 ### @replace 0, f"Decimal('1e-{prec}')"
EPS *= 1+Decimal('1e-5') # add some leniency
@set_checker()
@default_score
def checker(input_file, output_file, judge_file, **kwargs):
worst = 0
for line1, line2 in zip_longest(output_file, judge_file):
if (line1 is None) != (line2 is None): raise WA("Unequal number of lines")
p1 = line1.rstrip().split(" ")
p2 = line2.rstrip().split(" ")
if len(p1) != len(p2): raise WA("Incorrect number of values in line")
for v1, v2 in zip(p1, p2):
if v1 != v2: # they're different as tokens. try considering them as numbers
try:
err = error(Decimal(v1), Decimal(v2)) ### @replace "error", "abs_rel_error" if has_rel else "abs_error"
except InvalidOperation:
raise WA(f"Unequal tokens that are not numbers: {v1!r} != {v2!r}")
worst = max(worst, err)
if err > EPS:
print('Found an error of', worst) ### @keep @if format not in ('hr', 'cms')
raise WA("Bad precision.")
print('Worst error:', worst) ### @keep @if format not in ('pg', 'hr', 'cms')
help_ = ('Compare if two sequences of real numbers are "close enough" (by XXX). ' ### @replace 'XXX', '1e-' + str(prec)
"Uses XXX error.") ### @replace 'XXX', 'absolute/relative' if has_rel else 'absolute'
if __name__ == '__main__': chk(help=help_)
| 2,041 | 637 |
import time
import os
import subprocess
import threading
class ProcessHandler:
def __init__(self, *args, on_output=None):
self.process = subprocess.Popen(args, stdin=subprocess.PIPE,
stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
self.on_output = on_output
self.start_stdout_listening()
def send_message(self, msg):
if not isinstance(msg, bytes):
msg = msg.encode('utf8')
if not msg.endswith(b'\n'):
msg += b'\n'
self.process.stdin.write(msg)
try:
self.process.stdin.flush()
except OSError:
print(f'Process {self} already closed')
def dispatch_process_output(self):
for line in self.process.stdout:
line = line.decode('utf8')
self.on_output(line)
def start_stdout_listening(self):
t = threading.Thread(target=self.dispatch_process_output, daemon=True)
t.start()
def run(s):
proc = ProcessHandler(s)
return proc
def run_sync(s):
return subprocess.run(s, shell=True).stdout | 1,099 | 340 |
import os
from setuptools import setup
readme = open('README.md').read()
requirements = ['click', 'feedparser', 'beautifulsoup4']
setup(
name = "whatsnew",
version = "0.13",
author = "Patrick Tyler Haas",
author_email = "patrick.tyler.haas@gmail.com",
description = ("A lightweight, convenient tool to get an overview of the day's headlines right from your command line."),
license = "MIT",
keywords = "",
url = "https://github.com/haaspt/whatsnew",
scripts=['main.py', 'newsfeeds.py', 'config.py'],
install_requires=requirements,
long_description=readme,
entry_points = {
'console_scripts': [
'whatsnew = main:main'
],
},
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Programming Language :: Python :: 3.6',
],
)
| 977 | 311 |
import argparse
import logging
import sys
from timeswitch.switch.manager import SwitchManager
from timeswitch.app import setup_app
from timeswitch.api import setup_api
from timeswitch.model import setup_model
# ######################################
# # parsing commandline args
# ######################################
def parse_arguments():
PARSER = argparse.ArgumentParser(description='Timeswitch for the\
GPIOs of an Raspberry Pi with a webinterface.')
PARSER.add_argument('-f', '--file', dest='schedule_file', metavar='file',
type=str, required=True,
help='A JSON-file containing the schedule.')
PARSER.add_argument('--debug', action='store_true',
help='A JSON-file containing the schedule.')
PARSER.add_argument('--create', dest='create', action='store_true',
help='Creates a new database. DELETES ALL DATA!!')
PARSER.add_argument('--manager', dest='manager', action='store_true',
help='Start the manager which switches the GPIOs at specified times.')
PARSER.add_argument('--static', dest='static_dir', metavar='file',
type=str, help='Folder with static files to serve')
return PARSER.parse_args()
# ######################################
# # Logging:
# ######################################
def setup_logger(debug=True):
# set up logging to file - see previous section for more details
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(name)-20s \
%(levelname)-8s %(message)s',
datefmt='%m-%d %H:%M',
filename='piSwitch.log',
filemode='a')
# define a Handler which writes INFO messages or higher to the sys.stderr
console = logging.StreamHandler()
if debug:
console.setLevel(logging.DEBUG)
else:
console.setLevel(logging.INFO)
# set a format which is simpler for console use
formatter = logging.Formatter('%(levelname)-8s:%(name)-8s:%(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)
def start(cmd_args, app, switch_model):
switch_manager = None
if cmd_args.manager:
switch_manager = SwitchManager(switch_model)
switch_manager.start()
try:
app.run(debug=cmd_args.debug)
finally:
if cmd_args.manager:
switch_manager.stop()
def main():
cmd_args = parse_arguments()
setup_logger(cmd_args.debug)
app = setup_app(static_folder=cmd_args.static_dir, static_url_path='')
model = setup_model(app)
_ = setup_api(app, model)
start(cmd_args, app, model)
if __name__ == '__main__':
main()
| 2,880 | 829 |
import sys, os, time
from pathlib import Path
import pickle
import datetime as dt
import glob
import h5py
import numpy as np
from matplotlib import pyplot as plt
from multiprocessing import Pool
from functools import partial
import torch
from torchvision import datasets, transforms
def subsample(x, n=0, m=200):
return x[..., n:m, n:m]
def _get_tstamp_string(tstamp_ix):
"""Calculates the timestamp in hh:mm based on the file index
Args:
tstamp_ix (int): Index of the single frame
Returns:
Str: hh:mm
"""
total_minutes = tstamp_ix*5
hours = total_minutes // 60
minutes = total_minutes % 60
return hours, minutes
class trafic4cast_dataset(torch.utils.data.Dataset):
"""Dataloader for trafic4cast data
Attributes:
compression (TYPE): Description
do_precomp_path (TYPE): Description
num_frames (TYPE): Description
reduce (TYPE): Description
source_root (TYPE): Description
split_type (TYPE): Description
target_file_paths (TYPE): Description
target_root (TYPE): Description
transform (TYPE): Description
valid_test_clips (TYPE): Description
"""
def __init__(self, source_root, target_root="precomuted_data",
split_type='train',
cities=['Berlin', 'Istanbul', 'Moscow'],
transform=None, reduce=False, compression=None,
num_frames=15, do_subsample=None, filter_test_times=False,
return_features=False, return_city=False):
"""Dataloader for the trafic4cast competition
Usage Dataloader:
The dataloader is situated in "videoloader.py", to use it, you have
to download the competition data and set two paths. "source_root"
and "target_root".
source_root: Is the directory with the raw competition data.
The expected file structure is shown below.
target_root: This directory will be used to store the
preprocessed data (about 200 GB)
Expected folder structure for raw data:
-source_root
- Berlin
-Berlin_test
-Berlin_training
-Berlin_validation
-Istanbul
-Instanbul_test
-…
-Moscow
-…
Args:
source_root (str): Is the directory with the raw competition data.
target_root (str, optional): This directory will be used to store the
preprocessed data
split_type (str, optional): Can be ['training', 'validation', 'test']
cities (list, optional): This can be used to limit the data loader to a
subset of cities. Has to be a list! Default is ['Berlin', 'Moscow', 'Istanbul']
transform (None, optional): Transform applied to x before returning it.
reduce (bool, optional): This option collapses the time dimension into the
(color) channel dimension.
compression (str, optional): The h5py compression method to store the
preprocessed data. 'compression=None' is the fastest.
num_frames (int, optional):
do_subsample (tuple, optional): Tuple of two integers. Returns only a part of the image. Slices the
image in the 'pixel' dimensions with x = x[n:m, n:m]. with m>n
filter_test_times (bool, optional): Filters output data, such that only valid (city-dependend) test-times are returned.
"""
self.reduce = reduce
self.source_root = source_root
self.target_root = target_root
self.transform = transform
self.split_type = split_type
self.compression = compression
self.cities = cities
self.num_frames = num_frames
self.subsample = False
self.filter_test_times = filter_test_times
self.return_features = return_features
self.return_city = return_city
if self.filter_test_times:
tt_dict2 = {}
tt_dict = pickle.load(open(os.path.join('.', 'utils', 'test_timestamps.dict'), "rb"))
for city, values in tt_dict.items():
values.sort()
tt_dict2[city] = values
self.valid_test_times = tt_dict2
if do_subsample is not None:
self.subsample = True
self.n = do_subsample[0]
self.m = do_subsample[1]
source_file_paths = []
for city in cities:
source_file_paths = source_file_paths + glob.glob(
os.path.join(self.source_root, city, '*_' + self.split_type,
'*.h5'))
do_precomp_path = []
missing_target_files = []
for raw_file_path in source_file_paths:
target_file = raw_file_path.replace(
self.source_root, self.target_root)
if not os.path.exists(target_file):
do_precomp_path.append(raw_file_path)
missing_target_files.append(target_file)
self.do_precomp_path = do_precomp_path
target_dirs = list(set([str(Path(x).parent)
for x in missing_target_files]))
for target_dir in target_dirs:
if not os.path.exists(target_dir):
os.makedirs(target_dir)
with Pool() as pool:
pool.map(self.precompute_clip, self.do_precomp_path)
pool.close()
pool.join()
target_file_paths = []
for city in cities:
target_file_paths = target_file_paths + glob.glob(
os.path.join(self.target_root, city, '*_' + self.split_type,
'*.h5'))
self.target_file_paths = target_file_paths
if self.split_type == 'test':
precomp_readt_test = partial(self.precompute_clip, mode='reading_test')
with Pool() as pool:
valid_test_clips = pool.map(precomp_readt_test,
self.target_file_paths)
pool.close()
pool.join()
valid_test_clips = [valid_tuple for sublist in valid_test_clips
for valid_tuple in sublist]
valid_test_clips.sort()
self.valid_test_clips = valid_test_clips
def precompute_clip(self, source_path, mode='writing'):
"""Summary
Args:
source_path (TYPE): Description
mode (str, optional): Description
Returns:
TYPE: Description
"""
target_path = source_path.replace(self.source_root, self.target_root)
f_source = h5py.File(source_path, 'r')
data1 = f_source['array']
data1 = data1[:]
if mode == 'writing':
data1 = np.moveaxis(data1, 3, 1)
f_target = h5py.File(target_path, 'w')
dset = f_target.create_dataset('array', (288, 3, 495, 436),
chunks=(1, 3, 495, 436),
dtype='uint8', data=data1,
compression=self.compression)
f_target.close()
if mode == 'reading_test':
valid_test_clips = list = []
for tstamp_ix in range(288-15):
clip = data1[tstamp_ix:tstamp_ix+self.num_frames, :, :, :]
sum_first_train_frame = np.sum(clip[0, :, :, :])
sum_last_train_frame = np.sum(clip[11, :, :, :])
if (sum_first_train_frame != 0) and (sum_last_train_frame != 0):
valid_test_clips.append((source_path, tstamp_ix))
f_source.close()
if mode == 'reading_test':
return valid_test_clips
def __len__(self):
if self.split_type == 'test':
pass
return len(self.valid_test_clips)
elif self.filter_test_times:
return len(self.target_file_paths) * 5
else:
return len(self.target_file_paths) * 272
def __getitem__(self, idx):
"""Summary
Args:
idx (TYPE): Description
Returns:
TYPE: Description
"""
return_dict = {}
if torch.is_tensor(idx):
idx = idx.tolist()
if self.split_type == 'test':
target_file_path, tstamp_ix = self.valid_test_clips[idx]
elif self.filter_test_times:
file_ix = idx // 5
valid_tstamp_ix = idx % 5
target_file_path = self.target_file_paths[file_ix]
city_name_path = Path(target_file_path.replace(self.target_root,''))
city_name = city_name_path.parts[1]
tstamp_ix = self.valid_test_times[city_name][valid_tstamp_ix]
else:
file_ix = idx // 272
tstamp_ix = idx % 272
target_file_path = self.target_file_paths[file_ix]
if self.return_features:
# create feature vector
date_string = Path(target_file_path).name.split('_')[0]
date_datetime = dt.datetime.strptime(date_string, '%Y%m%d')
hour, minute = _get_tstamp_string(tstamp_ix)
# feature_vector = []
sin_hours = np.sin(2*np.pi/24 * hour)
cos_hours = np.cos(2*np.pi/24 * hour)
sin_mins = np.sin(2*np.pi/60 * minute)
cos_mins = np.cos(2*np.pi/60 * minute)
sin_month = np.sin(2*np.pi/12 * date_datetime.month)
cos_month = np.cos(2*np.pi/12 * date_datetime.month)
weekday_ix = date_datetime.weekday() / 6
week_number = date_datetime.isocalendar()[1] / 52
feature_vector = np.asarray([sin_hours, cos_hours, sin_mins,
cos_mins, sin_month, cos_month,
weekday_ix, week_number]).ravel()
feature_vector = torch.from_numpy(feature_vector)
feature_vector = feature_vector.to(dtype=torch.float)
return_dict['feature_vector'] = feature_vector
if self.return_city:
city_name_path = Path(target_file_path.replace(self.target_root,''))
city_name = city_name_path.parts[1]
return_dict['city_names'] = city_name
# we want to predict the image at idx+1 based on the image with idx
f = h5py.File(target_file_path, 'r')
sample = f.get('array')
x = sample[tstamp_ix:tstamp_ix+12, :, :, :]
y = sample[tstamp_ix+12:tstamp_ix+15, :, :, :]
if self.reduce:
# stack all time dimensions into the channels.
# all channels of the same timestamp are left togehter
x = np.moveaxis(x, (0, 1), (2, 3))
x = np.reshape(x, (495, 436, 36))
x = torch.from_numpy(x)
x = x.permute(2, 0, 1) # Dimensions: time/channels, h, w
y = np.moveaxis(y, (0, 1), (2, 3))
y = np.reshape(y, (495, 436, 9))
y = torch.from_numpy(y)
y = y.permute(2, 0, 1)
y = y.to(dtype=torch.float) # is ByteTensor?
x = x.to(dtype=torch.float) # is ByteTensor?
else:
x = torch.from_numpy(x)
y = torch.from_numpy(y)
y = y.to(dtype=torch.float) # is ByteTensor?
x = x.to(dtype=torch.float) # is ByteTensor?
f.close()
if self.subsample:
x = subsample(x,self.n,self.m)
y = subsample(y,self.n,self.m)
if self.transform is not None:
x = self.transform(x)
return x, y, return_dict | 12,055 | 3,642 |
from django.views.generic import DeleteView, DetailView, UpdateView, CreateView
from django.forms.models import BaseInlineFormSet
from django.forms.models import inlineformset_factory
from braces.views import LoginRequiredMixin, UserFormKwargsMixin, SelectRelatedMixin
from ..models import Letter, Attachment
from ..forms import LetterForm
from ..filters import LetterFilter
from .mixins import (InitialFormMixin, CreateFormMessagesMixin,
UpdateFormMessagesMixin, DeletedMessageMixin, CreateFormsetView, UpdateFormsetView)
from ..forms import AttachmentForm
from django_filters.views import FilterView
from crispy_forms.helper import FormHelper
from django.core.urlresolvers import reverse
class FormsetHelper(FormHelper):
form_tag = False
form_method = 'post'
class TableInlineHelper(FormsetHelper):
template = 'bootstrap/table_inline_formset.html'
def formset_attachment_factory(form_formset=None, *args, **kwargs):
if form_formset is None:
class BaseAttachmentFormSet(BaseInlineFormSet):
helper = TableInlineHelper()
form_formset = BaseAttachmentFormSet
return inlineformset_factory(Letter, Attachment, form=AttachmentForm, formset=form_formset,
*args, **kwargs)
AttachmentFormSet = formset_attachment_factory()
class LetterDetailView(SelectRelatedMixin, DetailView):
model = Letter
select_related = ["created_by", "modified_by", "contact"]
class LetterListView(SelectRelatedMixin, FilterView):
model = Letter
filterset_class = LetterFilter
select_related = ["created_by", "modified_by", "contact", ]
class LetterCreateView(LoginRequiredMixin, CreateFormMessagesMixin, UserFormKwargsMixin,
InitialFormMixin, CreateFormsetView, CreateView):
model = Letter
form_class = LetterForm
formset_class = {'attachment_form': AttachmentFormSet}
class LetterDeleteView(DeletedMessageMixin, DeleteView):
model = Letter
def get_success_message(self):
return self.object
def get_success_url(self):
return reverse('correspondence:contact_list')
class LetterUpdateView(LoginRequiredMixin, UpdateFormMessagesMixin, UserFormKwargsMixin,
UpdateFormsetView, UpdateView):
model = Letter
form_class = LetterForm
formset_class = {'attachment_form': AttachmentFormSet}
| 2,369 | 693 |
import numpy as np
from pychunkedgraph.backend import chunkedgraph, chunkedgraph_utils
import cloudvolume
def initialize_chunkedgraph(cg_table_id, ws_cv_path, chunk_size, cg_mesh_dir,
fan_out=2, instance_id=None, project_id=None):
""" Initalizes a chunkedgraph on BigTable
:param cg_table_id: str
name of chunkedgraph
:param ws_cv_path: str
path to watershed segmentation on Google Cloud
:param chunk_size: np.ndarray
array of three ints
:param cg_mesh_dir: str
mesh folder name
:param fan_out: int
fan out of chunked graph (2 == Octree)
:param instance_id: str
Google instance id
:param project_id: str
Google project id
:return: ChunkedGraph
"""
ws_cv = cloudvolume.CloudVolume(ws_cv_path)
bbox = np.array(ws_cv.bounds.to_list()).reshape(2, 3)
# assert np.all(bbox[0] == 0)
# assert np.all((bbox[1] % chunk_size) == 0)
n_chunks = ((bbox[1] - bbox[0]) / chunk_size).astype(np.int)
n_layers = int(np.ceil(chunkedgraph_utils.log_n(np.max(n_chunks), fan_out))) + 2
dataset_info = ws_cv.info
dataset_info["mesh"] = cg_mesh_dir
dataset_info["data_dir"] = ws_cv_path
dataset_info["graph"] = {"chunk_size": [int(s) for s in chunk_size]}
kwargs = {"table_id": cg_table_id,
"chunk_size": chunk_size,
"fan_out": np.uint64(fan_out),
"n_layers": np.uint64(n_layers),
"dataset_info": dataset_info,
"is_new": True}
if instance_id is not None:
kwargs["instance_id"] = instance_id
if project_id is not None:
kwargs["project_id"] = project_id
cg = chunkedgraph.ChunkedGraph(**kwargs)
return cg
| 1,760 | 622 |
#!/usr/bin/env python3
from guizero import App, Text, Slider, Combo, PushButton, Box, Picture
pause = True
def readsensors():
return {"hlt" : 160, "rims" : 152, "bk" : 75}
def handlepause():
global pause
global pauseState
print("Pause Button pressed")
if pause:
print("running")
pause = not pause
pauseState.value=("Running")
hltFlame.visible=True
rimsFlame.visible=True
bkFlame.visible=True
else:
print("pausing")
pause = not pause
pauseState.value=("Paused")
hltFlame.visible=False
rimsFlame.visible=False
bkFlame.visible=False
return
app = App(title="Brew GUI", width=1280, height=768, layout="grid")
vertPad = Picture(app, image="blank_vert.gif", grid=[0,0])
hltBox = Box(app, layout="grid", grid=[1,0])
hltPad = Picture(hltBox, image="blank.gif", grid=[0,0])
hltTitle = Text(hltBox, text="HLT", grid=[0,1], align="top")
hltText = Text(hltBox, text="180", grid=[0,2], align="top")
hltSlider = Slider(hltBox, start=212, end=100, horizontal=False, grid=[0,3], align="top")
hltSlider.tk.config(length=500, width=50)
hltFlamePad = Picture(hltBox, image="blank_flame.gif", grid=[0,4])
hltFlame = Picture(hltBox, image="flame.gif", grid=[0,4])
rimsBox = Box(app, layout="grid", grid=[2,0])
rimsPad = Picture(rimsBox, image="blank.gif", grid=[0,0])
rimsTitle = Text(rimsBox, text="RIMS", grid=[0,1], align="top")
rimsText = Text(rimsBox, text="180", grid=[0,2], align="top")
rimsSlider = Slider(rimsBox, start=212, end=100, horizontal=False, grid=[0,3], align="top")
rimsSlider.tk.config(length=500, width=50)
rimsFlamePad = Picture(rimsBox, image="blank_flame.gif", grid=[0,4])
rimsFlame = Picture(rimsBox, image="flame.gif", grid=[0,4])
bkBox = Box(app, layout="grid", grid=[3,0])
bkPad = Picture(bkBox, image="blank.gif", grid=[0,0])
bkTitle = Text(bkBox, text="BK", grid=[0,1], align="top")
bkText = Text(bkBox, text="75", grid=[0,2], align="top")
bkSlider = Slider(bkBox, start=100, end=0, horizontal=False, grid=[0,3], align="top")
bkSlider.tk.config(length=500, width=50)
bkFlamePad = Picture(bkBox, image="blank_flame.gif", grid=[0,4])
bkFlame = Picture(bkBox, image="flame.gif", grid=[0,4])
modeBox = Box(app, layout="grid", grid=[4,0])
modePad = Picture(modeBox, image="blank.gif", grid=[0,0])
modeTitle = Text(modeBox, text="Mode", grid=[0,0], align="top")
mode = Combo(modeBox, options=["HLT", "RIMS", "BK"], grid=[1,0])
pauseState = Text(modeBox, text="Paused", grid=[0,1])
pauseButton = PushButton(modeBox, icon="pause-play.gif", command=handlepause, grid=[1,1])
hltFlame.visible=False
rimsFlame.visible=False
bkFlame.visible=False
app.display()
| 2,691 | 1,077 |
from click.testing import CliRunner
from resolos.interface import (
res_remote_add,
res_remote_remove,
res_init,
res_sync,
res
)
from resolos.remote import read_remote_db, list_remote_ids, delete_remote
from tests.common import verify_result
import logging
from pathlib import Path
import os
logger = logging.getLogger(__name__)
USER = os.environ["TEST_USER"]
PWD = os.environ["SSHPASS"]
HOST = os.environ["TEST_HOST"]
class TestIntegration:
remote_id = "test_remote"
def test_job(self, *args):
runner = CliRunner()
with runner.isolated_filesystem() as fs:
# Initialize a new local project
logger.info(f"Initializing new project in {fs}")
verify_result(runner.invoke(res, ["-v", "DEBUG", "info"]))
verify_result(runner.invoke(res_init, ["-y"]))
# Add remote
logger.info(f"### Adding remote in {fs}")
verify_result(
runner.invoke(
res_remote_add,
[self.remote_id, "-y", "-h", HOST, "-p", "3144", "-u", USER, "--remote-path", "/data/integration_test", "--conda-install-path", "/data", "--conda-load-command", "source /data/miniconda/bin/activate"]
)
)
remotes_list = read_remote_db()
assert self.remote_id in remotes_list
remotes_settings = remotes_list[self.remote_id]
assert remotes_settings["hostname"] == HOST
assert remotes_settings["username"] == USER
# Run job
with (Path(fs) / "test_script.py").open("w") as py:
py.write("""with open('test_output.txt', 'w') as txtf:
txtf.write('Hello, world!')""")
logger.info(f"### Syncing with remote {self.remote_id}")
verify_result(runner.invoke(res_sync, ["-r", self.remote_id]))
logger.info(f"### Running test job on {self.remote_id}")
verify_result(runner.invoke(res, ["-v", "DEBUG", "job", "-r", self.remote_id, "run", "-p", "normal", "python test_script.py"]))
# Sync back job results
logger.info(f"### Syncing results from remote {self.remote_id}")
verify_result(runner.invoke(res_sync, ["-r", self.remote_id]))
assert (Path(fs) / "test_output.txt").exists()
# Remove remote
logger.info(f"### Removing remote {self.remote_id}")
verify_result(runner.invoke(res_remote_remove, [self.remote_id])) | 2,498 | 761 |
# -*- coding: utf-8 -*-
from builtins import *
from model.group import Group
import pytest
import allure
#@pytest.mark.parametrize("group", testdata, ids=[repr(x) for x in testdata])
@allure.step('test_add_group')
def test_add_group(app, db, json_groups, check_ui):
group=json_groups
#with pytest.allure.step('Given a group list'):
old_group=db.get_group_list()
#with pytest.allure.step('When I add a group % to the list' % group):
app.group.create(group)
#with pytest.allure.step('Then the group list is equal to the old list with the added group'):
new_group=db.get_group_list()
old_group.append(group)
assert sorted(old_group, key=Group.id_or_max)==sorted(new_group, key=Group.id_or_max)
if check_ui:
assert sorted(map(app.group.clean_gap_from_group, new_group), key=Group.id_or_max) == sorted(app.group.get_group_list(), key=Group.id_or_max)
| 946 | 332 |
import urllib3
import lxml.etree as etree
import lxml.objectify as objectify
# Declare IP Address
ip_address = "192.168.0.123"
# Generate XML and XSD Validation
genius_schema = etree.XMLSchema(file='Genius.xsd')
xml_parser = objectify.makeparser(schema=genius_schema)
# Send Status Request
genius_comm = urllib3.PoolManager()
genius_request_url = "http://%s:8080/v2/pos?Action=Cancel&Format=XML" % ip_address
genius_response = genius_comm.request("GET", genius_request_url).data
# Validate the response with the Genius XSD
genius_response_data = objectify.fromstring(genius_response, xml_parser)
print("Cancel Result: %s" % genius_response_data.Status)
print("Response Message: %s" % genius_response_data.ResponseMessage)
input("Press Enter to close") | 753 | 255 |
#!/usr/bin/env python
__description__ =\
"""
editNames.py
Goes through a file looking for a set of strings, replacing each one with a
specific counterpart. The strings are defined in a delimited text file
with columns naemd "key" and "value".
"""
__author__ = "Michael J. Harms"
__date__ = "091205"
__usage__ = "editTreeNames.py file_to_modify master_file key_col value_col"
import os, sys, re
class EditNamesError(Exception):
"""
General error class for this module.
"""
pass
class NameObject:
"""
"""
def __init__(self,line,column_names,column_delimiter):
"""
Hold all column values for this sequence, keyed to column_name.
"""
column_values = [c.strip() for c in line.split(column_delimiter)]
if len(column_values) > len(column_names):
warning = "There are more data columns than data names for this\n"
warning += "line. This usually occurs if you added a '%s' within\n" \
% column_delimiter
warning += "one of the column entries. This may lead to wonkiness.\n"
warning += "The offending line is: \n\n"
warning += "%s\n" % line
warning += "which, when split, yields:\n\n"
warning += "\n".join(["%s: %s" % (column_names[i],column_values[i])
for i in range(len(column_names))])
warning += "\n\n"
sys.stderr.write(warning)
try:
self.columns = dict([(column_names[i],column_values[i])
for i in range(len(column_names))])
except IndexError:
err = "There is an error in the following line:\n\n"
err += line
err += "\n\nIncorrect number of columns?\n"
raise EditNamesError(err)
# make it so all column values can be accessed by a simple
# s.internal_name nomenclature
self.__dict__.update(self.columns)
def checkUniqueness(some_list):
"""
Verifies that every entry in a list is unique. If it is not, it returns
non-unique values.
"""
unique_list = dict([(x,[]) for x in some_list]).keys()
repeated_entries = [u for u in unique_list
if len([s for s in some_list if s == u]) > 1]
return repeated_entries
def readMasterFile(name_file,column_delimiter="\t"):
"""
Read a delimited (usually comma-delimited) file that has a set of sequence
attributes under a unique internal_name.
"""
f = open(name_file,'r')
lines = f.readlines()
f.close()
# Parse the file
lines = [l for l in lines if l[0] != "#" and l.strip() != ""]
# Create a dictionary that keys column names to column numbers
column_names = [c.strip() for c in lines[0].split(column_delimiter)]
column_dict = dict([(c,i) for i, c in enumerate(column_names)])
# Make sure file will be useful...
if "internal_name" not in column_names:
err = "\nYou must have an 'internal_name' column in this file!\n\n"
raise EditNamesError(err)
# Make sure column names are not repeated more than once
for k in column_dict.keys():
num_col_in_file = len([c for c in column_names if c == k])
if num_col_in_file > 1:
err = "column '%s' occurs more than once in the file!\n" % k
raise EditNamesError(err)
# Load all names
names = []
for l in lines[1:]:
names.append(NameObject(l,column_names,column_delimiter))
# make sure all internal_names are unique
internal_names = [n.internal_name for n in names]
repeated_names = checkUniqueness(internal_names)
if len(repeated_names) != 0:
err = "internal_name column must have unique entry for every line!\n"
err += "The following entries are repeated:\n\n"
err += "\n".join(repeated_names)
err += "\n\n"
raise EditNamesError(err)
return names
def modifyFile(file_to_modify,names,key_column,value_column):
"""
Read a file and replace all instances of the key_column with value_column
where key_column and value_column are defined uniquely for each sequence
in names.
"""
f = open(file_to_modify)
contents = f.read()
f.close()
# Grab keys and values from every sequence
keys = []
values = []
for n in names:
try:
keys.append(n.columns[key_column])
values.append(n.columns[value_column])
except KeyError:
err = "Sequences '%s' does not have '%s' or '%s'!\n\n" % \
(n.internal_name,key_column,value_column)
raise EditNamesError(err)
# Check keys and values to make sure they are unique
repeated_keys = checkUniqueness(keys)
if len(repeated_keys) != 0:
err = "Column '%s' has non-unique entries!\n" % key_column
err += "The following entries are repeated:\n\n"
err += "\n".join(repeated_keys)
err += "\n\n"
repeated_values = checkUniqueness(values)
if len(repeated_values) != 0:
err = "Column '%s' has non-unique entries!\n" % value_column
err += "The following entries are repeated:\n\n"
err += "\n".join(repeated_values)
err += "\n\n"
# Use regular experessions to replace all instances of key with value in the
# file.
name_dictionary = dict(zip(keys,values))
for key in name_dictionary.keys():
k = re.compile(key)
num_counts = len(k.findall(contents))
contents = k.sub("%s" % name_dictionary[key],contents,count=num_counts)
return contents
def main(argv=None):
"""
Read the command line and master file, then alter contents of
file_to_modify and print.
"""
if argv == None:
argv = sys.argv[1:]
try:
file_to_modify = argv[0]
master_file = argv[1]
key_column = argv[2]
value_column = argv[3]
except IndexError:
err = "Incorrect number of arguments!\n\nUsage:\n\n%s\n\n" % __usage__
raise EditNamesError(err)
names = readMasterFile(master_file)
out = modifyFile(file_to_modify,names,key_column,value_column)
print out
if __name__ == "__main__":
main()
| 6,270 | 1,939 |
#!/usr/bin/env python3
# _*_ coding: utf-8 _*_
"""Test docx2python.docx_context.py
author: Shay Hill
created: 6/26/2019
"""
import os
import shutil
import zipfile
from collections import defaultdict
from typing import Any, Dict
import pytest
from docx2python.docx_context import (
collect_docProps,
collect_numFmts,
get_context,
pull_image_files,
)
class TestCollectNumFmts:
"""Test strip_text.collect_numFmts """
# noinspection PyPep8Naming
def test_gets_formats(self) -> None:
"""Retrieves formats from example.docx
This isn't a great test. There are numbered lists I've added then removed as
I've edited my test docx. These still appear in the docx file. I could
compare directly with the extracted numbering xml file, but even then I'd be
comparing to something I don't know to be accurate. This just tests that all
numbering formats are represented.
"""
zipf = zipfile.ZipFile("resources/example.docx")
numId2numFmts = collect_numFmts(zipf.read("word/numbering.xml"))
formats = {x for y in numId2numFmts.values() for x in y}
assert formats == {
"lowerLetter",
"upperLetter",
"lowerRoman",
"upperRoman",
"bullet",
"decimal",
}
class TestCollectDocProps:
"""Test strip_text.collect_docProps """
def test_gets_properties(self) -> None:
"""Retrieves properties from docProps"""
zipf = zipfile.ZipFile("resources/example.docx")
props = collect_docProps(zipf.read("docProps/core.xml"))
assert props["creator"] == "Shay Hill"
assert props["lastModifiedBy"] == "Shay Hill"
@pytest.fixture
def docx_context() -> Dict[str, Any]:
"""result of running strip_text.get_context"""
zipf = zipfile.ZipFile("resources/example.docx")
return get_context(zipf)
# noinspection PyPep8Naming
class TestGetContext:
"""Text strip_text.get_context """
def test_docProp2text(self, docx_context) -> None:
"""All targets mapped"""
zipf = zipfile.ZipFile("resources/example.docx")
props = collect_docProps(zipf.read("docProps/core.xml"))
assert docx_context["docProp2text"] == props
def test_numId2numFmts(self, docx_context) -> None:
"""All targets mapped"""
zipf = zipfile.ZipFile("resources/example.docx")
numId2numFmts = collect_numFmts(zipf.read("word/numbering.xml"))
assert docx_context["numId2numFmts"] == numId2numFmts
def test_numId2count(self, docx_context) -> None:
"""All numIds mapped to a default dict defaulting to 0"""
for numId in docx_context["numId2numFmts"]:
assert isinstance(docx_context["numId2count"][numId], defaultdict)
assert docx_context["numId2count"][numId][0] == 0
def test_lists(self) -> None:
"""Pass silently when no numbered or bulleted lists."""
zipf = zipfile.ZipFile("resources/basic.docx")
context = get_context(zipf)
assert "numId2numFmts" not in context
assert "numId2count" not in context
class TestPullImageFiles:
"""Test strip_text.pull_image_files """
def test_pull_image_files(self) -> None:
"""Copy image files to output path."""
zipf = zipfile.ZipFile("resources/example.docx")
context = get_context(zipf)
pull_image_files(zipf, context, "delete_this/path/to/images")
assert os.listdir("delete_this/path/to/images") == ["image1.png", "image2.jpg"]
# clean up
shutil.rmtree("delete_this")
def test_no_image_files(self) -> None:
"""Pass silently when no image files."""
zipf = zipfile.ZipFile("resources/basic.docx")
context = get_context(zipf)
pull_image_files(zipf, context, "delete_this/path/to/images")
assert os.listdir("delete_this/path/to/images") == []
# clean up
shutil.rmtree("delete_this")
| 3,988 | 1,279 |
import transporters.approximator.runner as ra
from data.parameters_names import ParametersNames as Parameters
def transport(approximator, particles):
"""matrix in format returned by data.particles_generator functions"""
segments = dict()
segments["start"] = particles
matrix_for_transporter = particles.get_default_coordinates_of(Parameters.X, Parameters.THETA_X, Parameters.Y,
Parameters.THETA_Y, Parameters.PT)
transported_particles = ra.transport(approximator, matrix_for_transporter)
segments["end"] = particles.__class__(transported_particles, get_mapping())
return segments
def get_mapping():
mapping = {
Parameters.X: 0,
Parameters.THETA_X: 1,
Parameters.Y: 2,
Parameters.THETA_Y: 3,
Parameters.PT: 4
}
return mapping
def get_transporter(approximator):
def transporter(particles):
return transport(approximator, particles)
return transporter
| 1,022 | 297 |
from .embeddings import BertEmbeddings
from .encoder import BertEncoder
from .pooler import Pooler
from .pertrained_hooks import pretrained_bert_hook, pretrained_bert_classifier_hook
| 183 | 58 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-06-26 20:22
from __future__ import unicode_literals
import django.contrib.postgres.fields.jsonb
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('confsponsor', '0007_contract_per_conference'),
]
operations = [
migrations.RunSQL("UPDATE confsponsor_sponsorshipbenefit SET class_parameters='{}' WHERE class_parameters=''"),
migrations.AlterField(
model_name='sponsorshipbenefit',
name='class_parameters',
field=django.contrib.postgres.fields.jsonb.JSONField(blank=True),
),
]
| 666 | 224 |
import example_problem.analyst.dialogue_functions as analyst
import example_problem.engineer.dialogue_functions as engineer
import example_problem.critic.dialogue_functions as critic
| 186 | 50 |
#!/usr/bin/env python3
# Copyright 2021 Alibaba Group Holding Limited.
#
# 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.
import difflib
import os.path
import sys
from typing import List, Tuple
from lib import *
NOTICE_HEADER = '''PolarDB-X operator contains and relies on various third-party components under other open source licenses.
The following sections summaries those components and their licenses.
## Third-party
+ [hsperfdata](https://github.com/xin053/hsperfdata), [MIT license](./third-party/hsperfdata/LICENSE).
## Vendors
'''
def generate_markdown_list(vendor_licenses: List[Tuple[str, str, str]], vendor_license_root: str) -> List[str]:
vendor_license_markdown_item = []
for vendor_name, guessed_license, license_file_relative_path in vendor_licenses:
if len(guessed_license) > 0:
vendor_license_markdown_item.append(
'+ %s, [%s license](%s/%s).' % (
vendor_name, guessed_license, vendor_license_root, license_file_relative_path))
else:
vendor_license_markdown_item.append(
'+ %s, [license](%s/%s).' % (
vendor_name, vendor_license_root, license_file_relative_path))
return vendor_license_markdown_item
def normalize_license_content(s: str):
# remove all white spaces and concat with one blank.
return ' '.join(s.split()).lower()
MIT_LICENSE = normalize_license_content('''Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.''')
BSD2_LICENSE = normalize_license_content('''
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
''')
BSD3_LICENSE = normalize_license_content('''Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of AUTHOR nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
''')
BSD3_NEW_CLAUSE = normalize_license_content('''endorse or promote products derived from this software
without specific prior written permission''')
ISC_LICENSE = normalize_license_content('''Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.''')
def guess_license(license_file: str) -> str:
with open(license_file, 'r') as f:
content = f.read()
content = normalize_license_content(content)
if 'mit license' in content:
return 'MIT'
elif 'apache license' in content:
if 'version 2.0' in content:
return 'Apache 2.0'
else:
return 'Apache'
elif 'isc license' in content:
return 'ISC'
elif 'Mozilla Public License'.lower() in content:
if 'version 2.0' in content:
return 'MPL 2.0'
else:
return ''
else:
closest_matches = difflib.get_close_matches(content, [MIT_LICENSE, BSD2_LICENSE, BSD3_LICENSE, ISC_LICENSE], n=1, cutoff=0.3)
if len(closest_matches) == 0:
return ''
else:
m = closest_matches[0]
if m == MIT_LICENSE:
return 'MIT'
elif m == BSD3_LICENSE or m == BSD2_LICENSE:
if BSD3_NEW_CLAUSE in content:
# The new clause
return '3-Clause BSD'
else:
return '2-Clause BSD'
elif m == ISC_LICENSE:
return 'ISC'
else:
raise RuntimeError('never here')
def walk_through_vendor_licenses(licenses_dir: str) -> List[Tuple[str, str, str]]:
vendor_licenses = []
for root, dirs, files in os.walk(licenses_dir):
if 'LICENSE' in files:
relative_path = os.path.relpath(root, licenses_dir)
license_file_relative_path = os.path.join(relative_path, 'LICENSE')
vendor_licenses.append(
(relative_path, guess_license(os.path.join(root, 'LICENSE')), license_file_relative_path))
return vendor_licenses
def generate_notice_file(build_env: BuildEnv):
# Generate vendor licenses.
vendor_licenses_dir = os.path.join(build_env.root_dir, 'LICENSES/vendor')
vendor_licenses = walk_through_vendor_licenses(vendor_licenses_dir)
vendor_notice_list = generate_markdown_list(vendor_licenses, './LICENSES/vendor')
# Write to notice file.
notice_file = os.path.join(build_env.root_dir, 'NOTICE.md')
notice_content = NOTICE_HEADER + '\n\n'.join(vendor_notice_list) + '\n'
with open(notice_file, 'w+') as f:
f.write(notice_content)
def main():
generate_notice_file(BASIC_BUILD_ENV)
return 0
if __name__ == '__main__':
sys.exit(main())
| 9,077 | 3,010 |
import graph.bfs as bfs
import graph.dfs as dfs | 47 | 17 |
# -*- coding: utf-8 -*-
"""HydraTK core event handling implementation class
.. module:: core.eventhandler
:platform: Unix
:synopsis: HydraTK core event handling implementation class
.. moduleauthor:: Petr Czaderna <pc@hydratk.org>
"""
from hydratk.core import hsignal
class EventHandler(object):
"""Class EventHandler
"""
def _ec_check_co_privmsg(self, oevent):
self._check_co_privmsg()
def _ec_check_cw_privmsg(self, oevent):
self._check_cw_privmsg()
def _ec_stop_app(self, oevent, *args):
self._stop_app(*args)
def _eh_htk_on_got_cmd_options(self, oevent):
self.apply_command_options()
def _eh_htk_on_debug_info(self, oevent, *args):
self.dout(*args)
def _eh_htk_on_warning(self, oevent, *args):
if int(self.cfg['System']['Warnings']['enabled']) == 1:
self.wout(*args)
def _eh_htk_on_extension_warning(self, oevent, *args):
self.wout(*args)
def _eh_htk_on_error(self, oevent, *args):
self.errout(*args)
def _eh_htk_on_exception(self, oevent, *args):
self.exout(*args)
def _eh_htk_on_extension_error(self, oevent, *args):
self.errout(*args)
def _eh_htk_on_cprint(self, oevent, *args):
self.spout(*args)
def _ec_sig_handler(self, oevent, signum):
signal = hsignal.sigint2string[
signum] if signum in hsignal.sigint2string else signum
self.demsg('htk_on_debug_info', self._trn.msg(
'htk_sig_recv', signal), self.fromhere())
| 1,542 | 571 |
" Charon: Context handler for saving an entity. "
import logging
import couchdb
from . import constants
from . import utils
class Field(object):
"Specification of a data field for an entity."
type ='text'
def __init__(self, key, title=None, description=None,
mandatory=False, editable=True, default=None):
assert key
self.key = key
self.title = title or key.capitalize().replace('_', ' ')
self.description = description or self.__doc__
self.mandatory = mandatory # A non-None value is requried.
self.editable = editable # Changeable once set?
self.default=default
self.none_value=u'None'
def store(self, saver, data=None, check_only=False):
"""Check, convert and store the field value.
If 'data' is None, then obtain the value from HTML form parameter.
If 'check_only' is True, then just do validity checking, no update.
"""
if not saver.is_new() and not self.editable: return
logging.debug("Field.store(%s)", data)
value = self.get(saver, data=data)
try:
value = self.process(saver, value)
except ValueError, msg:
raise ValueError("field '{0}': {1}".format(self.key, msg))
if check_only: return
if self.default is not None and value is None:
value = self.default
if value == saver.doc.get(self.key):
logging.debug("Field.store: '%s' value equal", self.key)
return
saver.doc[self.key] = value
saver.changed[self.key] = value
def get(self, saver, data=None):
"Obtain the value from data, if given, else from HTML form parameter."
if data is None:
value = saver.rqh.get_argument(self.key, default=None)
if value == self.none_value:
return None
else:
return value
else:
try:
return data[self.key]
except KeyError:
return saver.get(self.key)
def process(self, saver, value):
"""Check validity and return converted to the appropriate type.
Raise ValueError if there is a problem."""
self.check_mandatory(saver, value)
self.check_valid(saver, value)
return value or None
def check_mandatory(self, saver, value):
"Check that a value is provided when required."
if self.mandatory and value is None:
raise ValueError('a defined value is mandatory')
def check_valid(self, saver, value):
"Check that the value, if provided, is valid."
pass
def html_display(self, entity):
"Return the field value as valid HTML."
return str(entity.get(self.key) or '-')
def html_create(self):
"Return an appropriate HTML input field for a create form."
return '<input type="text" name="{0}">'.format(self.key)
def html_edit(self, entity):
"Return an appropriate HTML input field for an edit form."
if self.editable:
return '<input type="text" name="{0}" value="{1}">'.\
format(self.key, entity.get(self.key) or '')
else:
return entity.get(self.key) or '-'
class ListField(Field):
type = "list"
def __init__(self, key, title=None, description=None, default=[]):
super(ListField, self).__init__(key, title=title,
description=description,
mandatory=False, editable=True,
default=default)
self.none_value = []
def process(self, saver, value):
self.check_mandatory(saver, value)
old_value = saver.doc.get(self.key)
if old_value is None:
old_value=[]
if value not in [None, '']:
if isinstance(value, list):
old_value = value
elif value.startswith('[') and value.endswith(']'):
old_value=[]
#assume it's a serialized list
values=value[1:-1].split(",")
for val in values:
if val.strip().startswith("u'") and val.endswith("'"):
old_value.append(val[2:-1])
else:
old_value.append(val)
else:
old_value = [value]
return old_value
class IdField(Field):
"The identifier for the entity."
type ='identifier'
def __init__(self, key, title=None, description=None):
super(IdField, self).__init__(key, title=title,
description=description,
mandatory=True, editable=False)
def check_valid(self, saver, value):
"Only allow a subset of ordinary ASCII characters."
logging.debug('IdField.check_valid')
if not constants.ALLOWED_ID_CHARS.match(value):
raise ValueError('invalid identifier value (disallowed characters)')
class SelectField(Field):
"Select one of a set of values."
none_value = u'None'
def __init__(self, key, title=None, description=None,
mandatory=False, editable=True, options=[]):
super(SelectField, self).__init__(key, title=title,
description=description,
mandatory=mandatory,
editable=editable)
self.options = options
def get(self, saver, data=None):
"Obtain the value from data, if given, else from HTML form parameter."
if data is None :
value = saver.rqh.get_argument(self.key, default=None)
if value == self.none_value:
return None
else:
return value
else:
try:
return data[self.key]
except KeyError:
return saver.get(self.key)
def check_valid(self, saver, value):
"Check that the value, if provided, is valid."
if value is None or value == self.none_value: return
if value not in self.options:
logging.debug("invalid select value: %s", value)
raise ValueError("invalid value '{0}; not among options for select".
format(value))
def html_create(self):
"Return the field HTML input field for a create form."
options = ["<option>{0}</option>".format(o) for o in self.options]
if not self.mandatory:
options.insert(0, "<option>{0}</option>".format(self.none_value))
return '<select name="{0}">{1}</select>'.format(self.key, options)
def html_edit(self, entity):
"Return the field HTML input field for an edit form."
value = entity.get(self.key)
if self.editable:
options = []
if not self.mandatory:
if value is None:
options.append("<option selected>{0}</option>".format(
self.none_value))
else:
options.append("<option>{0}</option>".format(
self.none_value))
for option in self.options:
if value == option:
options.append("<option selected>{0}</option>".format(option))
else:
options.append("<option>{0}</option>".format(option))
return '<select name="{0}">{1}</select>'.format(self.key, options)
else:
return value or '-'
class NameField(Field):
"The name for the entity, unique if non-null."
def __init__(self, key, title=None, description=None):
super(NameField, self).__init__(key, title=title,
description=description,
mandatory=False)
class FloatField(Field):
"A floating point value field."
type ='float'
def __init__(self, key, title=None, description=None,
mandatory=False, editable=True, default=None):
super(FloatField, self).__init__(key,
title=title,
description=description,
mandatory=mandatory,
editable=editable, default=default)
def process(self, saver, value):
self.check_mandatory(saver, value)
if value is None: return None
if value == '': return None
return float(value)
def html_display(self, entity):
"Return the field value as valid HTML."
value = entity.get(self.key)
if value is None:
value = '-'
else:
value = str(value)
return '<span class="number">{0}</span>'.format(value)
def html_edit(self, entity):
"Return the field HTML input field for an edit form."
value = entity.get(self.key)
if value is None:
if self.editable:
return '<input type="text" name="{0}">'.format(self.key)
else:
return '-'
else:
if self.editable:
return '<input type="text" name="{0}" value="{1}">'.\
format(self.key, value)
else:
return str(value)
class RangeFloatField(FloatField):
"A floating point value field, with an allowed range."
def __init__(self, key, minimum=None, maximum=None,
title=None, description=None,
mandatory=False, editable=True):
super(RangeFloatField, self).__init__(key,
title=title,
description=description,
mandatory=mandatory,
editable=editable)
self.minimum = minimum
self.maximum = maximum
def process(self, saver, value):
value = super(RangeFloatField, self).process(saver, value)
if value is None: return None
if self.minimum is not None:
if value < self.minimum: raise ValueError('value too low')
if self.maximum is not None:
if value > self.maximum: raise ValueError('value too high')
return value
class Saver(object):
"Context handler defining the fields of the entity and saving the data."
doctype = None
fields = []
field_keys = []
def __init__(self, doc=None, rqh=None, db=None):
self.fields_lookup = dict([(f.key, f) for f in self.fields])
assert self.doctype
if rqh is not None:
self.rqh = rqh
self.db = rqh.db
self.current_user = rqh.current_user
elif db is not None:
self.db = db
self.current_user = dict()
else:
raise AttributeError('neither db nor rqh given')
self.doc = doc or dict()
self.changed = dict()
if '_id' in self.doc:
assert self.doctype == self.doc[constants.DB_DOCTYPE]
else:
self.doc['_id'] = utils.get_iuid()
self.doc[constants.DB_DOCTYPE] = self.doctype
self.initialize()
def __enter__(self):
return self
def __exit__(self, type, value, tb):
if type is not None: return False # No exceptions handled here
self.finalize()
try:
self.db.save(self.doc)
except couchdb.http.ResourceConflict:
raise IOError('document revision update conflict')
if self.changed:
utils.log(self.db, self.doc,
changed=self.changed,
current_user=self.current_user)
def __setitem__(self, key, value):
"Update the key/value pair."
try:
field = self.fields_lookup[key]
except KeyError:
try:
checker = getattr(self, "check_{0}".format(key))
except AttributeError:
pass
else:
checker(value)
try:
converter = getattr(self, "convert_{0}".format(key))
except AttributeError:
pass
else:
value = converter(value)
try:
if self.doc[key] == value: return
except KeyError:
pass
self.doc[key] = value
self.changed[key] = value
else:
field.store(self, value)
def __getitem__(self, key):
return self.doc[key]
def initialize(self):
"Perform actions when creating the entity."
self.doc['created'] = utils.timestamp()
def is_new(self):
"Is the entity new, i.e. not previously saved in the database?"
return '_rev' not in self.doc
def store(self, data=None, check_only=False):
"""Given the fields, store the data items.
If data is None, then obtain the value from HTML form parameter.
If 'check_only' is True, then just do validity checking, no update.
"""
for field in self.fields:
field.store(self, data=data, check_only=check_only)
def finalize(self):
"Perform any final modifications before saving the entity."
self.doc['modified'] = utils.timestamp()
def get(self, key, default=None):
try:
return self[key]
except KeyError:
return default
| 13,660 | 3,637 |
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient
from core.models import PortfolioItem
from projects.serializers import PortfolioItemSerializer
PORTFOLIO_URL = reverse('projects:portfolioitem-list')
def detail_url(portfolio_id):
"""Return the detail URL of a portfolio item"""
return reverse('projects:portfolioitem-detail', args=[portfolio_id])
class PublicPortfolioApiTests(TestCase):
"""Test the publicly available projects API"""
def setUp(self):
self.client = APIClient()
def test_login_not_required(self):
"""Test that login is not required to access the endpoint"""
res = self.client.get(PORTFOLIO_URL)
self.assertEqual(res.status_code, status.HTTP_200_OK)
def test_retrieve_portfolio_list(self):
"""Test retrieving a list of portfolio items"""
sample_user = get_user_model().objects.create_user(
'test@xemob.com',
'testpass'
)
PortfolioItem.objects.create(user=sample_user,
name='Portfolio Item 1')
PortfolioItem.objects.create(user=sample_user,
name='Portfolio Item 2')
res = self.client.get(PORTFOLIO_URL)
portfolio_items = PortfolioItem.objects.all().order_by('-name')
serializer = PortfolioItemSerializer(portfolio_items, many=True)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(res.data, serializer.data)
class PrivatePortfolioApiTests(TestCase):
"""Test the private portfolio API"""
def setUp(self):
self.client = APIClient()
self.user = get_user_model().objects.create_user(
'test@xemob.com',
'testpass'
)
self.client.force_authenticate(self.user)
def test_create_portfolio_item_successfully(self):
"""Test creating a new portfolio item"""
payload = {'name': 'New portfolio item', 'user': self.user.id}
self.client.post(PORTFOLIO_URL, payload)
exists = PortfolioItem.objects.filter(
user=self.user,
name=payload['name']
).exists()
self.assertTrue(exists)
def test_create_portfolio_item_invalid(self):
"""Test creating a portfolio item with invalid payload"""
payload = {'name': '', 'user': self.user.id}
res = self.client.post(PORTFOLIO_URL, payload)
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
def test_partial_portfolio_update_successfully(self):
"""Test partial updating a project by owner is successful"""
portfolio_item = PortfolioItem.objects.create(user=self.user,
name='Portfolio Item 1')
payload = {'name': 'Alt portfolio item'}
url = detail_url(portfolio_item.id)
res = self.client.patch(url, payload)
portfolio_item.refresh_from_db()
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(portfolio_item.name, payload['name'])
def test_partial_portfolio_update_invalid(self):
"""Test updating a portfolio item by not owner is invalid"""
self.user2 = get_user_model().objects.create_user(
'other@xemob.com',
'testpass'
)
portfolio_item = PortfolioItem.objects.create(user=self.user2,
name='Portfolio Item 1')
payload = {'name': 'Alt portfolio item'}
url = detail_url(portfolio_item.id)
res = self.client.patch(url, payload)
portfolio_item.refresh_from_db()
self.assertEqual(res.status_code, status.HTTP_403_FORBIDDEN)
self.assertNotEqual(portfolio_item.name, payload['name'])
def test_full_portfolio_update_successful(self):
"""Test updating a portfolio item by owner is successful with PUT"""
portfolio_item = PortfolioItem.objects.create(user=self.user,
name='Portfolio Item 1')
payload = {'user': self.user.id, 'name': 'Alt portfolio item'}
url = detail_url(portfolio_item.id)
res = self.client.put(url, payload)
portfolio_item.refresh_from_db()
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(portfolio_item.name, payload['name'])
def test_full_portfolio_update_invalid(self):
"""Test updateing a portfolio item by not owner is invalid with PUT"""
self.user2 = get_user_model().objects.create_user(
'other@xemob.com',
'testpass'
)
portfolio_item = PortfolioItem.objects.create(user=self.user2,
name='Portfolio Item 1')
payload = {'user': self.user.id, 'name': 'Alt portfolio item'}
url = detail_url(portfolio_item.id)
res = self.client.put(url, payload)
portfolio_item.refresh_from_db()
self.assertEqual(res.status_code, status.HTTP_403_FORBIDDEN)
self.assertNotEqual(portfolio_item.name, payload['name'])
| 5,264 | 1,543 |
# -*- coding: utf-8 -*-
"""
Created on: Sun May 21 05:09:40 2017
Author: Waldu Woensdregt
Description: Code uses OpenWPM package to extract HTTPS responses from
selected set of URLs (defined in GetListOfSiteURLsToExtract)
and then splits the resulting data into individual URL
parameters to allow it to be sorted and classified for use
in a thesis masters assignment
"""
import msc_UseOpenWPM
from msc_ParamCleansing import open_db_conn
from msc_ParamCleansing import setup_db_tables
from msc_ParamCleansing import extract_parameters
def get_site_urls_to_extract():
url_list = []
# url_list.append('http://www.smallestwebsitetotheworld.com/') # for testing
# url_list.append('https://www.reddit.com/') # for testing
url_list.append('https://www.youtube.com/watch?v=JGwWNGJdvx8')
url_list.append('https://www.reddit.com/')
url_list.append('https://www.amazon.co.uk/')
url_list.append('http://www.ebay.co.uk/itm/232254122171')
url_list.append('http://www.ladbible.com/')
url_list.append('https://www.yahoo.com/')
url_list.append('https://www.theguardian.com/uk')
url_list.append('http://diply.com/')
url_list.append('http://imgur.com/gallery/nxrNk')
url_list.append('http://www.dailymail.co.uk/home/index.html')
url_list.append('https://www.twitch.tv/')
url_list.append('http://www.imdb.com/')
url_list.append('http://www.rightmove.co.uk/property-for-sale/property-66961808.html')
url_list.append('http://www.telegraph.co.uk/')
url_list.append('http://fandom.wikia.com/articles/pitch-perfect-3-teaser-trailer-drops')
url_list.append('http://www.sportbible.com/football/transfers-barcelonas-plan-b-is-just-as-good-as-marco-verratti'
'-20170625')
url_list.append('http://www.independent.co.uk/')
url_list.append('https://www.gumtree.com/p/plumbing-central-heating/gas-fired-log-fired-central-heating-system'
'-cheap-/1250349004')
url_list.append('https://wordpress.com/')
url_list.append('http://www.msn.com/en-gb/lifestyle/family-relationships/meghan-markle-responds-to-marriage'
'-rumours/ar-BBCxAHD')
return url_list
# -------------------------------------------------------------------------- #
# - MAIN START - #
# ------------------------------------------------------------------------- -#
# init variables
myprefix = 'msc_' # table prefix to easily keep them separate from OpenWPM
# enable/disable certain parts during testing
runDataCollection = 1 # 1 = enabled
do_extractParameters = 1 # 1 = enabled
# open database connection
conn = open_db_conn()
# connect to DB and get max crawl (to later know which crawls are new)
max_crawl_id = conn.execute('SELECT MAX(crawl_id) FROM crawl').fetchone()[0]
print 'Max CrawlID before new crawl = ' + str(max_crawl_id)
setup_db_tables(conn, myprefix) # create msc tables if they do not exist
# Run data collection
new_crawl_id = 0
if runDataCollection == 1:
sites = get_site_urls_to_extract()
msc_UseOpenWPM.extract_via_openwpm(sites)
print 'Data collection completed for:'
for site in sites:
print ' - ' + site
new_crawl_id = conn.execute('SELECT MAX(crawl_id) FROM crawl').fetchone()[0]
print 'All data extraction completed for new crawl: {}'.format(new_crawl_id)
# extract parameters into parameter table
if do_extractParameters == 1 and new_crawl_id > 0:
extract_parameters(conn, new_crawl_id, myprefix)
# close database connection
conn.close()
print '-done-'
| 3,662 | 1,264 |
import pandas as pd
import datetime
import geopandas as gpd
import os
from tqdm import tqdm
from shapely import wkt
from config import config
import trackintel as ti
def generate_Location(df, epsilon, user):
"""Cluster staypoints to locations, with different parameters and distinguish 'user' and 'dataset'"""
# select only activity staypoints
df = df.loc[df["activity"] == True].copy()
# change to trackintel format
df.set_index("id", inplace=True)
tqdm.pandas(desc="Load Geometry")
df["geom"] = df["geom"].progress_apply(wkt.loads)
gdf = gpd.GeoDataFrame(df, crs="EPSG:4326", geometry="geom")
# cluster the staypoints into locations (DBSCAN)
if user:
agg_level = "user"
else:
agg_level = "dataset"
stps, locs = gdf.as_staypoints.generate_locations(
epsilon=epsilon, num_samples=1, distance_metric="haversine", agg_level=agg_level, n_jobs=-1
)
print("cluster complete")
# rename to avoid conflict
stps.rename(
columns={"user_id": "userid", "started_at": "startt", "finished_at": "endt", "location_id": "locid"},
inplace=True,
)
locs.rename(columns={"user_id": "userid"}, inplace=True)
stps["startt"] = pd.to_datetime(stps["startt"]).dt.tz_localize(None)
stps["endt"] = pd.to_datetime(stps["endt"]).dt.tz_localize(None)
stps.sort_index(inplace=True)
locs.sort_index(inplace=True)
stps.to_csv(os.path.join(config["proc"], f"stps_act_{agg_level}_{epsilon}.csv"), index=True)
locs.to_csv(os.path.join(config["proc"], f"locs_{agg_level}_{epsilon}.csv"), index=True)
if __name__ == "__main__":
# SBB
# df = pd.read_csv(os.path.join(config["raw"], "stps.csv"))
# df.rename(columns={"userid": "user_id", "startt": "started_at", "endt": "finished_at"}, inplace=True)
# df["started_at"], df["finished_at"] = pd.to_datetime(df["started_at"]), pd.to_datetime(df["finished_at"])
# # end period cut
# end_period = datetime.datetime(2017, 12, 25)
# df = df.loc[df["finished_at"] < end_period].copy()
# df["started_at"] = df["started_at"].dt.tz_localize(tz="utc")
# df["finished_at"] = df["finished_at"].dt.tz_localize(tz="utc")
# Geolife
df = pd.read_csv(os.path.join(config["proc"], "stps.csv"))
df.rename(columns={"userid": "user_id", "startt": "started_at", "endt": "finished_at"}, inplace=True)
df["started_at"], df["finished_at"] = pd.to_datetime(df["started_at"]), pd.to_datetime(df["finished_at"])
generate_Location(df, epsilon=50, user=True)
| 2,545 | 967 |
from EVBUS import EVBUS
from sklearn.datasets import load_boston
import sklearn.model_selection as xval
boston = load_boston()
Y = boston.data[:, 12]
X = boston.data[:, 0:12]
bos_X_train, bos_X_test, bos_y_train, bos_y_test = xval.train_test_split(X, Y, test_size=0.3)
evbus = EVBUS.varU(bos_X_train, bos_y_train, bos_X_test)
v = evbus.calculate_variance()
print(v)
| 369 | 165 |
from __future__ import absolute_import
from __future__ import unicode_literals
from django.contrib.auth import get_user_model
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.utils.translation import ugettext as _
from bazaar.listings.models import Listing
from rest_framework import status
from tests import factories as f
from tests.factories import PublishingFactory, ListingFactory
class TestBase(TestCase):
def setUp(self):
self.user = get_user_model().objects.create_user(username='test', email='test@test.it', password='test')
class TestListingsListView(TestBase):
def test_list_view(self):
"""
Test that list view works fine
"""
# By default this operation will create a bound listing x1 of that product
self.product = f.ProductFactory(name='product1', price=2, description='the best you can have!')
self.listing = self.product.listings.first()
self.client.login(username=self.user.username, password='test')
response = self.client.get(reverse('bazaar:listing-list'))
self.assertEqual(response.status_code, status.HTTP_200_OK)
listings = response.context_data['listing_list']
self.assertEqual(listings.count(), 1)
self.assertEqual(listings[0].sku, self.listing.sku)
def test_list_view_not_working_without_login(self):
"""
Test that trying to call the list view without being logged redirects to the login page
"""
response = self.client.get(reverse('bazaar:listing-list'))
self.assertRedirects(response, '/accounts/login/?next=/listings/')
def test_list_view_no_products(self):
"""
Test that a void list view displays "no products"
"""
self.client.login(username=self.user.username, password='test')
response = self.client.get(reverse('bazaar:listing-list'))
self.assertEqual(response.status_code, status.HTTP_200_OK)
listings = response.context_data['listing_list']
self.assertEqual(listings.count(), 0)
self.assertIn(_('There are 0 listings').encode(encoding='UTF-8'), response.content)
class TestListingUpdateView(TestBase):
def test_update_view_not_working_without_login(self):
"""
Test that the update view redirects to the login page if the user is not logged
"""
response = self.client.get(reverse('bazaar:listing-update', kwargs={'pk': 1}))
self.assertRedirects(response, '/accounts/login/?next=%s' % reverse('bazaar:listing-update', kwargs={'pk': 1}))
def test_update_listing_does_not_change_sku(self):
self.client.login(username=self.user.username, password='test')
product = f.ProductFactory()
listing = product.listings.first()
self.client.login(username=self.user.username, password='test')
data = {'product': product.pk}
response = self.client.post(reverse('bazaar:listing-update', kwargs={'pk': listing.pk}), data=data)
self.assertEqual(response.status_code, status.HTTP_302_FOUND)
modified_listing = Listing.objects.get(pk=listing.pk)
self.assertEqual(listing.sku, modified_listing.sku)
def test_new_simple_view_has_back_button(self):
"""
Test that the new view has back and save button
"""
self.client.login(username=self.user.username, password='test')
response = self.client.get(reverse('bazaar:listing-create'))
content = response.content.decode('utf-8')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertIn('href="/listings/"', content)
self.assertIn('id="submit-id-save"', content)
class TestListingCreateView(TestBase):
def test_create_simple_listing_view(self):
"""
Test that the create view works fine
"""
# By default this operation will create a bound listing x1 of that product
self.product = f.ProductFactory(name='product1', price=2, description='the best you can have!')
self.listing = self.product.listings.first()
self.client.login(username=self.user.username, password='test')
data = {'product': self.product.id}
response = self.client.post(reverse('bazaar:listing-create'), data=data)
new_listing = Listing.objects.exclude(sku=self.listing.sku).first()
self.assertRedirects(response, '/listings/%s/' % new_listing.pk)
def test_create_view_not_working_without_login(self):
"""
Test that the create view redirects to the login page if the user is not logged
"""
# By default this operation will create a bound listing x1 of that product
self.product = f.ProductFactory(name='product1', price=2, description='the best you can have!')
self.listing = self.product.listings.first()
data = {'product': self.product.id}
response = self.client.post(reverse('bazaar:listing-create'), data=data)
self.assertRedirects(response, '/accounts/login/?next=/listings/new/')
class TestDeleteView(TestBase):
def test_delete_view_not_working_without_login(self):
"""
Test that the delete view redirects to the login page if the user is not logged
"""
response = self.client.get(reverse('bazaar:listing-delete', kwargs={'pk': 1}))
self.assertRedirects(response, '/accounts/login/?next=/listings/delete/%s/' % 1)
def test_delete_view(self):
"""
Test that the delete view works fine
"""
# By default this operation will create a bound listing x1 of that product
self.product = f.ProductFactory(name='product1', price=2, description='the best you can have!')
self.listing = self.product.listings.first()
self.client.login(username=self.user.username, password='test')
response = self.client.post(reverse('bazaar:listing-delete', kwargs={'pk': self.listing.pk}))
self.assertEqual(response.status_code, status.HTTP_302_FOUND)
listing_exists = Listing.objects.filter(pk=self.listing.pk).exists()
self.assertEqual(listing_exists, False)
def test_delete_view_let_delete_a_listing_only_if_it_has_not_publishing_associated(self):
"""
Test that the product has associated publishings
"""
# By default this operation will create a bound listing x1 of that product
self.product = f.ProductFactory(name='product1', price=2, description='the best you can have!')
self.listing = self.product.listings.first()
publishing = PublishingFactory(listing=self.listing)
self.client.login(username=self.user.username, password='test')
response = self.client.post(reverse('bazaar:listing-delete', kwargs={'pk': self.listing.pk}))
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
publishing.delete()
response = self.client.post(reverse('bazaar:listing-delete', kwargs={'pk': self.listing.pk}))
self.assertEqual(response.status_code, status.HTTP_302_FOUND)
listing_exists = Listing.objects.filter(pk=self.listing.pk).exists()
self.assertEqual(listing_exists, False)
| 7,226 | 2,102 |
import json
import requests
from bs4 import BeautifulSoup
PAGE_URL = 'https://olympics.com/tokyo-2020/olympic-games/en/results/all-sports/medal-standings.htm'
def get_table(html=None):
if not html: html = requests.get(PAGE_URL).content
site = BeautifulSoup(html, 'html.parser')
table = site.find('table', { 'id': 'medal-standing-table' })
return table.findAll('tr')[1:] # Remove header
def get_num(value):
try:
return int(value.find('a').getText())
except:
return 0
def get_counts(entry):
values = entry.findAll('td', { 'class': 'text-center'})
return int(values[0].find('strong').getText()), { # 4 total, 3 bronze, 2 silver, 1 gold, 0 rank
'gold': get_num(values[1]),
'silver': get_num(values[2]),
'bronze': get_num(values[3]),
'total': get_num(values[4]),
}
def get_rankings():
rankings = []
for country in get_table():
rank, medals = get_counts(country)
rankings.append({
'country': country.find('a', { 'class': 'country'}).getText(),
'country_alpha3': country.find('div', { 'class': 'playerTag'})['country'],
'rank': rank,
'medals': medals
})
return rankings
def lambda_handler(event, context):
try:
country = event['queryStringParameters']['country']
except:
country = None
print(f'Request -> Country: {country}')
rankings = get_rankings()
if country:
if len(country) == 3:
for country_ranking in rankings:
if country == country_ranking['country_alpha3']:
rankings = country_ranking
return {
"statusCode": 200,
"headers": {
"Access-Control-Allow-Headers": "Content-Type,X-Amz-Date,X-Amz-Security-Token,Authorization,X-Api-Key,X-Requested-With,Accept,Access-Control-Allow-Methods,Access-Control-Allow-Origin,Access-Control-Allow-Headers",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET"
},
"body": json.dumps(rankings),
"isBase64Encoded": False
}
| 2,141 | 707 |
import queue
import json
import logging
import threading
from crawlers.core.flags import FLAGS
class BaseThread(threading.Thread):
def __init__(self, name: str, worker, pool):
threading.Thread.__init__(self, name=name)
self._worker = worker # can be a Fetcher/Parser/Saver instance
self._thread_pool = pool # ThreadPool
def running(self):
return
def run(self):
logging.warning(f'{self.__class__.__name__}[{self.getName()}] started...')
while True:
try:
# keep running self.working() and checking result
# break (terminate) thread when self.working() failed
# break (terminate) thread when queue is empty, and all jobs
# are done
if not self.running():
break
except queue.Empty:
if self._thread_pool.all_done():
break
except Exception as e:
import sys, os
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
logging.warning(f'{self.__class__.__name__} end: error={str(e)}, file={str(fname)}, line={str(exc_tb.tb_lineno)}')
break
logging.warning(f'{self.__class__.__name__}[{self.getName()}] ended...')
class FetcherThread(BaseThread):
def __init__(self, name: str, worker, pool, session=None):
super().__init__(name, worker, pool)
self.session = session
def running(self):
"""
invoke Fetcher's working()
content: (status_code, url, html_text)
"""
priority, url, data, deep, repeat = self._thread_pool.get_task(FLAGS.FETCH)
try:
data = json.loads(data)
except:
data = {}
fetch_result, data, content = self._worker.working(url, data, repeat, self.session)
# fetch success, update FETCH counter, add task to task_queue_p, for
# parser's further process
if isinstance(data, dict):
data = json.dumps(data)
if fetch_result == 1:
self._thread_pool.update_flag(FLAGS.FETCH, 1)
self._thread_pool.put_task(FLAGS.PARSE, (priority, url, data, deep, content))
# fetch failed, put back to task_queue_f and repeat later
elif fetch_result == 0:
self._thread_pool.put_task(FLAGS.FETCH, (priority + 1, url, data, deep, repeat + 1))
# current round of fetcher is done, notify task_queue_f with
# task_done() to stop block
self._thread_pool.finish_task(FLAGS.FETCH)
return False if fetch_result == -1 else True
class ParserThread(BaseThread):
def __init__(self, name: str, worker, pool):
super().__init__(name, worker, pool)
def running(self):
"""
invoke Parser's working()
get all required urls from target html text
content: (status_code, url, html_text)
"""
priority, url, data, deep, content = self._thread_pool.get_task(FLAGS.PARSE)
try:
data = json.loads(data)
except:
data = {}
parse_result = 1
urls = []
stamp = ()
# if data is negative or data has a negative 'save' value, parse the
# html, otherwise skip
if not data or not data.get('save'):
parse_result, urls, stamp = self._worker.working(priority, url, data, deep, content)
if parse_result > 0:
self._thread_pool.update_flag(FLAGS.PARSE, 1)
# add each url in urls list into task_queue_f, waiting for
# fetcher's further process
for _url, _data, _priority in urls:
if isinstance(_data, dict):
_data = json.dumps(_data)
self._thread_pool.put_task(FLAGS.FETCH, (_priority, _url, _data, deep + 1, 0))
# add current url (already fetched/parsed) into task_queue_s,
# waiting for saver's further process
#
# if data in task_queue_p has a positive 'save' value, or no data but with an url
if (data and data.get('save')) or (not data and url):
try:
# when saving to task_queue_s, delete 'save' key
del data['save']
del data['type']
data = json.dumps(data)
except:
pass
self._thread_pool.put_task(FLAGS.SAVE, (url, data, stamp))
# current round of parser is done, notify task_queue_p with
# task_done() to stop block
self._thread_pool.finish_task(FLAGS.PARSE)
return True
class SaverThread(BaseThread):
def __init__(self, name: str, worker, pool):
super().__init__(name, worker, pool)
def running(self):
"""
invoke Saver's working()
"""
url, data, stamp = self._thread_pool.get_task(FLAGS.SAVE)
save_result = self._worker.working(url, data, stamp)
if save_result:
self._thread_pool.update_flag(FLAGS.SAVE, 1)
# current round of saver is done, notify task_queue_s with
# task_done() to stop block
self._thread_pool.finish_task(FLAGS.SAVE)
return True
| 5,348 | 1,563 |
from .sophie import SophieAI
| 30 | 12 |
#!/usr/bin/env python2.7
#
# Take various CSV inputs and produce a read-to-import conference schedule.
import pandas as pd
from datetime import date
def main():
dfs = []
t = pd.read_csv('talks.csv')
t['kind_slug'] = 'talk'
t['proposal_id'] = t.pop('proposal')
t['day'] = date(2016, 5, 30) + pd.to_timedelta(t['day'], 'd')
t['room'] = 'Session ' + t['room']
t = t[['kind_slug', 'proposal_id', 'day', 'time', 'duration', 'room']]
dfs.append(t)
t = pd.read_csv('~/Downloads/PyCon 2016 Tutorial Counts - Sheet1.csv')
rooms = {str(title).strip().lower(): room_name
for title, room_name in t[['Title', 'Room Name']].values}
t = pd.read_csv('tutorials.csv')
t['kind_slug'] = 'tutorial'
t['proposal_id'] = t.pop('ID')
t['day'] = pd.to_datetime(t['Day Slot'])
t['time'] = t['Time Slot'].str.extract('([^ ]*)')
t['duration'] = 200
t['room'] = t['Title'].str.strip().str.lower().map(rooms)
t = t[['kind_slug', 'proposal_id', 'day', 'time', 'duration', 'room']]
dfs.append(t)
t = pd.read_csv('sponsor-tutorials-edited.csv')
t = t[t['ID'].notnull()].copy()
t['kind_slug'] = 'sponsor-tutorial'
#t['kind_slug'] = 'tutorial'
t['proposal_id'] = t.pop('ID').astype(int)
t['day'] = pd.to_datetime(t['Day Slot'])
t['time'] = t['Time Slot'].str.extract('([^ ]*)')
t['room'] = t['Room']
# t = t.sort_values(['Title'])
# t['room'] = t.groupby(['day', 'time'])['room'].cumsum()
# t['room'] = t['room'].apply(lambda n: 'Sponsor Room {}'.format(n))
t = t[['kind_slug', 'proposal_id', 'day', 'time', 'duration', 'room']]
dfs.append(t)
#t.to_csv('schedule.csv', index=False)
c = pd.concat(dfs).rename(columns={'time': 'start'})
c.to_csv('schedule.csv', index=False)
if __name__ == '__main__':
main()
| 1,848 | 757 |
NUM_ROWS = 128
NUM_COLS = 8
"""
Cool solution:
https://github.com/tymofij/advent-of-code-2020/blob/master/05/seats.py
Cool solution using str.translate:
def seat_id(s, t=str.maketrans("FBLR", "0101")):
return int(s.translate(t), 2)
def max_seat_id(boarding_passes):
return max(map(seat_id, boarding_passes))
def missing_seat(boarding_passes, t=str.maketrans("FBLR", "0101")):
return max(set(range(920)) - set(int(s.translate(t), 2) for s in boarding_passes))
"""
def part1(l):
highest_id = -1
for p in l:
row = -1
col = -1
r_lo = c_lo = 0
r_hi = NUM_ROWS - 1
c_hi = NUM_COLS - 1
for s in p:
r_mid = r_lo + (r_hi - r_lo) // 2
c_mid = c_lo + (c_hi - c_lo) // 2
if s == 'F':
r_hi = r_mid
elif s == 'B':
r_lo = r_mid + 1
elif s == 'R':
c_lo = c_mid + 1
elif s == 'L':
c_hi = c_mid
else:
return -1
assert r_hi == r_lo
assert c_hi == c_lo
row, col = r_hi, c_hi
seat_id = row * 8 + col
if seat_id > highest_id:
highest_id = seat_id
return highest_id
def part2(l):
seats = []
for p in l:
row = -1
col = -1
r_lo = c_lo = 0
r_hi = NUM_ROWS - 1
c_hi = NUM_COLS - 1
for s in p:
r_mid = r_lo + (r_hi - r_lo) // 2
c_mid = c_lo + (c_hi - c_lo) // 2
if s == 'F':
r_hi = r_mid
elif s == 'B':
r_lo = r_mid + 1
elif s == 'R':
c_lo = c_mid + 1
elif s == 'L':
c_hi = c_mid
else:
return -1
assert r_hi == r_lo
assert c_hi == c_lo
row, col = r_hi, c_hi
seat_id = row * 8 + col
seats.append(seat_id)
# all_seats = [r * 8 + c for r in range(NUM_ROWS) for c in range(NUM_COLS)]
# missing = [x for x in all_seats if x not in seats]
# my_seat = [x for x in missing if x - 1 not in missing and x + 1 not in missing][0]
my_seat = [s for s in range(min(seats), max(seats) + 1) if s not in seats][0]
return my_seat
if __name__ == '__main__':
with open('input.txt', 'r') as f:
l = [x.strip().upper() for x in f]
print("Part 1:", part1(l))
print("Part 2:", part2(l))
| 2,468 | 978 |
import os
import cv2
import numpy as np
import re
path_regex = re.compile('^.+?/(.*)')
def resize_image(im, factor):
row, col, chan = im.shape
col_re = np.rint(col*factor).astype(int)
row_re = np.rint(row*factor).astype(int)
im = cv2.resize(im, (col_re, row_re)) #resize patch
return im
imdir = '../Marsh_Images_BH/Row1_1_2748to2797'
outdir = './image_resize_BH'
for (dirpath, dirname, files) in os.walk(imdir, topdown='True'):
for name in files:
fullpath = os.path.join(dirpath,name)
print(name)
m = path_regex.findall(dirpath)
dirpath_sub = m[0]
new_dirpath = os.path.join(outdir,dirpath_sub)
if not os.path.isdir(new_dirpath):
os.makedirs(new_dirpath)
file_base = os.path.splitext(name)[0]
im = cv2.imread(fullpath)
im_alt = resize_image(im, 0.2)
outfile = file_base + '_small.jpg'
outpath = os.path.join(new_dirpath, outfile)
cv2.imwrite(outpath,im_alt)
| 997 | 394 |
from distutils.core import setup, Extension
from numpy.distutils.misc_util import get_numpy_include_dirs
setup(ext_modules=[Extension("arc_c_extensions", ["arc_c_extensions.c"],
extra_compile_args = ['-Wall', '-O3'],
include_dirs=get_numpy_include_dirs())])
| 294 | 92 |
import sys
import os
import ttk
import Tkinter as tk
import tkMessageBox
from ttkHyperlinkLabel import HyperlinkLabel
from config import applongname, appversion
import myNotebook as nb
import json
import requests
import zlib
import re
import webbrowser
this = sys.modules[__name__]
this.apiURL = "http://factiongist.herokuapp.com"
FG_VERSION = "0.0.3"
availableFactions = tk.StringVar()
try:
this_fullpath = os.path.realpath(__file__)
this_filepath, this_extension = os.path.splitext(this_fullpath)
config_file = this_filepath + "config.json"
with open(config_file) as f:
data = json.load(f)
availableFactions.set(data)
except:
availableFactions.set("everyone")
if(availableFactions.get() == "everyone"):
msginfo = ['Please update your Reporting Faction.',
'\nYou can report to one or many factions,'
'simply separate each faction with a comma.\n'
'\nFile > Settings > FactionGist']
tkMessageBox.showinfo("Reporting Factions", "\n".join(msginfo))
def plugin_app(parent):
this.parent = parent
this.frame = tk.Frame(parent)
filter_update()
return this.frame
def filter_update():
this.parent.after(300000, filter_update)
response = requests.get(this.apiURL + "/listeningFor")
if(response.status_code == 200):
this.listening = response.content
def plugin_start(plugin_dir):
awake = requests.get(this.apiURL)
check_version()
return 'FactionGist'
def plugin_prefs(parent):
PADX = 10 # formatting
frame = nb.Frame(parent)
frame.columnconfigure(5, weight=1)
HyperlinkLabel(frame, text='FactionGist GitHub', background=nb.Label().cget('background'),
url='https://github.com/OdysseyScorpio/FactionGist', underline=True).grid(columnspan=2, padx=PADX, sticky=tk.W)
nb.Label(frame, text="FactionGist - crazy-things-might-happen-pre-pre-alpha release Version {VER}".format(
VER=FG_VERSION)).grid(columnspan=2, padx=PADX, sticky=tk.W)
nb.Label(frame).grid() # spacer
nb.Button(frame, text="UPGRADE", command=upgrade_callback).grid(row=10, column=0,
columnspan=2, padx=PADX, sticky=tk.W)
nb.lblReportingFactions = tk.Label(frame)
nb.lblReportingFactions.grid(
row=3, column=0, columnspan=2, padx=PADX, sticky=tk.W)
nb.lblReportingFactions.config(text='Factions I am supporting')
nb.Entry1 = tk.Entry(frame, textvariable=availableFactions)
nb.Entry1.grid(row=4, column=0, columnspan=2, padx=PADX, sticky=tk.W+tk.E)
return frame
def check_version():
response = requests.get(this.apiURL + "/version")
version = response.content
if version != FG_VERSION:
upgrade_callback()
def upgrade_callback():
this_fullpath = os.path.realpath(__file__)
this_filepath, this_extension = os.path.splitext(this_fullpath)
corrected_fullpath = this_filepath + ".py"
try:
response = requests.get(this.apiURL + "/download")
if (response.status_code == 200):
with open(corrected_fullpath, "wb") as f:
f.seek(0)
f.write(response.content)
f.truncate()
f.flush()
os.fsync(f.fileno())
this.upgrade_applied = True # Latch on upgrade successful
msginfo = ['Upgrade has completed sucessfully.',
'Please close and restart EDMC']
tkMessageBox.showinfo("Upgrade status", "\n".join(msginfo))
sys.stderr.write("Finished plugin upgrade!\n")
else:
msginfo = ['Upgrade failed. Bad server response',
'Please try again']
tkMessageBox.showinfo("Upgrade status", "\n".join(msginfo))
except:
sys.stderr.writelines(
"Upgrade problem when fetching the remote data: {E}\n".format(E=sys.exc_info()[0]))
msginfo = ['Upgrade encountered a problem.',
'Please try again, and restart if problems persist']
tkMessageBox.showinfo("Upgrade status", "\n".join(msginfo))
def dashboard_entry(cmdr, is_beta, entry):
this.cmdr = cmdr
def journal_entry(cmdr, is_beta, system, station, entry, state):
if entry['event'] in this.listening:
entry['commanderName'] = cmdr
entry['pluginVersion'] = FG_VERSION
entry['currentSystem'] = system
entry['currentStation'] = station
entry['reportingFactions'] = [availableFactions.get()]
transmit_json = json.dumps(entry)
url_jump = this.apiURL + '/events'
headers = {'content-type': 'application/json'}
response = requests.post(
url_jump, data=transmit_json, headers=headers, timeout=7)
def plugin_stop():
sys.stderr.writelines("\nGood bye commander\n")
config = availableFactions.get()
this_fullpath = os.path.realpath(__file__)
this_filepath, this_extension = os.path.splitext(this_fullpath)
config_file = this_filepath + "config.json"
with open(config_file, 'w') as f:
json.dump(config, f)
| 5,133 | 1,640 |
import os
from logging import getLogger
from django.core.exceptions import ValidationError
from django.db import models, transaction
from django.template.defaultfilters import filesizeformat, pluralize
from django.urls import reverse
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from hexa.catalog.models import CatalogQuerySet, Datasource, Entry
from hexa.catalog.sync import DatasourceSyncResult
from hexa.core.models import Base, Permission
from hexa.core.models.cryptography import EncryptedTextField
from hexa.plugins.connector_s3.api import (
S3ApiError,
get_object_metadata,
head_bucket,
list_objects_metadata,
)
from hexa.plugins.connector_s3.region import AWSRegion
logger = getLogger(__name__)
class Credentials(Base):
"""We actually only need one set of credentials. These "principal" credentials will be then used to generate
short-lived credentials with a tailored policy giving access only to the buckets that the user team can
access"""
class Meta:
verbose_name = "S3 Credentials"
verbose_name_plural = "S3 Credentials"
ordering = ("username",)
username = models.CharField(max_length=200)
access_key_id = EncryptedTextField()
secret_access_key = EncryptedTextField()
default_region = models.CharField(
max_length=50, default=AWSRegion.EU_CENTRAL_1, choices=AWSRegion.choices
)
user_arn = models.CharField(max_length=200)
app_role_arn = models.CharField(max_length=200)
@property
def display_name(self):
return self.username
class BucketPermissionMode(models.IntegerChoices):
READ_ONLY = 1, "Read Only"
READ_WRITE = 2, "Read Write"
class BucketQuerySet(CatalogQuerySet):
def filter_by_mode(self, user, mode: BucketPermissionMode = None):
if user.is_active and user.is_superuser:
# if SU -> all buckets are RW; so if mode is provided and mode == RO -> no buckets available
if mode == BucketPermissionMode.READ_ONLY:
return self.none()
else:
return self
if mode is None:
# return all buckets
modes = [BucketPermissionMode.READ_ONLY, BucketPermissionMode.READ_WRITE]
else:
modes = [mode]
return self.filter(
bucketpermission__team__in=[t.pk for t in user.team_set.all()],
bucketpermission__mode__in=modes,
).distinct()
def filter_for_user(self, user):
if user.is_active and user.is_superuser:
return self
return self.filter(
bucketpermission__team__in=[t.pk for t in user.team_set.all()],
).distinct()
class Bucket(Datasource):
def get_permission_set(self):
return self.bucketpermission_set.all()
class Meta:
verbose_name = "S3 Bucket"
ordering = ("name",)
name = models.CharField(max_length=200)
region = models.CharField(
max_length=50, default=AWSRegion.EU_CENTRAL_1, choices=AWSRegion.choices
)
objects = BucketQuerySet.as_manager()
searchable = True # TODO: remove (see comment in datasource_index command)
@property
def principal_credentials(self):
try:
return Credentials.objects.get()
except (Credentials.DoesNotExist, Credentials.MultipleObjectsReturned):
raise ValidationError(
"The S3 connector plugin should be configured with a single Credentials entry"
)
def refresh(self, path):
metadata = get_object_metadata(
principal_credentials=self.principal_credentials,
bucket=self,
object_key=path,
)
try:
s3_object = Object.objects.get(bucket=self, key=path)
except Object.DoesNotExist:
Object.create_from_metadata(self, metadata)
except Object.MultipleObjectsReturned:
logger.warning(
"Bucket.refresh(): incoherent object list for bucket %s", self.id
)
else:
s3_object.update_from_metadata(metadata)
s3_object.save()
def clean(self):
try:
head_bucket(principal_credentials=self.principal_credentials, bucket=self)
except S3ApiError as e:
raise ValidationError(e)
def sync(self):
"""Sync the bucket by querying the S3 API"""
s3_objects = list_objects_metadata(
principal_credentials=self.principal_credentials,
bucket=self,
)
# Lock the bucket
with transaction.atomic():
Bucket.objects.select_for_update().get(pk=self.pk)
# Sync data elements
with transaction.atomic():
created_count = 0
updated_count = 0
identical_count = 0
deleted_count = 0
remote = set()
local = {str(x.key): x for x in self.object_set.all()}
for s3_object in s3_objects:
key = s3_object["Key"]
remote.add(key)
if key in local:
if (
s3_object.get("ETag") == local[key].etag
and s3_object["Type"] == local[key].type
):
# If it has the same key bot not the same ETag: the file was updated on S3
# (Sometime, the ETag contains double quotes -> strip them)
identical_count += 1
else:
updated_count += 1
local[key].update_from_metadata(s3_object)
local[key].save()
else:
Object.create_from_metadata(self, s3_object)
created_count += 1
# cleanup unmatched objects
for key, obj in local.items():
if key not in remote:
deleted_count += 1
obj.delete()
# Flag the datasource as synced
self.last_synced_at = timezone.now()
self.save()
return DatasourceSyncResult(
datasource=self,
created=created_count,
updated=updated_count,
identical=identical_count,
deleted=deleted_count,
)
@property
def content_summary(self):
count = self.object_set.count()
return (
""
if count == 0
else _("%(count)d object%(suffix)s")
% {"count": count, "suffix": pluralize(count)}
)
def populate_index(self, index):
index.last_synced_at = self.last_synced_at
index.content = self.content_summary
index.path = [self.pk.hex]
index.external_id = self.name
index.external_name = self.name
index.external_type = "bucket"
index.search = f"{self.name}"
index.datasource_name = self.name
index.datasource_id = self.id
@property
def display_name(self):
return self.name
def __str__(self):
return self.display_name
def writable_by(self, user):
if not user.is_active:
return False
elif user.is_superuser:
return True
elif (
BucketPermission.objects.filter(
bucket=self,
team_id__in=user.team_set.all().values("id"),
mode=BucketPermissionMode.READ_WRITE,
).count()
> 0
):
return True
else:
return False
def get_absolute_url(self):
return reverse(
"connector_s3:datasource_detail", kwargs={"datasource_id": self.id}
)
class BucketPermission(Permission):
bucket = models.ForeignKey("Bucket", on_delete=models.CASCADE)
mode = models.IntegerField(
choices=BucketPermissionMode.choices, default=BucketPermissionMode.READ_WRITE
)
class Meta:
unique_together = [("bucket", "team")]
def index_object(self):
self.bucket.build_index()
def __str__(self):
return f"Permission for team '{self.team}' on bucket '{self.bucket}'"
class ObjectQuerySet(CatalogQuerySet):
def filter_for_user(self, user):
if user.is_active and user.is_superuser:
return self
return self.filter(bucket__in=Bucket.objects.filter_for_user(user))
class Object(Entry):
def get_permission_set(self):
return self.bucket.bucketpermission_set.all()
class Meta:
verbose_name = "S3 Object"
ordering = ("key",)
unique_together = [("bucket", "key")]
bucket = models.ForeignKey("Bucket", on_delete=models.CASCADE)
key = models.TextField()
parent_key = models.TextField()
size = models.PositiveBigIntegerField()
storage_class = models.CharField(max_length=200) # TODO: choices
type = models.CharField(max_length=200) # TODO: choices
last_modified = models.DateTimeField(null=True, blank=True)
etag = models.CharField(max_length=200, null=True, blank=True)
objects = ObjectQuerySet.as_manager()
searchable = True # TODO: remove (see comment in datasource_index command)
def save(self, *args, **kwargs):
if self.parent_key is None:
self.parent_key = self.compute_parent_key(self.key)
super().save(*args, **kwargs)
def populate_index(self, index):
index.last_synced_at = self.bucket.last_synced_at
index.external_name = self.filename
index.path = [self.bucket.pk.hex, self.pk.hex]
index.context = self.parent_key
index.external_id = self.key
index.external_type = self.type
index.external_subtype = self.extension
index.search = f"{self.filename} {self.key}"
index.datasource_name = self.bucket.name
index.datasource_id = self.bucket.id
def __repr__(self):
return f"<Object s3://{self.bucket.name}/{self.key}>"
@property
def display_name(self):
return self.filename
@property
def filename(self):
if self.key.endswith("/"):
return os.path.basename(self.key[:-1])
return os.path.basename(self.key)
@property
def extension(self):
return os.path.splitext(self.key)[1].lstrip(".")
def full_path(self):
return f"s3://{self.bucket.name}/{self.key}"
@classmethod
def compute_parent_key(cls, key):
if key.endswith("/"): # This is a directory
return os.path.dirname(os.path.dirname(key)) + "/"
else: # This is a file
return os.path.dirname(key) + "/"
@property
def file_size_display(self):
return filesizeformat(self.size) if self.size > 0 else "-"
@property
def type_display(self):
if self.type == "directory":
return _("Directory")
else:
if verbose_file_type := self.verbose_file_type:
return verbose_file_type
else:
return _("File")
@property
def verbose_file_type(self):
file_type = {
"xlsx": "Excel file",
"md": "Markdown document",
"ipynb": "Jupyter Notebook",
"csv": "CSV file",
}.get(self.extension)
if file_type:
return _(file_type)
else:
return None
def update_from_metadata(self, metadata):
self.key = metadata["Key"]
self.parent_key = self.compute_parent_key(metadata["Key"])
self.size = metadata["Size"]
self.storage_class = metadata["StorageClass"]
self.type = metadata["Type"]
self.last_modified = metadata["LastModified"]
self.etag = metadata["ETag"]
@classmethod
def create_from_metadata(cls, bucket, metadata):
return cls.objects.create(
bucket=bucket,
key=metadata["Key"],
parent_key=cls.compute_parent_key(metadata["Key"]),
storage_class=metadata["StorageClass"],
last_modified=metadata["LastModified"],
etag=metadata["ETag"],
type=metadata["Type"],
size=metadata["Size"],
)
def get_absolute_url(self):
return reverse(
"connector_s3:object_detail",
kwargs={"bucket_id": self.bucket.id, "path": self.key},
)
| 12,542 | 3,588 |
# Operadores de identidade
# serve para compara objetos não somente se eles sao iguais , mas sim se estao no mesmo local de memoria(na mesma variavel)
x = ["apple", "banana"]
y = ["apple", "banana"]
z = x
print(x is z)
print(x is y)
print(x == y)
print(x is not z)
print(x is not y)
print(x != y) | 301 | 120 |
WINDOW_SIZE = 8000
KMER_SIZE = 6
UPPER_THRESHOLD = 0.75
LOWER_THRESHOLD = 0.5
TUNE_METRIC = 1000
MINIMUM_GI_SIZE = 10000
| 121 | 82 |
import moeda
n = float(input('Digite o preço: R$'))
print (f'O dobro de {moeda.moeda(n)} é {moeda.dobro(n, True)}')
print (f'A metade de {moeda.moeda(n)} é {moeda.metade(n, True)}')
print (f'O aumento de 10% de {moeda.moeda(n)} é {moeda.aumento(n, 10, True)}')
print (f'O desconto de 13% de {moeda.moeda(n)} é {moeda.desconto(n, 13, True)}')
| 343 | 167 |
import vi.csp
import collections
import operator
BacktrackStatistics = collections.namedtuple(
'BacktrackStatistics', ['calls', 'failures'])
def backtrack_search(network):
statistics = BacktrackStatistics(calls=0, failures=0)
# Ensure arc consistency before making any assumptions:
return backtrack(vi.csp.general_arc_consistency(network), statistics)
def backtrack(network, statistics):
def select_unassigned_variable():
# Use Minimum-Remaining-Values heuristic:
return min(((variable, domain)
for variable, domain in network.domains.items()
if len(domain) > 1),
key=operator.itemgetter(1))[0]
def order_domain_variables():
return network.domains[variable]
statistics = BacktrackStatistics(statistics.calls + 1,
statistics.failures)
if all(len(domain) == 1 for domain in network.domains.values()):
return network, statistics
variable = select_unassigned_variable()
for value in order_domain_variables():
successor = network.copy()
successor.domains[variable] = [value]
successor = vi.csp.general_arc_consistency_rerun(successor, variable)
if all(len(domain) >= 1
for domain in successor.domains.values()):
result, statistics = backtrack(successor, statistics)
if result:
return result, statistics
statistics = BacktrackStatistics(statistics.calls,
statistics.failures + 1)
return None, statistics
| 1,618 | 433 |
#! env python
# coding: utf-8
# 功能:对文字部分使用k-means算法进行聚类
import os
import time
import sys
import cv2
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
from sklearn.externals import joblib
def get_img_as_vector(fn):
im = cv2.imread(fn)
im = im[:, :, 0]
retval, dst = cv2.threshold(im, 128, 1, cv2.THRESH_BINARY_INV)
return dst.reshape(dst.size)
def main():
# 读取训练用数据
print('Start: read data', time.process_time())
fns = os.listdir('ocr')
X = [get_img_as_vector(os.path.join('ocr', fn)) for fn in fns]
print('Samples', len(X), 'Feature', len(X[0]))
# PCA
print('Start: PCA', time.process_time())
pca = PCA(n_components=0.99)
pca.fit(X)
X = pca.transform(X)
print('Samples', len(X), 'Feature', len(X[0]))
sys.stdout.flush()
# 训练
print('Start: train', time.process_time())
n_clusters = 2000 # 聚类中心个数
estimator = KMeans(n_clusters, n_init=1, max_iter=20, verbose=True)
estimator.fit(X)
print('Clusters', estimator.n_clusters, 'Iter', estimator.n_iter_)
print('Start: classify', time.process_time())
fp = open('result11.txt', 'w')
for fn, c in zip(fns, estimator.labels_):
print(fn, c, file=fp)
fp.close()
print('Start: save model', time.process_time())
joblib.dump(estimator, 'k-means11.pkl')
if __name__ == '__main__':
main()
| 1,377 | 592 |
import torch
from torch.utils.data import Dataset
import json
import numpy as np
import os
from PIL import Image, ImageFilter
from torchvision import transforms as T
from models.camera import Camera
from tqdm import tqdm
from .ray_utils import *
class BlenderEfficientShadows(Dataset):
def __init__(self, root_dir, split='train', img_wh=(800, 800), hparams=None):
self.root_dir = root_dir
self.split = split
assert img_wh[0] == img_wh[1], 'image width must equal image height!'
self.img_wh = img_wh
print("Training Image size:", img_wh)
self.define_transforms()
self.white_back = True
# self.white_back = False # Setting it to False (!)
self.hparams = hparams
self.black_and_white = False
if self.hparams is not None and self.hparams.black_and_white_test:
self.black_and_white = True
self.read_meta()
self.hparams.coords_trans = False
print("------------")
print("NOTE: self.hparams.coords_trans is set to {} ".format(self.hparams.coords_trans))
print("------------")
def read_meta(self):
# self.split = 'train'
with open(os.path.join(self.root_dir,
# f"transforms_train.json"), 'r') as f:
f"transforms_{self.split}.json"), 'r') as f:
self.meta = json.load(f)
w, h = self.img_wh
print("Root Directory: ".format(self.root_dir))
# if 'bunny' or 'box' or 'vase' in self.root_dir:
# res = 200 # these imgs have original size of 200
# else:
# res = 800
res = 800
if 'resolution' in self.meta.keys():
res = self.meta['resolution']
print("-------------------------------")
print("RESOLUTION OF THE ORIGINAL IMAGE IS SET TO {}".format(res))
print("-------------------------------")
self.focal = 0.5*res/np.tan(0.5*self.meta['camera_angle_x']) # original focal length
# when W=res
self.focal *= self.img_wh[0]/res # modify focal length to match size self.img_wh
################
self.light_camera_focal = 0.5*res/np.tan(0.5*self.meta['light_camera_angle_x']) # original focal length
################
# if 'bunny' or 'box' or 'vase' in self.root_dir:
# self.light_camera_focal = 0.5*res/np.tan(0.5*self.meta['light_angle_x']) # original focal length
# else:
# self.light_camera_focal = 0.5*res/np.tan(0.5*self.meta['light_camera_angle_x']) # original focal length
# when W=res
self.light_camera_focal *= self.img_wh[0]/res # modify focal length to match size self.img_wh
# bounds, common for all scenes
self.near = 1.0
self.far = 200.0
# probably need to change this
self.light_near = 1.0
self.light_far = 200.0
self.bounds = np.array([self.near, self.far])
# ray directions for all pixels, same for all images (same H, W, focal)
self.directions = \
get_ray_directions(h, w, self.focal) # (h, w, 3)
### Light Camera Matrix
################
pose = np.array(self.meta['light_camera_transform_matrix'])[:3, :4]
################
# if 'bunny' or 'box' or 'vase' in self.root_dir:
# self.meta['light_angle_x'] = 0.5 * self.meta['light_angle_x']
# print("Changing the HFOV of Light")
# pose = np.array(self.meta['frames'][0]['light_transform'])[:3, :4]
# else:
# pose = np.array(self.meta['light_camera_transform_matrix'])[:3, :4]
self.l2w = torch.FloatTensor(pose)
pixels_u = torch.arange(0, w, 1)
pixels_v = torch.arange(0, h, 1)
i, j = np.meshgrid(pixels_v.numpy(), pixels_u.numpy(), indexing='xy')
i = torch.tensor(i) + 0.5 #.unsqueeze(2)
j = torch.tensor(j)+ 0.5 #.unsqueeze(2)
self.light_pixels = torch.stack([i,j, torch.ones_like(i)], axis=-1).view(-1, 3) # (H*W,3)
light_directions = get_ray_directions(h, w, self.light_camera_focal) # (h, w, 3)
rays_o, rays_d = get_rays(light_directions, self.l2w) # both (h*w, 3)
self.light_rays = torch.cat([rays_o, rays_d,
self.light_near*torch.ones_like(rays_o[:, :1]),
self.light_far*torch.ones_like(rays_o[:, :1])],
1) # (h*w, 8)
################
hfov = self.meta['light_camera_angle_x'] * 180./np.pi
################
# if 'bunny' or 'box' or 'vase' in self.root_dir:
# hfov = self.meta['light_angle_x'] * 180./np.pi
# else:
# hfov = self.meta['light_camera_angle_x'] * 180./np.pi
self.light_ppc = Camera(hfov, (h, w))
self.light_ppc.set_pose_using_blender_matrix(self.l2w, self.hparams.coords_trans)
print("LIGHT: c2w: {}\n, camera:{}\n, eye:{}\n".format(self.l2w, self.light_ppc.camera, self.light_ppc.eye_pos))
### Light Camera Matrix
# new_frames = []
# # only do on a single image
# for frame in self.meta['frames']:
# if 'r_137' in frame['file_path']:
# a = [frame]
# new_frames.extend(a * 10)
# break
# self.meta['frames'] = new_frames
if self.split == 'val':
new_frames = []
for frame in self.meta['frames']:
###### load the RGB+SM Image
file_path = frame['file_path'].split('/')
sm_file_path = 'sm_'+ file_path[-1]
sm_path = os.path.join(self.root_dir, f"{sm_file_path}.png")
## Continue if not os.path.exists(shadows)
if not os.path.exists(sm_path):
continue
else:
new_frames.append(frame)
self.meta['frames'] = new_frames
if self.split == 'train': # create buffer of all rays and rgb data
self.image_paths = []
self.poses = []
self.all_rays = []
self.all_rgbs = []
self.all_ppc = []
self.all_pixels = []
for frame in tqdm(self.meta['frames']):
#### change it to load the shadow map
file_path = frame['file_path'].split('/')
file_path = 'sm_'+ file_path[-1]
################
image_path = os.path.join(self.root_dir, f"{file_path}.png")
self.image_paths += [image_path]
## Continue if not os.path.exists(shadows)
if not os.path.exists(image_path):
continue
print("Processing Frame {}".format(image_path))
#####
# real processing begins
pose = np.array(frame['transform_matrix'])[:3, :4]
self.poses += [pose]
c2w = torch.FloatTensor(pose)
hfov = self.meta['camera_angle_x'] * 180./np.pi
ppc = Camera(hfov, (h, w))
ppc.set_pose_using_blender_matrix(c2w, self.hparams.coords_trans)
self.all_ppc.extend([ppc]*h*w)
img = Image.open(image_path)
img = img.resize(self.img_wh, Image.LANCZOS)
if not self.hparams.blur == -1:
img = img.filter(ImageFilter.GaussianBlur(self.hparams.blur))
img = self.transform(img) # (4, h, w)
img = img.view(3, -1).permute(1, 0) # (h*w, 4) RGBA
# Figure out where the rays originated from
pixels_u = torch.arange(0, w, 1)
pixels_v = torch.arange(0, h, 1)
i, j = np.meshgrid(pixels_v.numpy(), pixels_u.numpy(), indexing='xy')
i = torch.tensor(i) + 0.5 #.unsqueeze(2)
j = torch.tensor(j)+ 0.5 #.unsqueeze(2)
pixels = torch.stack([i,j, torch.ones_like(i)], axis=-1).view(-1, 3) # (H*W,3)
rays_o, rays_d = get_rays(self.directions, c2w)
rays = torch.cat([rays_o, rays_d,
self.near*torch.ones_like(rays_o[:, :1]),
self.far*torch.ones_like(rays_o[:, :1])],
1) # (H*W, 8)
print("-------------------------------")
print("frame: {}\n, c2w: {}\n, camera:{}\n, eye:{}\n".format(file_path, c2w, ppc.camera, ppc.eye_pos))
print("-------------------------------")
self.all_rgbs += [img]
self.all_rays += [rays]
self.all_pixels += [pixels]
self.all_rays = torch.cat(self.all_rays, 0) # (len(self.meta['frames])*h*w, 3)
self.all_pixels = torch.cat(self.all_pixels, 0) # (len(self.meta['frames])*h*w, 3)
self.all_rgbs = torch.cat(self.all_rgbs, 0) # (len(self.meta['frames])*h*w, 3)
print("self.all_rgbs.shape, self.all_rays.shape, self.all_pixels.shape, all_ppc.shape",
self.all_rgbs.shape, self.all_rays.shape, self.all_pixels.shape, len(self.all_ppc))
if not (float(self.hparams.white_pix) == -1):
print("-------------------------- rgb max {}, min {}".format(self.all_rgbs.max(), self.all_rgbs.min()))
print("only Training on pixels with shadow map values > 0.")
all_bw = (self.all_rgbs[:,0] + self.all_rgbs[:,1] + self.all_rgbs[:,2])/3.
idx = torch.where(all_bw > float(self.hparams.white_pix))
self.all_rgbs = self.all_rgbs[idx]
self.all_pixels = self.all_pixels[idx]
self.all_rays = self.all_rays[idx]
new_ppc = []
for i in idx[0]:
new_ppc.append(self.all_ppc[i])
self.all_ppc = new_ppc
print("self.all_rgbs.shape, self.all_rays.shape, self.all_pixels.shape, all_ppc.shape",
self.all_rgbs.shape, self.all_rays.shape, self.all_pixels.shape, len(self.all_ppc))
def define_transforms(self):
self.transform = T.ToTensor()
def __len__(self):
if self.split == 'train':
return len(self.all_rays)
elif self.split == 'val':
return 8 # only validate 8 images (to support <=8 gpus)
else:
return len(self.meta['frames'])
def __getitem__(self, idx):
"""
Processes and return rays, rgbs PER image
instead of on a ray by ray basis. Albeit slower,
Implementation of shadow mapping is easier this way.
"""
if self.split == 'train': # use data in the buffers
# pose = self.poses[idx]
# c2w = torch.FloatTensor(pose)
sample = {'rays': self.all_rays[idx], # (8) Ray originating from pixel (i,j)
'pixels': self.all_pixels[idx], # pixel where the ray originated from
'rgbs': self.all_rgbs[idx], # (h*w,3)
# 'ppc': [self.all_ppc[idx].eye_pos, self.all_ppc[idx].camera],
# 'light_ppc': [self.light_ppc.eye_pos, self.light_ppc.camera],
'ppc': {
'eye_pos': self.all_ppc[idx].eye_pos,
'camera': self.all_ppc[idx].camera,
},
'light_ppc': {
'eye_pos': self.light_ppc.eye_pos,
'camera': self.light_ppc.camera,
},
# 'c2w': pose, # (3,4)
# pixel where the light ray originated from
'light_pixels': self.light_pixels, #(h*w, 3)
# light rays
'light_rays': self.light_rays, #(h*w,8)
}
else: # create data for each image separately
frame = self.meta['frames'][idx]
file_path = frame['file_path'].split('/')
file_path = 'sm_'+ file_path[-1]
c2w = torch.FloatTensor(frame['transform_matrix'])[:3, :4]
###########
w, h = self.img_wh
hfov = self.meta['camera_angle_x'] * 180./np.pi
ppc = Camera(hfov, (h, w))
ppc.set_pose_using_blender_matrix(c2w, self.hparams.coords_trans)
eye_poses = [ppc.eye_pos]*h*w
cameras = [ppc.camera]*h*w
###########
img = Image.open(os.path.join(self.root_dir, f"{file_path}.png"))
img = img.resize(self.img_wh, Image.LANCZOS)
if not self.hparams.blur == -1:
img = img.filter(ImageFilter.GaussianBlur(self.hparams.blur))
img = self.transform(img) # (3, H, W)
img = img.view(3, -1).permute(1, 0) # (H*W, 3) RGBA
# img = img[:, :3]*img[:, -1:] + (1-img[:, -1:]) # blend A to RGB
pixels_u = torch.arange(0, w, 1)
pixels_v = torch.arange(0, h, 1)
i, j = np.meshgrid(pixels_v.numpy(), pixels_u.numpy(), indexing='xy')
i = torch.tensor(i) + 0.5 #.unsqueeze(2)
j = torch.tensor(j)+ 0.5 #.unsqueeze(2)
pixels = torch.stack([i,j, torch.ones_like(i)], axis=-1).view(-1, 3) # (H*W,3)
rays_o, rays_d = get_rays(self.directions, c2w)
rays = torch.cat([rays_o, rays_d,
self.near*torch.ones_like(rays_o[:, :1]),
self.far*torch.ones_like(rays_o[:, :1])],
1) # (H*W, 8)
# print("rays.shape", rays.shape)
# valid_mask = (img[-1]>0).flatten() # (H*W) valid color area
sample = {'rays': rays,
'pixels': pixels, # pixel where rays originated from
'rgbs': img,
'ppc': {
'eye_pos': eye_poses,
'camera': cameras,
},
'light_ppc': {
'eye_pos': self.light_ppc.eye_pos,
'camera': self.light_ppc.camera,
},
# pixel where the light ray originated from
'light_pixels': self.light_pixels, #(h*w, 3)
# light rays
'light_rays': self.light_rays, #(h*w,8)
}
return sample | 14,735 | 4,967 |
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
if len(s) == 1:
return s
start = 0
end = len(s)
maxlength = 0
longest = ""
while(start < len(s)):
substring = s[start:end]
if substring == substring[::-1] and len(substring) > maxlength:
maxlength = len(substring)
longest = substring
else:
end -=1
if start == end:
start += 1
end = len(s)
return longest
| 625 | 168 |
#
# PySNMP MIB module RBN-ICR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RBN-ICR-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:44:25 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ValueRangeConstraint, SingleValueConstraint, ConstraintsUnion, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ValueSizeConstraint")
InetPortNumber, InetAddressType, InetAddress = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetPortNumber", "InetAddressType", "InetAddress")
rbnMgmt, = mibBuilder.importSymbols("RBN-SMI", "rbnMgmt")
NotificationGroup, ModuleCompliance, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance", "ObjectGroup")
NotificationType, ObjectIdentity, ModuleIdentity, IpAddress, Unsigned32, Counter32, Counter64, iso, Bits, TimeTicks, MibIdentifier, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "NotificationType", "ObjectIdentity", "ModuleIdentity", "IpAddress", "Unsigned32", "Counter32", "Counter64", "iso", "Bits", "TimeTicks", "MibIdentifier", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Integer32")
DisplayString, TextualConvention, RowStatus = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention", "RowStatus")
rbnIcrMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 2352, 2, 101))
rbnIcrMIB.setRevisions(('2011-01-10 00:00',))
if mibBuilder.loadTexts: rbnIcrMIB.setLastUpdated('201101100000Z')
if mibBuilder.loadTexts: rbnIcrMIB.setOrganization('Ericsson AB.')
rbnIcrNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 2352, 2, 101, 0))
rbnIcrMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 2352, 2, 101, 1))
rbnIcrMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 2352, 2, 101, 2))
rbnIcrTable = MibTable((1, 3, 6, 1, 4, 1, 2352, 2, 101, 1, 1), )
if mibBuilder.loadTexts: rbnIcrTable.setStatus('current')
rbnIcrEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2352, 2, 101, 1, 1, 1), ).setIndexNames((0, "RBN-ICR-MIB", "rbnIcrId"))
if mibBuilder.loadTexts: rbnIcrEntry.setStatus('current')
rbnIcrId = MibTableColumn((1, 3, 6, 1, 4, 1, 2352, 2, 101, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647)))
if mibBuilder.loadTexts: rbnIcrId.setStatus('current')
rbnIcrLocalAddressType = MibTableColumn((1, 3, 6, 1, 4, 1, 2352, 2, 101, 1, 1, 1, 2), InetAddressType().clone('unknown')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: rbnIcrLocalAddressType.setStatus('current')
rbnIcrLocalAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 2352, 2, 101, 1, 1, 1, 3), InetAddress().clone(hexValue="")).setMaxAccess("readcreate")
if mibBuilder.loadTexts: rbnIcrLocalAddress.setStatus('current')
rbnIcrLocalPort = MibTableColumn((1, 3, 6, 1, 4, 1, 2352, 2, 101, 1, 1, 1, 4), InetPortNumber()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: rbnIcrLocalPort.setStatus('current')
rbnIcrPeerAddressType = MibTableColumn((1, 3, 6, 1, 4, 1, 2352, 2, 101, 1, 1, 1, 5), InetAddressType().clone('unknown')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: rbnIcrPeerAddressType.setStatus('current')
rbnIcrPeerAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 2352, 2, 101, 1, 1, 1, 6), InetAddress().clone(hexValue="")).setMaxAccess("readcreate")
if mibBuilder.loadTexts: rbnIcrPeerAddress.setStatus('current')
rbnIcrPeerPort = MibTableColumn((1, 3, 6, 1, 4, 1, 2352, 2, 101, 1, 1, 1, 7), InetPortNumber()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: rbnIcrPeerPort.setStatus('current')
rbnIcrPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 2352, 2, 101, 1, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("low", 1), ("high", 2))).clone('low')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: rbnIcrPriority.setStatus('current')
rbnIcrKeepAliveInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 2352, 2, 101, 1, 1, 1, 9), Integer32().clone(1)).setUnits('seconds').setMaxAccess("readcreate")
if mibBuilder.loadTexts: rbnIcrKeepAliveInterval.setStatus('current')
rbnIcrHoldTime = MibTableColumn((1, 3, 6, 1, 4, 1, 2352, 2, 101, 1, 1, 1, 10), Integer32().clone(10)).setUnits('seconds').setMaxAccess("readcreate")
if mibBuilder.loadTexts: rbnIcrHoldTime.setStatus('current')
rbnIcrState = MibTableColumn((1, 3, 6, 1, 4, 1, 2352, 2, 101, 1, 1, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("initialize", 1), ("active", 2), ("standby", 3), ("pendingStandby", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rbnIcrState.setStatus('current')
rbnIcrAdminStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 2352, 2, 101, 1, 1, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("up", 1), ("down", 2))).clone('down')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: rbnIcrAdminStatus.setStatus('current')
rbnIcrRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 2352, 2, 101, 1, 1, 1, 13), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: rbnIcrRowStatus.setStatus('current')
rbnIcrInconsistencyError = MibScalar((1, 3, 6, 1, 4, 1, 2352, 2, 101, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1))).clone(namedValues=NamedValues(("peerLoss", 1)))).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: rbnIcrInconsistencyError.setStatus('current')
rbnIcrNewActive = NotificationType((1, 3, 6, 1, 4, 1, 2352, 2, 101, 0, 1)).setObjects(("RBN-ICR-MIB", "rbnIcrLocalAddressType"), ("RBN-ICR-MIB", "rbnIcrLocalAddress"), ("RBN-ICR-MIB", "rbnIcrLocalPort"), ("RBN-ICR-MIB", "rbnIcrState"))
if mibBuilder.loadTexts: rbnIcrNewActive.setStatus('current')
rbnIcrNewStandby = NotificationType((1, 3, 6, 1, 4, 1, 2352, 2, 101, 0, 2)).setObjects(("RBN-ICR-MIB", "rbnIcrLocalAddressType"), ("RBN-ICR-MIB", "rbnIcrLocalAddress"), ("RBN-ICR-MIB", "rbnIcrLocalPort"), ("RBN-ICR-MIB", "rbnIcrPeerAddressType"), ("RBN-ICR-MIB", "rbnIcrPeerAddress"), ("RBN-ICR-MIB", "rbnIcrPeerPort"), ("RBN-ICR-MIB", "rbnIcrState"))
if mibBuilder.loadTexts: rbnIcrNewStandby.setStatus('current')
rbnIcrNewPendingStandby = NotificationType((1, 3, 6, 1, 4, 1, 2352, 2, 101, 0, 3)).setObjects(("RBN-ICR-MIB", "rbnIcrLocalAddressType"), ("RBN-ICR-MIB", "rbnIcrLocalAddress"), ("RBN-ICR-MIB", "rbnIcrLocalPort"), ("RBN-ICR-MIB", "rbnIcrPeerAddressType"), ("RBN-ICR-MIB", "rbnIcrPeerAddress"), ("RBN-ICR-MIB", "rbnIcrPeerPort"), ("RBN-ICR-MIB", "rbnIcrState"))
if mibBuilder.loadTexts: rbnIcrNewPendingStandby.setStatus('current')
rbnIcrInconsistency = NotificationType((1, 3, 6, 1, 4, 1, 2352, 2, 101, 0, 4)).setObjects(("RBN-ICR-MIB", "rbnIcrLocalAddressType"), ("RBN-ICR-MIB", "rbnIcrLocalAddress"), ("RBN-ICR-MIB", "rbnIcrLocalPort"), ("RBN-ICR-MIB", "rbnIcrPeerAddressType"), ("RBN-ICR-MIB", "rbnIcrPeerAddress"), ("RBN-ICR-MIB", "rbnIcrPeerPort"), ("RBN-ICR-MIB", "rbnIcrInconsistencyError"))
if mibBuilder.loadTexts: rbnIcrInconsistency.setStatus('current')
rbnIcrMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 2352, 2, 101, 2, 1))
rbnIcrMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 2352, 2, 101, 2, 2))
rbnIcrMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 2352, 2, 101, 2, 1, 1)).setObjects(("RBN-ICR-MIB", "rbnIcrGroup"), ("RBN-ICR-MIB", "rbnIcrNotificationObjectGroup"), ("RBN-ICR-MIB", "rbnIcrNotificationGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
rbnIcrMIBCompliance = rbnIcrMIBCompliance.setStatus('current')
rbnIcrGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 2352, 2, 101, 2, 2, 1)).setObjects(("RBN-ICR-MIB", "rbnIcrLocalAddressType"), ("RBN-ICR-MIB", "rbnIcrLocalAddress"), ("RBN-ICR-MIB", "rbnIcrLocalPort"), ("RBN-ICR-MIB", "rbnIcrPeerAddressType"), ("RBN-ICR-MIB", "rbnIcrPeerAddress"), ("RBN-ICR-MIB", "rbnIcrPeerPort"), ("RBN-ICR-MIB", "rbnIcrPriority"), ("RBN-ICR-MIB", "rbnIcrKeepAliveInterval"), ("RBN-ICR-MIB", "rbnIcrHoldTime"), ("RBN-ICR-MIB", "rbnIcrState"), ("RBN-ICR-MIB", "rbnIcrAdminStatus"), ("RBN-ICR-MIB", "rbnIcrRowStatus"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
rbnIcrGroup = rbnIcrGroup.setStatus('current')
rbnIcrNotificationObjectGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 2352, 2, 101, 2, 2, 2)).setObjects(("RBN-ICR-MIB", "rbnIcrInconsistencyError"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
rbnIcrNotificationObjectGroup = rbnIcrNotificationObjectGroup.setStatus('current')
rbnIcrNotificationGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 2352, 2, 101, 2, 2, 3)).setObjects(("RBN-ICR-MIB", "rbnIcrNewActive"), ("RBN-ICR-MIB", "rbnIcrNewStandby"), ("RBN-ICR-MIB", "rbnIcrNewPendingStandby"), ("RBN-ICR-MIB", "rbnIcrInconsistency"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
rbnIcrNotificationGroup = rbnIcrNotificationGroup.setStatus('current')
mibBuilder.exportSymbols("RBN-ICR-MIB", rbnIcrGroup=rbnIcrGroup, rbnIcrPeerAddress=rbnIcrPeerAddress, rbnIcrPeerAddressType=rbnIcrPeerAddressType, rbnIcrNotifications=rbnIcrNotifications, rbnIcrNewActive=rbnIcrNewActive, rbnIcrMIBCompliance=rbnIcrMIBCompliance, rbnIcrNotificationObjectGroup=rbnIcrNotificationObjectGroup, rbnIcrMIB=rbnIcrMIB, PYSNMP_MODULE_ID=rbnIcrMIB, rbnIcrTable=rbnIcrTable, rbnIcrMIBConformance=rbnIcrMIBConformance, rbnIcrLocalAddressType=rbnIcrLocalAddressType, rbnIcrPriority=rbnIcrPriority, rbnIcrEntry=rbnIcrEntry, rbnIcrState=rbnIcrState, rbnIcrKeepAliveInterval=rbnIcrKeepAliveInterval, rbnIcrAdminStatus=rbnIcrAdminStatus, rbnIcrLocalPort=rbnIcrLocalPort, rbnIcrHoldTime=rbnIcrHoldTime, rbnIcrRowStatus=rbnIcrRowStatus, rbnIcrNotificationGroup=rbnIcrNotificationGroup, rbnIcrPeerPort=rbnIcrPeerPort, rbnIcrMIBObjects=rbnIcrMIBObjects, rbnIcrNewPendingStandby=rbnIcrNewPendingStandby, rbnIcrLocalAddress=rbnIcrLocalAddress, rbnIcrNewStandby=rbnIcrNewStandby, rbnIcrMIBGroups=rbnIcrMIBGroups, rbnIcrId=rbnIcrId, rbnIcrInconsistency=rbnIcrInconsistency, rbnIcrMIBCompliances=rbnIcrMIBCompliances, rbnIcrInconsistencyError=rbnIcrInconsistencyError)
| 10,410 | 4,829 |
#!/usr/bin/env python
# coding: utf-8
# In[93]:
import os
from shutil import copyfile
import json
print("cwd = ", os.getcwd())
current_folder = os.getcwd()
#extracted_train_data = os.path.join(current_folder, "extracted_train_data")
extracted_train_data = "/dataset/training/"
#annotations_dir = '/data/annotations'
copied_train_data = "/data/dataset/training/"
# In[100]:
data_location = "/dataset/training/"
files_list = []
neural_net_list = []
linear_mappings = []
for subdir, dirs, files in os.walk(data_location):
for file in set(files):
if file.endswith('.pnm'):
current_file = os.path.join(subdir, file)
files_list.append(current_file)
print(len(files_list))
prev_file_number = 0
prev_file_dir_name = ""
prev_neural_net = ""
counter = 0
linear_list = []
########################################## EDIT #####################################################################
for file in sorted(files_list):
file_name_split = file.split('/')
file_number = int(file_name_split[-1].split(".pnm")[0])
dir_name = file_name_split[-3] + file_name_split[-2]
counter += file_number - prev_file_number
if(prev_file_dir_name != dir_name):
counter = 0
neural_net_list.append(file)
prev_neural_net = file
linear_list = []
else:
if(counter >= 5):
neural_net_list.append(file)
linear_mappings.append({ "linear_list": linear_list, "predecessor": prev_neural_net, "successor": file })
counter = 0
prev_neural_net = file
linear_list = []
else:
#linear_mappings[file] = "linear"
linear_list.append(file)
# print("making linear", file)
prev_file_number = file_number
prev_file_dir_name = dir_name
with open('linear_mappings.json', 'w') as outfile:
json.dump(linear_mappings, outfile)
# for file in file_body:
# if (file_body[file] == "neuralnet"):
# print(file)
# for file in file_body:
# if (file_body[file] == "linear"):
# print(file)
# In[97]:
#neural_net_list[] - list of images to be sent to neural network
import os
import glob
from mmdet.apis import init_detector, inference_detector, show_result, write_result
import time
import datetime
config_file = '/root/ws/mmdetection-icevision/configs/dcn/cascade_rcnn_dconv_c3-c5_r50_fpn_1x_all_classes.py'
#model = init_detector(config_file, checkpoint_file, device='cuda:0')
#epch_count = 1
#for epochs in glob.glob(os.path.join('/data_tmp/icevisionmodels/cascade_rcnn_dconv_c3-c5_r50_fpn_1x_all_classes/', '*.pth')):
checkpoint_file = '/data/trained_models/cascade_rcnn_dconv_c3-c5_r50_fpn_1x_135_classes/epoch_15.pth'
#checkpoint_file = epochs
# build the model from a config file and a checkpoint file
model = init_detector(config_file, checkpoint_file, device='cuda:0')
TEST_RESULT_PATH = "/data/test_results/"
img_count = 0
#print(img_count)
FINAL_ONLINE_TEST_PATH = "/data/train_subset/"
#FINAL_ONLINE_TEST_PATH = '/data/test_results/2018-02-13_1418/left/'
#for TEST_SET_PATH in (FINAL_ONLINE_TEST_PATH + "2018-02-16_1515_left/", FINAL_ONLINE_TEST_PATH + "2018-03-16_1424_left/", FINAL_ONLINE_TEST_PATH + "2018-03-23_1352_right/"):
#print(TEST_SET_PATH)
#imgs = glob.glob('/dataset/training/**/*.pnm', recursive=True)
for img in neural_net_list:
ts = time.time()
st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
print ("time =", st)
#imgs = ['test.jpg', '000000.jpg']
#print(img) # /dataset/training/2018-02-13_1418/left/020963.pnm --> required format 2018-02-13_1418_left/000033
name = img.split("/") # ['', 'home', 'luminosity', 'ws', 'icevision', 'data', 'final', '2018-02-16_1515_left', '001887.jpg']
#print(name)
base = name[-1].split(".")[0] # ['001887', 'jpg']
#print(base)
name = name[-3] + "_" + name[-2]
tmp = name
name = name + "/" + base
#print(name)
######## Remove
#name_tmp = base.split("_")
#name = name_tmp[0] + "_" + name_tmp[1] + "_" + name_tmp[2] + "/" + name_tmp[-1]
#name = "annotation_train_subset/" + base
#base_list = base.split("_")
#name = base_list[0] + "_" + base_list[1] + "_" + base_list[2] + "/" + base_list[3]
##########Remove
result = inference_detector(model, img)
#write_result(name, result, model.CLASSES, out_file=os.path.join(TEST_RESULT_PATH, 'my_test_multi_scale_epch_{}.tsv'.format(epch_count))) # use name instead name1 for hackthon submission
#show_result(img, result, model.CLASSES, out_file= TEST_RESULT_PATH + 'bboxs/' + tmp + ".pnm")
write_result(name, result, model.CLASSES, out_file=os.path.join(TEST_RESULT_PATH, 'my_test_epch_15_interpolation.tsv')) # use name instead name1 for hackthon submission
img_count+=1
#print(img_count)
print("num = %d name = %s" %(img_count,name))
# In[103]:
import os
import glob
import csv
from shutil import copyfile
def linear_interpolation(pred, succ, lin_images, input_tsv, step, out_tsv):
lin_images.sort()
succ_base_name = os.path.basename(succ).split(".")[0]
pred_base_name = os.path.basename(pred).split(".")[0]
#copyfile(input_tsv, out_tsv)
tsv_file = csv.reader(open(input_tsv, "r"), delimiter="\t")
prd_classes = []
suc_classes = []
prd_keys = set()
suc_keys = set()
for row in tsv_file:
# print("row = ", row)
# print('ped_keys = ', prd_keys)
# print('suc_keys = ', suc_keys)
# frame xtl ytl xbr ybr class temporary data
# 2018-02-13_1418_left/020963 679 866 754 941 3.27
prd_record = {} #defaultdict(list)
suc_record = {} #defaultdict(list)
#print("row[0] = ", row[0])
x = os.path.join(os.path.basename(os.path.dirname(pred)),os.path.basename(pred))
y = os.path.basename(os.path.dirname(os.path.dirname(pred)))
dict_key = y + "_" + x
x2 = os.path.join(os.path.basename(os.path.dirname(succ)),os.path.basename(succ))
y2 = os.path.basename(os.path.dirname(os.path.dirname(succ)))
dict_key2 = y2 + "_" + x2
# print('y = ', y)
# print("x = ", x)
# print("dict_key = ", dict_key.split('.')[0])
if row[0] == dict_key.split('.')[0]:
if row[5] not in prd_keys:
print("pred check cleared")
prd_record["class"] = row[5]
prd_record["xtl"] = row[1]
prd_record["ytl"] = row[2]
prd_record["xbr"] = row[3]
prd_record["ybr"] = row[4]
print("prd_record['ybr'] = ", prd_record["ybr"])
prd_keys.add(row[5])
# #prd_record[row[5]].append(row[1]) #xtl
# prd_record[row[5]].append(row[2]) #ytl
# prd_record[row[5]].append(row[3]) #xbr
# prd_record[row[5]].append(row[4]) #ybr
prd_classes.append(prd_record)
else:
for prd_class in prd_classes:
if prd_class["class"] == row[5]:
del prd_class
print("del prd_class")
elif row[0] == dict_key2.split('.')[0]:
print("Succ check cleared")
if row[5] not in suc_keys:
suc_record["class"] = row[5]
suc_record["xtl"] = row[1]
suc_record["ytl"] = row[2]
suc_record["xbr"] = row[3]
suc_record["ybr"] = row[4]
suc_keys.add(row[5])
# suc_record[row[5]].append(row[1])
# suc_record[row[5]].append(row[2])
# suc_record[row[5]].append(row[3])
# suc_record[row[5]].append(row[4])
suc_classes.append(suc_record)
else:
for suc_class in suc_classes:
if suc_class["class"] == row[5]:
del suc_class
print("del prd_class")
#print("prd_keys = ", prd_keys)
common_classes = prd_keys.intersection(suc_keys)
print(common_classes)
for common_class in common_classes:
for prd_class in prd_classes:
if prd_class["class"] == common_class:
for suc_class in suc_classes:
if suc_class["class"] == common_class:
xtl_gr = (int(prd_class["xtl"]) - int(suc_class["xtl"])) / step
ytl_gr = (int(prd_class["ytl"]) - int(suc_class["ytl"])) / step
xbr_gr = (int(prd_class["xbr"]) - int(suc_class["xbr"])) / step
ybr_gr = (int(prd_class["ybr"]) - int(suc_class["ybr"])) / step
print(xtl_gr, ytl_gr, xbr_gr, ybr_gr)
for f in lin_images:
curr_base = os.path.basename(f).split(".")[0]
# print("curr_base = ", curr_base)
# print("pred_base_name = ", pred_base_name)
# print("f = ", f)
factor = int(curr_base) - int(pred_base_name)
curr_xtl = int(prd_class["xtl"]) + (factor * xtl_gr)
curr_ytl = int(prd_class["ytl"]) + (factor * ytl_gr)
curr_xbr = int(prd_class["xbr"]) + (factor * xbr_gr)
curr_ybr = int(prd_class["ybr"]) + (factor * ybr_gr)
temp = ''
with open(out_tsv, mode = 'a') as result_file:
result_file_writer = csv.writer(result_file, delimiter = '\t')
result_file_writer.writerow([f, str(curr_xtl), str(curr_ytl), str(curr_xbr), str(curr_ybr), prd_class["class"], temp, temp])
# In[105]:
#load the linear mappings.json
import csv
linear_mappings = "/root/ws/mmdetection-icevision/data-preprocess/linear_mappings.json"
input_tsv = os.path.join(TEST_RESULT_PATH, 'my_test_epch_15_interpolation_copy.tsv')
out_tsv = os.path.join(TEST_RESULT_PATH, 'my_test_epch_15_interpolation_copy.tsv')
interpolation_mappings = []
with open(linear_mappings, 'r') as f:
interpolation_mappings = json.load(f)
for i in interpolation_mappings:
pred = i["predecessor"]
succ = i['successor']
interpol_list = i['linear_list']
step = 5
linear_interpolation(pred, succ, interpol_list, input_tsv, step, out_tsv)
# if i["predecessor"] == neural_net_list[100]:
# break
# In[70]:
# trial code
# extracted_train_data = "/home/sgj/temp/test_data/2018-03-16_1324"
# for subdir, dirs, files in os.walk(extracted_train_data):
# print("subdir = ", subdir)
# for file in files:
# if file.endswith('.jpg'):
# current_file = os.path.join(subdir, file)
# #folder_name = os.path.basename(os.path.dirname(current_file))
# #expected_name = folder_name + '_' + os.path.basename(current_file)
# y = file.split("_")
# expected_name = y[0] + "_" + y[1] + "_left_jpgs_" + y[2]
# absolute_expected_name = os.path.join(os.path.dirname(current_file),expected_name)
# os.rename(current_file, absolute_expected_name)
# In[37]:
extracted_train_data = "/home/sgj/temp/train_data/2018-02-13_1418_left_jpgs"
for subdir, dirs, files in os.walk(extracted_train_data):
print("subdir = ", subdir)
for file in files:
if file.endswith('.jpg'):
current_file = os.path.join(subdir, file)
folder_name = os.path.basename(os.path.dirname(current_file))
expected_name = folder_name + '_' + os.path.basename(current_file)
absolute_expected_name = os.path.join(os.path.dirname(current_file),expected_name)
os.rename(current_file, absolute_expected_name)
# In[25]:
# move out un-annotated images -
# ARGS -
# Annotations data tsv
# Extracted images folder
# Destination folder for annotated_data
import os
annotation_data_tsv_folder = "/home/sgj/nvme/ice-vision/annotations/test/all_validation_annotations"
extracted_images_folder = "/home/sgj/temp/test_data/all_validation_images"
#dest_annotated_imgs = "/home/sgj/nvme/ice-vision/annotated_data/val"
dest_annotated_imgs = "/home/sgj/temp/ice-vision/annotated_data/val"
os.makedirs(dest_annotated_imgs)
img_count = 0
for root, dirs, files in os.walk(annotation_data_tsv_folder):
for name in files:
if name.endswith('.tsv'):
prefix = name.split(".")[0]
image_name = prefix + ".jpg"
expected_img_path = os.path.join(extracted_images_folder, image_name)
new_image_path = os.path.join(dest_annotated_imgs, image_name)
if os.path.exists(expected_img_path):
img_count = img_count + 1
os.rename(expected_img_path, new_image_path)
else:
print("image missing-----------------------")
print("total images = ", img_count)
# In[18]:
temp = "2018-02-13_1418_left_jpgs_014810.tsv"
temp.split(".")[0]
# In[3]:
for subdir, dirs, files in os.walk(copied_train_data):
print("subdir = ", subdir)
for file in files:
if file.endswith('.pnm'):
current_file = os.path.join(subdir, file)
print('current file = ', current_file)
cam_dir = current_file.split('/')[-2]
#print("cam dir = ", cam_dir)
date_dir = current_file.split('/')[-3]
#print("date_dir = ", date_dir)
expected_folder = '/data/train_subset/'
expected_file_name = date_dir + "_" + cam_dir + "_" + os.path.basename(current_file)
expected_file_path = os.path.join(expected_folder, expected_file_name)
#copyfile(current_file, dst_file_path)
os.rename(current_file, expected_file_path)
print("expected_file_path = ", expected_file_path)
# In[4]:
# In[ ]:
| 14,325 | 5,116 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'second_childwin.ui'
#
# Created by: PyQt5 UI code generator 5.15.0
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form_2(object):
def setupUi(self, Form_2):
Form_2.setObjectName("Form_2")
Form_2.resize(982, 618)
self.graphicsView = QtWidgets.QGraphicsView(Form_2)
self.graphicsView.setGeometry(QtCore.QRect(420, 10, 560, 606))
self.graphicsView.setObjectName("graphicsView")
self.pushButton = QtWidgets.QPushButton(Form_2)
self.pushButton.setGeometry(QtCore.QRect(20, 60, 301, 40))
font = QtGui.QFont()
font.setPointSize(20)
self.pushButton.setFont(font)
self.pushButton.setObjectName("pushButton")
self.lineEdit = QtWidgets.QLineEdit(Form_2)
self.lineEdit.setGeometry(QtCore.QRect(20, 110, 391, 41))
font = QtGui.QFont()
font.setPointSize(16)
self.lineEdit.setFont(font)
self.lineEdit.setObjectName("lineEdit")
self.pushButton_2 = QtWidgets.QPushButton(Form_2)
self.pushButton_2.setGeometry(QtCore.QRect(20, 160, 91, 41))
font = QtGui.QFont()
font.setPointSize(20)
self.pushButton_2.setFont(font)
self.pushButton_2.setObjectName("pushButton_2")
self.label = QtWidgets.QLabel(Form_2)
self.label.setGeometry(QtCore.QRect(30, 220, 101, 41))
font = QtGui.QFont()
font.setPointSize(20)
self.label.setFont(font)
self.label.setObjectName("label")
self.lineEdit_2 = QtWidgets.QLineEdit(Form_2)
self.lineEdit_2.setGeometry(QtCore.QRect(80, 280, 130, 40))
font = QtGui.QFont()
font.setPointSize(16)
self.lineEdit_2.setFont(font)
self.lineEdit_2.setText("")
self.lineEdit_2.setReadOnly(True)
self.lineEdit_2.setObjectName("lineEdit_2")
self.lineEdit_4 = QtWidgets.QLineEdit(Form_2)
self.lineEdit_4.setGeometry(QtCore.QRect(80, 400, 130, 40))
font = QtGui.QFont()
font.setPointSize(16)
self.lineEdit_4.setFont(font)
self.lineEdit_4.setReadOnly(True)
self.lineEdit_4.setObjectName("lineEdit_4")
self.label_2 = QtWidgets.QLabel(Form_2)
self.label_2.setGeometry(QtCore.QRect(40, 280, 40, 30))
font = QtGui.QFont()
font.setFamily("Times New Roman")
font.setPointSize(20)
self.label_2.setFont(font)
self.label_2.setObjectName("label_2")
self.label_3 = QtWidgets.QLabel(Form_2)
self.label_3.setGeometry(QtCore.QRect(40, 400, 40, 30))
font = QtGui.QFont()
font.setFamily("Times New Roman")
font.setPointSize(20)
self.label_3.setFont(font)
self.label_3.setObjectName("label_3")
self.label_4 = QtWidgets.QLabel(Form_2)
self.label_4.setGeometry(QtCore.QRect(40, 340, 40, 30))
font = QtGui.QFont()
font.setFamily("Times New Roman")
font.setPointSize(20)
self.label_4.setFont(font)
self.label_4.setObjectName("label_4")
self.pushButton_3 = QtWidgets.QPushButton(Form_2)
self.pushButton_3.setGeometry(QtCore.QRect(30, 520, 91, 41))
font = QtGui.QFont()
font.setPointSize(20)
self.pushButton_3.setFont(font)
self.pushButton_3.setObjectName("pushButton_3")
self.lineEdit_3 = QtWidgets.QLineEdit(Form_2)
self.lineEdit_3.setGeometry(QtCore.QRect(80, 340, 130, 40))
font = QtGui.QFont()
font.setPointSize(16)
self.lineEdit_3.setFont(font)
self.lineEdit_3.setText("")
self.lineEdit_3.setReadOnly(True)
self.lineEdit_3.setObjectName("lineEdit_3")
self.retranslateUi(Form_2)
self.pushButton_3.clicked.connect(Form_2.close)
QtCore.QMetaObject.connectSlotsByName(Form_2)
def retranslateUi(self, Form_2):
_translate = QtCore.QCoreApplication.translate
Form_2.setWindowTitle(_translate("Form_2", "色度测量仿真"))
self.pushButton.setText(_translate("Form_2", "选择透射谱/反射谱文件"))
self.pushButton_2.setText(_translate("Form_2", "运行"))
self.label.setText(_translate("Form_2", "色坐标:"))
self.label_2.setText(_translate("Form_2", "x:"))
self.label_3.setText(_translate("Form_2", "z:"))
self.label_4.setText(_translate("Form_2", "y:"))
self.pushButton_3.setText(_translate("Form_2", "返回"))
| 4,721 | 1,816 |
import os
import matplotlib.pyplot as plt
import numpy as np
from models import models_util
DIFFICULTY_LABEL = "Star Difficulty"
BPM_LABEL = "BPM"
LENGTH_LABEL = "Length"
CS_LABEL = "Circle Size"
DRAIN_LABEL = "HP Drain"
ACCURACY_LABEL = "Accuracy"
AR_LABEL = "Approach Rate"
SAVE_FOLDER = "visualization/"
def print_property_values(labels, values):
for idx, value in enumerate(values):
print(f"{labels[idx]}: {value}")
print()
# Data rows are in the format of [difficulty_rating],[bpm],[total_length],[cs],[drain],[accuracy],[ar].
labels = [DIFFICULTY_LABEL, BPM_LABEL, LENGTH_LABEL, CS_LABEL, DRAIN_LABEL, ACCURACY_LABEL, AR_LABEL]
filename_labels = []
for label in labels:
filename_labels.append(label.lower().replace(" ", "_"))
# Keep track of each property in separate rows.
points = np.transpose(models_util.load_metadata_dataset())
mins = points.min(axis=-1)
maxes = points.max(axis=-1)
means = np.mean(points, axis=-1)
print("Minimum values:")
print_property_values(labels, mins)
print("Maximum values:")
print_property_values(labels, maxes)
print("Mean values:")
print_property_values(labels, means)
# Plot graphs for each input output feature pair.
for i in range(3):
for j in range(3, 7):
plt.hexbin(points[i], points[j], gridsize=50, cmap="inferno")
plt.axis([mins[i], maxes[i], mins[j], maxes[j]])
x_label = labels[i]
y_label = labels[j]
plt.title(f"{y_label} vs {x_label}")
plt.xlabel(x_label)
plt.ylabel(y_label)
x_file_label = filename_labels[i]
y_file_label = filename_labels[j]
image_name = os.path.join(SAVE_FOLDER, f"{y_file_label}_vs_{x_file_label}.png")
print(f"Saving graph to {image_name}.")
plt.savefig(image_name) | 1,683 | 681 |
import unittest
from unittest.mock import *
from src.zad02.main import Subscriber
class SubscriberTest(unittest.TestCase):
def setUp(self):
self.subscriber = Subscriber()
def test_add_client(self):
self.subscriber.add_client = MagicMock(return_value=["Andrzej"])
self.assertEqual(["Andrzej"], self.subscriber.add_client("Andrzej"))
def test_remove_client(self):
self.subscriber.remove_client = MagicMock(return_value=[])
self.assertEqual([], self.subscriber.remove_client("Andrzej"))
def test_send_message_to_client(self):
self.subscriber.clients = ["Andrzej"]
self.subscriber.send_message = MagicMock(side_effect=lambda client, message: message)
self.assertEqual("Hello Andrzej!", self.subscriber.send_message_to_client("Andrzej", "Hello Andrzej!"))
def test_add_client_type_error(self):
self.subscriber.add_client = MagicMock(side_effect=TypeError("Client is not a string!"))
with self.assertRaisesRegex(TypeError, "Client is not a string!"):
self.subscriber.add_client(1)
def test_add_client_value_error(self):
self.subscriber.add_client = MagicMock(side_effect=ValueError("Client already exists!"))
with self.assertRaisesRegex(ValueError, "Client already exists!"):
self.subscriber.add_client("Andrzej")
def test_remove_client_type_error(self):
self.subscriber.remove_client = MagicMock(side_effect=TypeError("Client is not a string!"))
with self.assertRaisesRegex(TypeError, "Client is not a string!"):
self.subscriber.remove_client(1)
def test_send_message_to_client_type_error(self):
self.subscriber.send_message_to_client = MagicMock(side_effect=TypeError("Client or message is not a string!"))
with self.assertRaisesRegex(TypeError, "Client or message is not a string!"):
self.subscriber.send_message_to_client("Andrzej", [])
def test_send_message_to_client_value_error(self):
self.subscriber.send_message_to_client = MagicMock(side_effect=ValueError("Client doesn't exist!"))
with self.assertRaisesRegex(ValueError, "Client doesn't exist!"):
self.subscriber.send_message_to_client("Andrzej", "Hello Andrzej!")
def tearDown(self):
self.subscriber = None
| 2,327 | 743 |
# import some common libraries
# import some common detectron2 utilities
from detectron2.config import get_cfg
from detectron2.data import (
build_detection_test_loader,
build_detection_train_loader,
)
from detectron2.engine import default_argument_parser, default_setup, launch, DefaultTrainer
# import ADE related package
from dataset.ade import register_all_ade
from dataset.my_mapper import MyDatasetMapper
from transforms.my_resize import MyResize
from modeling.backbone.my_build import register_my_backbone
from modeling.roi_heads.roi_cls import register_roi_cls
from additional_cfg import set_additional_cfg
class Trainer(DefaultTrainer):
@classmethod
def build_train_loader(cls, cfg):
"""
Returns:
iterable
It now calls :func:`detectron2.data.build_detection_train_loader`.
Overwrite it if you'd like a different data loader.
"""
return build_detection_train_loader(cfg, mapper=MyDatasetMapper(cfg, is_train=True, augmentations=[
MyResize(cfg.INPUT.RESIZE_SHORT, cfg.INPUT.RESIZE_LONG)]))
def setup(args):
"""
Create configs and perform basic setups.
"""
cfg = get_cfg()
cfg.merge_from_file(args.config_file)
cfg.merge_from_list(args.opts)
cfg = set_additional_cfg(cfg)
cfg.freeze()
default_setup(
cfg, args
) # if you don't like any of the default setup, write your own setup code
return cfg
def register_all(cfg):
register_all_ade(cfg.DATASETS.ADE_ROOT)
register_my_backbone()
register_roi_cls()
def main(args):
cfg = setup(args)
register_all(cfg)
trainer = Trainer(cfg)
trainer.resume_or_load(resume=args.resume)
return trainer.train()
if __name__ == "__main__":
args = default_argument_parser().parse_args()
print("Command Line Args:", args)
launch(
main,
args.num_gpus,
num_machines=args.num_machines,
machine_rank=args.machine_rank,
dist_url=args.dist_url,
args=(args,),
)
| 2,077 | 680 |
# OpenWeatherMap API Key
weather_api_key = "3796d9507516315ec2ebdc39473cc6ea"
# Google API Key
g_key = "AIzaSyDQ3DTH86ntlGML7QCVhKWSocZX8Cb4yBA"
| 146 | 89 |
PERMISSION_DENIED_MESSAGE: str = "***PERMISSION DENIED!*** \n" \
"You are not permitted to use this command. \n" \
"Please contact to your server master. \n."
ERROR_OCCURRED_MESSAGE: str = "***ERROR OCCURRED!*** \n" \
"Error has occurred while executing gcp request command. \n" \
"Please contact to your server master or the software developer. \n" \
"Error: {} \n"
OPERATION_COMPLETED_MESSAGE: str = "***Operation Completed! ***\n" \
"Operation: {} has successfully completed. \n" \
"This may take more 2~3 minutes that the Minecraft Server starts (stops)."
INSTANCE_IS_ALREADY_IN_REQUESTED_STATUS: str = "***Already in status of {}.*** \n" \
"The instance is already in the status. \n" \
"No operation has done."
PRE_STOP_OPERATION_PROCESSING: str = "Processing pre-stop operation... \n" \
"Trying to shutdown Minecraft server from the console channel. \n" \
"Whichever the operation is completed or not, " \
"the server will shutdown in 5 minutes forcibly."
REQUEST_RECEIVED: str = "Operation: {} has requested. \n" \
"Please wait until the operation is done. \n"
START_REQUEST_RECEIVED_MESSAGE = "Trying to start the gcp server. \n" \
"It takes 3 sec at least to complete the operation. \n" \
"The minecraft server will start as soon as gcp server started. \n" \
"PLEASE WAIT UNTIL YOU RECEIVE MESSAGE 'SERVER HAS STARTED!' " \
"BEFORE YOU JOIN THE MINECRAFT SERVER."
STOP_REQUEST_RECEIVED_MESSAGE = "Trying to stop the gcp server. \n" \
"It takes 5 minutes at least to complete the operation. \n" \
"We will issue `stop` command in console channel. \n" \
"And then, we will wait for 5 minutes for the Minecraft server stops." \
"After all the process is done, we will shutdown GCP instance finally."
| 2,411 | 622 |
from pydicom.sr import _snomed_dict
import os
import re
import pydicom.sr._snomed_dict
folder = "E:\\work\\QIICR\\dcmqi"
Out_Folder = "E:\\work\\QIICR\\renamed_dcmqi"
def recursive_file_find(address, regexp):
filelist = os.listdir(address)
approvedlist=[]
for filename in filelist:
fullpath = os.path.join(address, filename)
if os.path.isdir(fullpath):
approvedlist.extend(recursive_file_find(fullpath, regexp))
elif re.match(regexp, fullpath) is not None:
approvedlist.append(fullpath)
return approvedlist
def GetFileString(filename):
File_object = open(filename, "r")
try:
Content = File_object.read()
except:
print("Couldn't read the file")
Content = ""
File_object.close()
return Content
def WriteTextInFile(filename, txt):
folder = os.path.dirname(filename)
if not os.path.exists(folder):
os.makedirs(folder)
File_object = open(filename, "w")
File_object.write(txt)
File_object.close()
def FindRegex(regexp, text, extend=[0, 0], printout=False):
found_iters = re.finditer(regexp, text)
founds = list(found_iters)
ii = []
for mmatch in founds:
yy = text[mmatch.start() - extend[0]:mmatch.end() + extend[1]]
counter = "[%04d ]" % len(ii)
if (printout):
print(counter + yy)
ii.append(yy)
return ii
def ReplaceQuotedText(find_text, rep_text, text):
pattern = "(\"\s*" + find_text + "\s*\")|('\s*" + find_text + "\s*')"
replacement = "\"" + rep_text + "\"";
new_text = re.sub(pattern, replacement, text)
View = ShowReplaceMent(pattern, replacement, text)
return [new_text, View]
def FindAndReplace(find_text, rep_text, text):
newtext = re.sub(find_text, rep_text, text)
x = ShowReplaceMent(find_text, rep_text, text)
return [newtext, x]
def ShowReplaceMent(find_text, rep_text, text):
output = []
text_seq = FindRegex("\\n.*(" + find_text + ").*\\n", text, [-1, -1])
for line_txt in text_seq:
found_iters = re.finditer(find_text, line_txt)
founds = list(found_iters)
if len(founds) > 0:
mmatch = founds[0]
yy = line_txt[:mmatch.start()] + \
"{ [" + line_txt[mmatch.start():mmatch.end()] + "]-->[" + rep_text + "] }" + \
line_txt[mmatch.end():]
output.append(yy)
return output
dict = _snomed_dict.mapping["SCT"]
details = []
# recursive_file_find(folder, all_files, "(.*\\.cpp$)|(.*\\.h$)|(.*\\.json$)")
all_files = recursive_file_find(folder, "(?!.*\.git.*)")
for f, jj in zip(all_files, range(1, len(all_files))):
f_content = (GetFileString(f))
if len(f_content) == 0:
continue
[f_content, x] = ReplaceQuotedText("SCT", "SCT", f_content)
details = x
[f_content, x] = FindAndReplace(",\s*SRT\s*,", ",SCT,", f_content)
details.extend(x)
[f_content, x] = FindAndReplace("SCT", " SCT ", f_content)
details.extend(x)
[f_content, x] = FindAndReplace("_SCT_", "_SCT_", f_content)
details.extend(x)
[f_content, x] = FindAndReplace("sct.h", "sct.h", f_content)
details.extend(x)
for srt_code, sct_code in dict.items():
# f_content = ReplaceQuotedText(srt_code, sct_code, f_content)
[f_content, x] = FindAndReplace(srt_code, sct_code, f_content)
details.extend(x)
if len(details) == 0:
continue
edited_file_name = f.replace(folder, Out_Folder)
edited_file_log = f.replace(folder, os.path.join(Out_Folder, '..\\log')) + ".txt"
WriteTextInFile(edited_file_name, f_content)
print("------------------------------------------------------------------------")
f_number = "(file %03d ) " % jj
print(f_number + f)
logg = ""
for m, c in zip(details, range(0, len(details))):
indent = "\t\t\t%04d" % c
logg += (indent + m + "\n")
if len(logg) != 0:
WriteTextInFile(edited_file_log, logg)
print("the find/replace process finished ...")
| 4,035 | 1,458 |
# coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# 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.
"""Utility functions for the visualization code."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
from disentanglement_lib.utils import resources
import numpy as np
from PIL import Image
import scipy
from six.moves import range
import torch
import imageio
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def array_animation(data, fps=20):
fig, ax = plt.subplots(figsize=(3, 3))
plt.tight_layout()
ax.set_axis_off()
if len(data.shape) == 4:
data = data.transpose([0, 2, 3, 1])
im = ax.imshow(data[0], vmin=0, vmax=1)
def init():
im.set_data(data[0])
return (im,)
# animation function. This is called sequentially
def animate(i):
data_slice = data[i]
im.set_data(data_slice)
return (im,)
# call the animator. blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=len(data), interval=1000 / fps, blit=True)
return anim
def traversal_latents(base_latent, traversal_vector, dim):
l = len(traversal_vector)
traversals = base_latent.repeat(l, 1)
traversals[:, dim] = traversal_vector
return traversals
def plot_bar(axes, images, label=None):
for ax, img in zip(axes, images):
if img.shape[2] == 3:
ax.imshow(img)
elif img.shape[2] == 1:
ax.imshow(img.squeeze(2), cmap='gray')
ax.axis('off')
if label:
axes[-1].get_yaxis().set_label_position("right")
axes[-1].set_ylabel(label)
def sigmoid(x):
return 1 / (1 + np.exp(-np.clip(x, -20, 20)))
def plt_sample_traversal(mu, decode, traversal_len=5, dim_list=range(4), r=3):
"""
:param mu: Tensor: [1,dim]
:param decode:
:param traversal_len:
:param dim_list:
:param r:
:return:
"""
dim_len = len(dim_list)
if len(mu.shape) == 1:
mu = mu.unsqueeze(0)
with torch.no_grad():
fig, axes = plt.subplots(dim_len, traversal_len, squeeze=False,
figsize=(traversal_len, dim_len,))
plt.tight_layout(pad=0.1)
plt.subplots_adjust(wspace=0.01, hspace=0.05)
for i, dim in enumerate(dim_list):
base_latents = mu.clone()
linear_traversal = torch.linspace(-r, r, traversal_len)
traversals = traversal_latents(base_latents, linear_traversal, dim)
recon_batch = decode(traversals)
plot_bar(axes[i, :], recon_batch)
return fig
def save_image(image, image_path):
"""Saves an image in the [0,1]-valued Numpy array to image_path.
Args:
image: Numpy array of shape (height, width, {1,3}) with values in [0, 1].
image_path: String with path to output image.
"""
# Copy the single channel if we are provided a grayscale image.
if image.shape[2] == 1:
image = np.repeat(image, 3, axis=2)
image = np.ascontiguousarray(image)
image *= 255.
image = image.astype(np.uint8) # disable the converting warning
with open(image_path, "wb") as path:
img = Image.fromarray(image, mode="RGB")
img.save(path)
def grid_save_images(images, image_path):
"""Saves images in list of [0,1]-valued np.arrays on a grid.
Args:
images: List of Numpy arrays of shape (height, width, {1,3}) with values in
[0, 1].
image_path: String with path to output image.
"""
side_length = int(math.floor(math.sqrt(len(images))))
image_rows = [
np.concatenate(
images[side_length * i:side_length * i + side_length], axis=0)
for i in range(side_length)
]
tiled_image = np.concatenate(image_rows, axis=1)
print(image_path)
save_image(tiled_image, image_path)
def padded_grid(images, num_rows=None, padding_px=10, value=None):
"""Creates a grid with padding in between images."""
num_images = len(images)
if num_rows is None:
num_rows = best_num_rows(num_images)
# Computes how many empty images we need to add.
num_cols = int(np.ceil(float(num_images) / num_rows))
num_missing = num_rows * num_cols - num_images
# Add the empty images at the end.
all_images = images + [np.ones_like(images[0])] * num_missing
# Create the final grid.
rows = [padded_stack(all_images[i * num_cols:(i + 1) * num_cols], padding_px,
1, value=value) for i in range(num_rows)]
return padded_stack(rows, padding_px, axis=0, value=value)
def padded_stack(images, padding_px=10, axis=0, value=None):
"""Stacks images along axis with padding in between images."""
padding_arr = padding_array(images[0], padding_px, axis, value=value)
new_images = [images[0]]
for image in images[1:]:
new_images.append(padding_arr)
new_images.append(image)
return np.concatenate(new_images, axis=axis)
def padding_array(image, padding_px, axis, value=None):
"""Creates padding image of proper shape to pad image along the axis."""
shape = list(image.shape)
shape[axis] = padding_px
if value is None:
return np.ones(shape, dtype=image.dtype)
else:
assert len(value) == shape[-1]
shape[-1] = 1
return np.tile(value, shape)
def best_num_rows(num_elements, max_ratio=4):
"""Automatically selects a smart number of rows."""
best_remainder = num_elements
best_i = None
i = int(np.sqrt(num_elements))
while True:
if num_elements > max_ratio * i * i:
return best_i
remainder = (i - num_elements % i) % i
if remainder == 0:
return i
if remainder < best_remainder:
best_remainder = remainder
best_i = i
i -= 1
def pad_around(image, padding_px=10, axis=None, value=None):
"""Adds a padding around each image."""
# If axis is None, pad both the first and the second axis.
if axis is None:
image = pad_around(image, padding_px, axis=0, value=value)
axis = 1
padding_arr = padding_array(image, padding_px, axis, value=value)
return np.concatenate([padding_arr, image, padding_arr], axis=axis)
def add_below(image, padding_px=10, value=None):
"""Adds a footer below."""
if len(image.shape) == 2:
image = np.expand_dims(image, -1)
if image.shape[2] == 1:
image = np.repeat(image, 3, 2)
if image.shape[2] != 3:
raise ValueError("Could not convert image to have three channels.")
with open(resources.get_file("disentanglement_lib.png"), "rb") as f:
footer = np.array(Image.open(f).convert("RGB")) * 1.0 / 255.
missing_px = image.shape[1] - footer.shape[1]
if missing_px < 0:
return image
if missing_px > 0:
padding_arr = padding_array(footer, missing_px, axis=1, value=value)
footer = np.concatenate([padding_arr, footer], axis=1)
return padded_stack([image, footer], padding_px, axis=0, value=value)
def save_animation(list_of_animated_images, image_path, fps):
full_size_images = []
for single_images in zip(*list_of_animated_images):
full_size_images.append(
pad_around(add_below(padded_grid(list(single_images)))))
imageio.mimwrite(image_path, full_size_images, fps=fps)
def cycle_factor(starting_index, num_indices, num_frames):
"""Cycles through the state space in a single cycle."""
grid = np.linspace(starting_index, starting_index + 2 * num_indices,
num=num_frames, endpoint=False)
grid = np.array(np.ceil(grid), dtype=np.int64)
grid -= np.maximum(0, 2 * grid - 2 * num_indices + 1)
grid += np.maximum(0, -2 * grid - 1)
return grid
def cycle_gaussian(starting_value, num_frames, loc=0., scale=1.):
"""Cycles through the quantiles of a Gaussian in a single cycle."""
starting_prob = scipy.stats.norm.cdf(starting_value, loc=loc, scale=scale)
grid = np.linspace(starting_prob, starting_prob + 2.,
num=num_frames, endpoint=False)
grid -= np.maximum(0, 2 * grid - 2)
grid += np.maximum(0, -2 * grid)
grid = np.minimum(grid, 0.999)
grid = np.maximum(grid, 0.001)
return np.array([scipy.stats.norm.ppf(i, loc=loc, scale=scale) for i in grid])
def cycle_interval(starting_value, num_frames, min_val, max_val):
"""Cycles through the state space in a single cycle."""
starting_in_01 = (starting_value - min_val) / (max_val - min_val)
grid = np.linspace(starting_in_01, starting_in_01 + 2.,
num=num_frames, endpoint=False)
grid -= np.maximum(0, 2 * grid - 2)
grid += np.maximum(0, -2 * grid)
return grid * (max_val - min_val) + min_val
| 9,417 | 3,244 |
# Created by Chenye Yang, Haokai Zhao, Zhuoyue Xing on 2019/10/13.
# Copyright © 2019 Chenye Yang, Haokai Zhao, Zhuoyue Xing . All rights reserved.
from machine import Pin, I2C, RTC, Timer
import socket
import ssd1306
import time
import network
import urequests
import json
# ESP8266 connects to a router
def ConnectWIFI(essid, key):
import network
sta_if = network.WLAN(network.STA_IF) # config a station object
if not sta_if.isconnected(): # if the connection is not established
print('connecting to network...')
sta_if.active(True) # activate the station interface
sta_if.connect(essid, key) # connect to WiFi network
while not sta_if.isconnected():
print('connecting')
pass
print('network config:', sta_if.ifconfig()) # check the IP address
# ap_if.active(False) # disable the access-point interface
else:
print('network config:', sta_if.ifconfig()) # IP address, subnet mask, gateway and DNS server
# Get Current Time and Set ESP8266 Time to current time
def SetCurtTime():
# World Clock API
url = "http://worldclockapi.com/api/json/est/now"
webTime = json.loads(urequests.get(url).text) # returns a json string, convert it to json
webTime = webTime['currentDateTime'].split('T') # currentDataTime string as 2019-10-13T15:05-04:00
date = list(map(int, webTime[0].split('-'))) # extract time numbers
time = list(map(int, webTime[1].split('-')[0].split(':')))
timeTuple = (date[0], date[1], date[2], 0, time[0], time[1], 0, 0) # (year, month, day, weekday, hours, minutes, seconds, mseconds)
rtc.datetime(timeTuple) # set a specific date and time
# print(rtc.datetime())
# Show current time on OLED
def OLEDShowTime():
weekday = {0:'Monday', 1:'Tuesday', 2:'Wednesday', 3:'Thursday', 4:'Friday', 5:'Saturday', 6:'Sunday'}
# Storeage the current date and time to <int> list
timeList = list(map(int, rtc.datetime()))
# Covert <int> list to <str>
dateStr = "{:0>4d}".format(timeList[0])+'-'+"{:0>2d}".format(timeList[1])+'-'+"{:0>2d}".format(timeList[2])
# weekStr = weekday[timeList[3]]
timeStr = "{:0>2d}".format(timeList[4])+':'+"{:0>2d}".format(timeList[5])+':'+"{:0>2d}".format(timeList[6])
# Put string to OLED
oled.text(dateStr, 0, 0) # (message, x, y, color)
# oled.text(weekStr, 0, 11)
oled.text(timeStr, 0, 22)
# OLED show whether ESP8266 received commands
def OLEDRecvComd(received):
if received:
oled.text('RCVD', 80, 22) # Received the correct command
else:
oled.text('MISS', 80, 22) # Received a command ,but NOT a correct one
# Judge the Command received
def WhatCommand(cmd):
# cmd is Command in string, like: "turn on display"
global FLAG_True_Comd # Flag about whether it is a right command
global FLAG_Display_On # Flag about whetehr OLED can display things
global FLAG_Show_Time # Flag about whether the current time is shown on OLED
if cmd == 'turn on display':
FLAG_True_Comd = 1
FLAG_Display_On = 1
elif cmd == 'turn off display':
FLAG_True_Comd = 1
FLAG_Display_On = 0
elif cmd == 'show current time':
FLAG_True_Comd = 1
FLAG_Show_Time = 1
elif cmd == 'close current time':
FLAG_True_Comd = 1
FLAG_Show_Time = 0
else:
FLAG_True_Comd = 0 # not a right command
# Judge what to display on OLED, and display OLED with Timer
def WhatShowOLED(p):
global FLAG_True_Comd # Flag about whether it is a right command
global FLAG_Display_On # Flag about whetehr OLED can display things
global FLAG_Show_Time # Flag about whether the current time is shown on OLED
global showComd
if FLAG_Display_On: # able to display OLED
oled.text(showComd,0,11)
OLEDRecvComd(FLAG_True_Comd) # whether it's a right command, show on OLED
if FLAG_Show_Time: # show time on OLED if be able to
OLEDShowTime()
oled.show() # display text
else:
oled.fill(0) # fill OLED with black
oled.show() # display all black
oled.fill(0) # refresh, remove residue
# ESP8266 as a server to listen and response
def ListenResponse():
# a response ahout receiving a right JSON POST request
goodHTML = """<!DOCTYPE html>
<html>
<head> <title>Good Command</title> </head>
<body> <h1>The command from you is received by ESP8266</h1></body>
</html>
"""
# a response ahout NOT receiving a JSON POST request
badHTML = """<!DOCTYPE html>
<html>
<head> <title>Bad Command</title> </head>
<body> <h1>The command from you is NOT a JSON format</h1></body>
</html>
"""
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1] # Set web server port number to 80
s = socket.socket()
s.bind(addr) # Bind the socket to address
s.listen(1) # Enable a server to accept connections
print('listening on', addr)
global FLAG_True_Comd # Flag about whether it is a right command
global FLAG_Display_On # Flag about whetehr OLED can display things
global FLAG_Show_Time # Flag about whether the current time is shown on OLED
FLAG_True_Comd = 0
FLAG_Display_On = 0
FLAG_Show_Time = 0
while True:
print("FLAG_True_Comd", FLAG_True_Comd)
print("FLAG_Display_On", FLAG_Display_On)
print("FLAG_Show_Time", FLAG_Show_Time)
# accept the connect to 80 port
cl, addr = s.accept()
print('client connected from', addr)
# ESP8266 listen from the port
# The client terminal instruction should be like:
# curl -H "Content-Type:application/json" -X POST -d '{"Command":"turn on display"}' http://192.168.50.100:80
cl_receive = cl.recv(500).decode("utf-8").split("\r\n")[-1] # get the whole request and try to split it
try: # if the request is in a JSON POST format
cl_receive = json.loads(cl_receive) # convert the json string to json
print(cl_receive['Command'])
global showComd
showComd = cl_receive['Command']
except ValueError: # if not, give the response ahout not receiving a JSON POST
response = "HTTP/1.1 501 Implemented\r\n\r\nBad"
else: # if can be trasformed to JSON, give good response
response = "HTTP/1.1 200 OK\r\n\r\nGood"
WhatCommand(cl_receive['Command']) # judge what's the command received
# write to the port, i.e., give response
cl.send(response)
cl.close()
if __name__ == '__main__':
i2c = I2C(-1, scl=Pin(5), sda=Pin(4)) # initialize access to the I2C bus
i2c.scan()
oled = ssd1306.SSD1306_I2C(128, 32, i2c) # the width=128 and height=32
rtc = RTC()
tim = Timer(-1)
tim.init(period=100, mode=Timer.PERIODIC, callback=WhatShowOLED)
ConnectWIFI('Columbia University','') # connect esp8266 to a router
SetCurtTime()
ListenResponse() # Show ESP8266 Pins to test server
| 6,515 | 2,548 |
# ____ _ __ _ _ #
# / ___|| | ___ _ / _| __ _| | | ___ _ __ #
# \___ \| |/ / | | | |_ / _` | | |/ _ \ '_ \ #
# ___) | <| |_| | _| (_| | | | __/ | | |#
# |____/|_|\_\\__, |_| \__,_|_|_|\___|_| |_|#
# |___/ #########
# ____ ____ _ _ #
# / ___|___ | _ \ _ __ _____ _(_) __| | ___ _ __ #
# | | / _ \| |_) | '__/ _ \ \ / / |/ _` |/ _ \ '__|#
# | |__| (_) | __/| | | (_) \ V /| | (_| | __/ | #
# \____\___/|_| |_| \___/ \_/ |_|\__,_|\___|_| #
# #
###########################################################################
# (C) 2021 - Skyfallen Developers #
# Skyfallen CoProvider Beta #
# Manage your containerized servers with ease. #
# ----DAEMON CODE---- #
# This file helps validate requests #
###########################################################################
class ArgumentValidator:
def validateGetParams(requestArgs, paramsToValidate):
for x in paramsToValidate:
y = requestArgs.get(x)
if(y == "" or y == None):
return False
return True | 1,397 | 440 |
from rdflib import Namespace, XSD
from rdflib.namespace import DC, DCTERMS
FHIRCAT_CORD = Namespace("http://fhircat.org/cord-19/")
SSO = Namespace("http://semanticscholar.org/cv-research/")
DOI = Namespace("https://doi.org/")
PUBMED = Namespace("https://www.ncbi.nlm.nih.gov/pubmed/")
PMC = Namespace("https://www.ncbi.nlm.nih.gov/pmc/articles/")
MS_ACADEMIC = Namespace("https://academic.microsoft.com/paper/")
FHIR = Namespace("http://hl7.org/fhir/") | 453 | 189 |
import sys
import os
import argparse
from types import MethodType
from importlib import import_module
from argparse import RawTextHelpFormatter # Note: this applies to all options, might not always be what we want...
from pbutils.configs import get_config, get_config_from_data, to_dict, inject_opts, CP
from .strings import qw, ppjson
from .streams import warn
def parser_stub(docstr):
parser = argparse.ArgumentParser(description=docstr, formatter_class=RawTextHelpFormatter)
parser.add_argument('--config', default=_get_default_config_fn())
parser.add_argument('-v', '--verbose', action='store_true', help='verbose')
parser.add_argument('-q', '--silent', action='store_true', help='silent mode')
parser.add_argument('-d', '--debug', action='store_true', help='debugging flag')
# leave comments here as templates
# parser.add_argument('required_arg')
# parser.add_argument('--something', default='', help='')
# parser.add_argument('args', nargs=argparse.REMAINDER)
return parser
def _get_default_config_fn():
# warning: pyenv breaks this with its shims
fn = sys.argv[0].replace('.py', '.ini')
if not fn.endswith('.ini'):
fn += '.ini'
return fn
def _assemble_config(opts, default_section_name='default'):
'''
This builds a config by the following steps:
1. read config file (as specified in opts, otherwise empty)
2. inject environment vars as specified by config
3. inject opts
returns a ConfigParserRaw object.
'''
if opts.config:
try:
config = get_config(opts.config, config_type='Raw')
except OSError as e:
if e.errno == 2 and e.filename != _get_default_config_fn():
raise
else:
config = get_config_from_data(f'[{default_section_name}]')
if opts.debug:
warn(f'skipping non-existent config file {opts.config}')
inject_opts(config, opts)
# add a convenience method to get opts, which are stored in the default section:
def opt(self, opt, default=None):
try:
return self.get(default_section_name, opt)
except CP.NoOptionError:
if default is not None:
return default
else:
raise
config.opt = MethodType(opt, config)
return config
def wrap_main(main, parser, args=sys.argv[1:]):
'''
create config from config file and cmd-line args;
set os.environ['DEBUG'] if -d;
Call main(config);
trap exceptions; if they occur, print an error message (with optional stack trace)
and set exit value appropriately.
'''
opts = parser.parse_args(args)
config = _assemble_config(opts)
if opts.debug:
os.environ['DEBUG'] = 'True'
warn(opts)
if opts.silent and opts.verbose:
warn('WARNING: both --silent and --verbose are set. Your output may be weird')
try:
rc = main(config) or 0
sys.exit(rc)
except Exception as e:
if 'DEBUG' in os.environ:
import traceback
traceback.print_exc()
else:
print('error: {} {}'.format(type(e), e))
sys.exit(1)
def parser_config(parser, config):
'''
Use sections/values from the config file to initialize an argparser.
One cmd-line arg per config section; that is, each section contains
all the args needed for a call to parser.add_argument()
Example:
names = ['-x', '--some-option']
section = {'type': int, 'action': 'store_true', etc} (Note: conflict)
'''
for section in config.sections():
section_dict = to_dict(config, section)
names = ['--'+section]
if 'short_name' in section_dict:
names.append('-'+section_dict.pop('short_name'))
if 'type' in section_dict:
actual_type = eval(section_dict['type'])
section_dict['type'] = actual_type
if 'default' in section_dict:
section_dict['default'] = actual_type(section_dict['default'])
if 'action' in section_dict:
action = section_dict['action']
if action not in qw('store store_const store_true store_false append append_const count help version'):
# action must be fully qualified name (module and class) of a class derived from argparse.Action
modname, clsname = action.rsplit('.', 1)
mod = import_module(modname)
cls = getattr(mod, clsname)
section_dict['action'] = cls
parser.add_argument(*names, **section_dict)
class FloatIntStrParserAction(argparse.Action):
'''
Convert a string value to float, int, or str as possible.
To be used as value to 'action' kwarg of argparse.parser.add_argument, eg:
parser.add_argument('--some-value', action=FloatIntStrParserAction, ...)
This is called one time for each value on command line.
NOTE: use of this class as an Action precludes the use of the 'type' kwarg in add_argument!
'''
def __init__(self, **kwargs):
super(FloatIntStrParserAction, self).__init__(**kwargs)
def __call__(self, parser, namespace, values, option_string):
if self.type is not None: # coerce to that type
setattr(namespace, self.dest, self.type(values))
return
for t in [int, float, str]: # order important
try:
setattr(namespace, self.dest, t(values))
break
except ValueError as e:
pass
else:
parser.error("Error processing negc_var '{}'".format(values)) # should never get here
if __name__ == '__main__':
def getopts(opts_ini=None):
import argparse
parser = argparse.ArgumentParser()
if opts_ini:
opts_config = get_config(opts_ini)
parser.add_argument('-v', action='store_true', help='verbose mode')
parser.add_argument('-q', action='store_true', help='silent mode')
parser.add_argument('-d', action='store_true', help='debugging flag')
opts = parser.parse_args()
if opts.debug:
os.environ['DEBUG'] = 'True'
print(ppjson(vars(opts)))
return opts
# -----------------------------------------------------------------------
opts_ini = os.path.abspath(os.path.join(os.path.dirname(__file__), 'opts.ini'))
if not os.path.exists(opts_ini):
warn('{}: no such file')
opts_ini = None
opts = getopts(opts_ini)
| 6,568 | 1,885 |
#!/usr/bin/env python3
import json
from django.core.management.base import BaseCommand
from api.models import User
class Command(BaseCommand):
help = 'Print a dict of user status (number of users signed up per day) to stdout'
def handle(self, *args, **options):
stats = {}
for user in User.objects.all():
date_str = user.date_joined.strftime('%Y-%m-%d')
stats.setdefault(date_str, 0)
stats[date_str] += 1
print(json.dumps(stats, indent=4))
| 513 | 160 |
import pytest
from common import SCHEMAS_PATH, assert_yaml_header_and_footer, load_yaml
from jsonschema import ValidationError
@pytest.mark.parametrize("path", SCHEMAS_PATH.glob("asdf-schema-*.yaml"))
def test_asdf_schema(path):
assert_yaml_header_and_footer(path)
# Asserting no exceptions here
load_yaml(path)
@pytest.mark.parametrize("path", SCHEMAS_PATH.glob("asdf-schema-*.yaml"))
def test_nested_object_validation(path, create_validator):
"""
Test that the validations are applied to nested objects.
"""
metaschema = load_yaml(path)
validator = create_validator(metaschema)
schema = {"$schema": metaschema["id"], "type": "object", "properties": {"foo": {"datatype": "float32"}}}
# No error here
validator.validate(schema)
schema = {"$schema": metaschema["id"], "type": "object", "properties": {"foo": {"datatype": "banana"}}}
with pytest.raises(ValidationError, match="'banana' is not valid"):
validator.validate(schema)
schema = {
"$schema": metaschema["id"],
"type": "array",
"items": {"type": "object", "properties": {"foo": {"ndim": "twelve"}}},
}
with pytest.raises(ValidationError):
validator.validate(schema)
| 1,234 | 411 |
import tensorflow as tf
from retinanet.dataloader.anchor_generator import AnchorBoxGenerator
from retinanet.dataloader.preprocessing_pipeline import PreprocessingPipeline
from retinanet.dataloader.utils import compute_iou
class LabelEncoder:
def __init__(self, params):
self.input_shape = params.input.input_shape
self.encoder_params = params.encoder_params
self.anchors = AnchorBoxGenerator(
*self.input_shape,
params.architecture.feature_fusion.min_level,
params.architecture.feature_fusion.max_level,
params.anchor_params)
self.preprocessing_pipeline = PreprocessingPipeline(
self.input_shape, params.dataloader_params)
self._all_unmatched = -1 * tf.ones(
[self.anchors.boxes.get_shape().as_list()[0]], dtype=tf.int32)
self._min_level = params.architecture.feature_fusion.min_level
self._max_level = params.architecture.feature_fusion.max_level
self._params = params
def _match_anchor_boxes(self, anchor_boxes, gt_boxes):
if tf.shape(gt_boxes)[0] == 0:
return self._all_unmatched
iou_matrix = compute_iou(gt_boxes, anchor_boxes, pair_wise=True)
max_ious = tf.reduce_max(iou_matrix, axis=0)
matched_gt_idx = tf.argmax(iou_matrix, axis=0, output_type=tf.int32)
matches = tf.where(tf.greater(max_ious, self.encoder_params.match_iou),
matched_gt_idx, -1)
matches = tf.where(
tf.logical_and(
tf.greater_equal(max_ious, self.encoder_params.ignore_iou),
tf.greater(self.encoder_params.match_iou, max_ious)), -2,
matches)
best_matched_anchors = tf.argmax(iou_matrix,
axis=-1,
output_type=tf.int32)
best_matched_anchors_one_hot = tf.one_hot(
best_matched_anchors, depth=tf.shape(iou_matrix)[-1])
matched_anchors = tf.reduce_max(best_matched_anchors_one_hot, axis=0)
matched_anchors_gt_idx = tf.argmax(best_matched_anchors_one_hot,
axis=0,
output_type=tf.int32)
matches = tf.where(tf.cast(matched_anchors, dtype=tf.bool),
matched_anchors_gt_idx, matches)
return matches
def _compute_box_target(self, matched_gt_boxes, matches, eps=1e-8):
matched_gt_boxes = tf.maximum(matched_gt_boxes, eps)
box_target = tf.concat(
[
(matched_gt_boxes[:, :2] - self.anchors.boxes[:, :2]) /
self.anchors.boxes[:, 2:],
tf.math.log(
matched_gt_boxes[:, 2:] / self.anchors.boxes[:, 2:]),
],
axis=-1,
)
positive_mask = tf.expand_dims(tf.greater_equal(matches, 0), axis=-1)
positive_mask = tf.broadcast_to(positive_mask, tf.shape(box_target))
box_target = tf.where(positive_mask, box_target, 0.0)
if self.encoder_params.scale_box_targets:
box_target = box_target / tf.convert_to_tensor(
self.encoder_params.box_variance, dtype=tf.float32)
return box_target
@staticmethod
def _pad_labels(gt_boxes, cls_ids):
gt_boxes = tf.concat([tf.stack([tf.zeros(4), tf.zeros(4)]), gt_boxes],
axis=0)
cls_ids = tf.concat([
tf.squeeze(tf.stack([-2 * tf.ones(1), -1 * tf.ones(1)])), cls_ids
],
axis=0)
return gt_boxes, cls_ids
def encode_sample(self, sample):
image, gt_boxes, cls_ids = self.preprocessing_pipeline(sample)
matches = self._match_anchor_boxes(self.anchors.boxes, gt_boxes)
cls_ids = tf.cast(cls_ids, dtype=tf.float32)
gt_boxes, cls_ids = LabelEncoder._pad_labels(gt_boxes, cls_ids)
gt_boxes = tf.gather(gt_boxes, matches + 2)
cls_target = tf.gather(cls_ids, matches + 2)
box_target = self._compute_box_target(gt_boxes, matches)
iou_target = compute_iou(self.anchors.boxes, gt_boxes, pair_wise=False)
iou_target = tf.where(tf.greater(matches, -1), iou_target, -1.0)
boundaries = self.anchors.anchor_boundaries
targets = {'class-targets': {}, 'box-targets': {}}
if self._params.architecture.auxillary_head.use_auxillary_head:
targets['iou-targets'] = {}
# TODO(srihari): use pyramid levels for indexing
for level in range(self._min_level, self._max_level + 1):
i = level - 3
fh = tf.math.ceil(self.input_shape[0] / (2**(i + 3)))
fw = tf.math.ceil(self.input_shape[1] / (2**(i + 3)))
targets['class-targets'][str(i + 3)] = tf.reshape(
cls_target[boundaries[i]:boundaries[i + 1]],
shape=[fh, fw, self.anchors._num_anchors])
targets['box-targets'][str(i + 3)] = tf.reshape(
box_target[boundaries[i]:boundaries[i + 1]],
shape=[fh, fw, 4 * self.anchors._num_anchors])
if 'iou-targets' in targets:
targets['iou-targets'][str(i + 3)] = tf.reshape(
iou_target[boundaries[i]:boundaries[i + 1]],
shape=[fh, fw, self.anchors._num_anchors])
num_positives = tf.reduce_sum(
tf.cast(tf.greater(matches, -1), dtype=tf.float32))
targets['num-positives'] = num_positives
return image, targets
| 5,552 | 1,893 |