index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
17,337,406
mindfirst-admin/mindfirst
refs/heads/main
/db_generated/admin.py
from django.contrib import admin from .models import * # Register your models here. admin.site.register(DayModel) admin.site.register(FiveDayModel) admin.site.register(WeekModel) admin.site.register(MindWorkshopModel) admin.site.register(ResourcesModel) admin.site.register(WhatYoullLearnModel)
{"/accounts/extras_.py": ["/accounts/models.py"], "/accounts/migrations/0017_auto_20210809_2204.py": ["/accounts/models.py"], "/user_files/migrations/0003_auto_20210727_2335.py": ["/user_files/models.py"], "/accounts/migrations/0001_initial.py": ["/accounts/models.py"], "/characters/models.py": ["/accounts/models.py"], "/background_apps/functions.py": ["/accounts/models.py", "/characters/models.py"], "/main/views.py": ["/accounts/models.py", "/accounts/extras_.py", "/user_files/models.py", "/characters/models.py", "/behaviours/models.py", "/files_gallery/models.py"], "/api/views.py": ["/accounts/extras_.py", "/user_files/models.py", "/api/models.py"], "/user_files/views.py": ["/user_files/models.py"], "/characters/views.py": ["/characters/models.py", "/accounts/models.py"], "/accounts/tests.py": ["/accounts/models.py"], "/accounts/views.py": ["/accounts/models.py", "/accounts/extras_.py"], "/behaviours/models.py": ["/accounts/models.py"], "/behaviours/views.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/models.py": ["/accounts/models.py"], "/behaviours/forms.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/migrations/0001_initial.py": ["/files_gallery/models.py"], "/files_gallery/views.py": ["/files_gallery/models.py"], "/db_generated/views.py": ["/db_generated/models.py"], "/background/cron.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/forms.py": ["/files_gallery/models.py"], "/db_generated/admin.py": ["/db_generated/models.py"], "/behaviours/admin.py": ["/behaviours/models.py"], "/files_gallery/admin.py": ["/files_gallery/models.py"], "/payment_system/views.py": ["/payment_system/models.py"]}
17,337,407
mindfirst-admin/mindfirst
refs/heads/main
/db_generated/migrations/0001_initial.py
# Generated by Django 3.2.5 on 2021-10-15 23:09 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='DayModel', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('day_id', models.IntegerField(default=0)), ('title', models.CharField(default='', max_length=255)), ('file', models.FileField(upload_to='admin/days/video_images')), ('description', models.CharField(default='', max_length=1024)), ], ), migrations.CreateModel( name='FiveDayModel', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('day_id', models.IntegerField(default=0)), ('title', models.CharField(default='', max_length=255)), ('file', models.FileField(upload_to='admin/5days/video_images')), ('description', models.CharField(default='', max_length=1024)), ], ), migrations.CreateModel( name='MindWorkshopModel', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('week_id', models.IntegerField(default=0)), ('title', models.CharField(default='', max_length=255)), ('file', models.FileField(upload_to='admin/mind_workshop/video_images')), ('description', models.CharField(default='', max_length=1024)), ], ), migrations.CreateModel( name='WeekModel', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('week_id', models.IntegerField(default=0)), ('title', models.CharField(default='', max_length=255)), ('file', models.FileField(upload_to='admin/weeks/video_images')), ('description', models.CharField(default='', max_length=1024)), ], ), migrations.CreateModel( name='WhatYoullLearnModel', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('image', models.FileField(blank=True, null=True, upload_to="admin/what_you'll_learn/")), ('video', models.FileField(blank=True, null=True, upload_to="admin/what_you'll_learn/")), ('text', models.CharField(blank=True, default='', max_length=1024, null=True)), ('day', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='db_generated.daymodel')), ('five_day', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='db_generated.fivedaymodel')), ('mind_workshop', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='db_generated.mindworkshopmodel')), ('week', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='db_generated.weekmodel')), ], ), migrations.CreateModel( name='ResourcesModel', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('file', models.FileField(upload_to='admin/data/folder')), ('file_name', models.CharField(default='', max_length=255)), ('day', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='db_generated.daymodel')), ('five_day', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='db_generated.fivedaymodel')), ('mind_workshop', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='db_generated.mindworkshopmodel')), ('week', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='db_generated.weekmodel')), ], ), ]
{"/accounts/extras_.py": ["/accounts/models.py"], "/accounts/migrations/0017_auto_20210809_2204.py": ["/accounts/models.py"], "/user_files/migrations/0003_auto_20210727_2335.py": ["/user_files/models.py"], "/accounts/migrations/0001_initial.py": ["/accounts/models.py"], "/characters/models.py": ["/accounts/models.py"], "/background_apps/functions.py": ["/accounts/models.py", "/characters/models.py"], "/main/views.py": ["/accounts/models.py", "/accounts/extras_.py", "/user_files/models.py", "/characters/models.py", "/behaviours/models.py", "/files_gallery/models.py"], "/api/views.py": ["/accounts/extras_.py", "/user_files/models.py", "/api/models.py"], "/user_files/views.py": ["/user_files/models.py"], "/characters/views.py": ["/characters/models.py", "/accounts/models.py"], "/accounts/tests.py": ["/accounts/models.py"], "/accounts/views.py": ["/accounts/models.py", "/accounts/extras_.py"], "/behaviours/models.py": ["/accounts/models.py"], "/behaviours/views.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/models.py": ["/accounts/models.py"], "/behaviours/forms.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/migrations/0001_initial.py": ["/files_gallery/models.py"], "/files_gallery/views.py": ["/files_gallery/models.py"], "/db_generated/views.py": ["/db_generated/models.py"], "/background/cron.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/forms.py": ["/files_gallery/models.py"], "/db_generated/admin.py": ["/db_generated/models.py"], "/behaviours/admin.py": ["/behaviours/models.py"], "/files_gallery/admin.py": ["/files_gallery/models.py"], "/payment_system/views.py": ["/payment_system/models.py"]}
17,337,408
mindfirst-admin/mindfirst
refs/heads/main
/db_generated/urls.py
from django.urls import path from . import views app_name = "template" urlpatterns = [ path("take-control-over-your-habits/week~<int:week_id>", views.take_control_over_your_habits, name="take_control_over_your_habits"), path("get-started/day/~<int:day_id>", views.day_, name="day"), path("mind-workshop/week~<int:week_id>", views.mind_workshop, name="mind_workshop"), ]
{"/accounts/extras_.py": ["/accounts/models.py"], "/accounts/migrations/0017_auto_20210809_2204.py": ["/accounts/models.py"], "/user_files/migrations/0003_auto_20210727_2335.py": ["/user_files/models.py"], "/accounts/migrations/0001_initial.py": ["/accounts/models.py"], "/characters/models.py": ["/accounts/models.py"], "/background_apps/functions.py": ["/accounts/models.py", "/characters/models.py"], "/main/views.py": ["/accounts/models.py", "/accounts/extras_.py", "/user_files/models.py", "/characters/models.py", "/behaviours/models.py", "/files_gallery/models.py"], "/api/views.py": ["/accounts/extras_.py", "/user_files/models.py", "/api/models.py"], "/user_files/views.py": ["/user_files/models.py"], "/characters/views.py": ["/characters/models.py", "/accounts/models.py"], "/accounts/tests.py": ["/accounts/models.py"], "/accounts/views.py": ["/accounts/models.py", "/accounts/extras_.py"], "/behaviours/models.py": ["/accounts/models.py"], "/behaviours/views.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/models.py": ["/accounts/models.py"], "/behaviours/forms.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/migrations/0001_initial.py": ["/files_gallery/models.py"], "/files_gallery/views.py": ["/files_gallery/models.py"], "/db_generated/views.py": ["/db_generated/models.py"], "/background/cron.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/forms.py": ["/files_gallery/models.py"], "/db_generated/admin.py": ["/db_generated/models.py"], "/behaviours/admin.py": ["/behaviours/models.py"], "/files_gallery/admin.py": ["/files_gallery/models.py"], "/payment_system/views.py": ["/payment_system/models.py"]}
17,337,409
mindfirst-admin/mindfirst
refs/heads/main
/behaviours/urls.py
from django.urls import path from . import views, forms app_name = 'behaviours' urlpatterns = [ path("", views.behaviour_mapping, name="behaviour_mapping"), path("habit-reporting/<str:orientation>/", views.habit_reporting, name="habit_reporting"), path("habit-design/<int:behaviour_id>/", views.habit_design, name="habit_design"), path("habit-summary/<str:orientation>/", views.habit_summary, name="habit_summary"), # forms path("change-aspiration-name", forms.change_aspiration_name, name="change_aspiration_name"), path("save-mapping", forms.select_behavior, name="select_behavior"), path("delete-behaviour", forms.delete_behaviour, name="delete_behaviour"), path("add-behaviour", forms.add_behaviour, name="add_behaviour"), path("update-behaviour", forms.update_behaviour, name="update_behaviour"), path("get-behaviours", forms.get_behaviours, name="get_behaviours"), path("design-positive-habit", forms.design_positive_habit, name="design_positive_habit"), path("design-negative-habit", forms.design_negative_habits, name="design_negative_habits"), path("record-todays-habit", forms.record_todays_habit, name="record_todays_habit"), path("scale-habit", forms.scale_habit, name="scale_habit"), # limiting beliefs path("update-beliefs", forms.update_beliefs, name="update_beliefs"), # members area chart path("three-month-data", forms.get_trimonthly_chart_data, name="get_trimonthly_chart_data"), path("weekly-data", forms.get_weekly_chart_data, name="get_weekly_chart_data"), ]
{"/accounts/extras_.py": ["/accounts/models.py"], "/accounts/migrations/0017_auto_20210809_2204.py": ["/accounts/models.py"], "/user_files/migrations/0003_auto_20210727_2335.py": ["/user_files/models.py"], "/accounts/migrations/0001_initial.py": ["/accounts/models.py"], "/characters/models.py": ["/accounts/models.py"], "/background_apps/functions.py": ["/accounts/models.py", "/characters/models.py"], "/main/views.py": ["/accounts/models.py", "/accounts/extras_.py", "/user_files/models.py", "/characters/models.py", "/behaviours/models.py", "/files_gallery/models.py"], "/api/views.py": ["/accounts/extras_.py", "/user_files/models.py", "/api/models.py"], "/user_files/views.py": ["/user_files/models.py"], "/characters/views.py": ["/characters/models.py", "/accounts/models.py"], "/accounts/tests.py": ["/accounts/models.py"], "/accounts/views.py": ["/accounts/models.py", "/accounts/extras_.py"], "/behaviours/models.py": ["/accounts/models.py"], "/behaviours/views.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/models.py": ["/accounts/models.py"], "/behaviours/forms.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/migrations/0001_initial.py": ["/files_gallery/models.py"], "/files_gallery/views.py": ["/files_gallery/models.py"], "/db_generated/views.py": ["/db_generated/models.py"], "/background/cron.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/forms.py": ["/files_gallery/models.py"], "/db_generated/admin.py": ["/db_generated/models.py"], "/behaviours/admin.py": ["/behaviours/models.py"], "/files_gallery/admin.py": ["/files_gallery/models.py"], "/payment_system/views.py": ["/payment_system/models.py"]}
17,337,410
mindfirst-admin/mindfirst
refs/heads/main
/behaviours/admin.py
from django.contrib import admin from .models import * # Register your models here. admin.site.register(BehaviourMapping) admin.site.register(DesignPositiveHabits) admin.site.register(DesignNegativeHabits) admin.site.register(LimitingBeliefs)
{"/accounts/extras_.py": ["/accounts/models.py"], "/accounts/migrations/0017_auto_20210809_2204.py": ["/accounts/models.py"], "/user_files/migrations/0003_auto_20210727_2335.py": ["/user_files/models.py"], "/accounts/migrations/0001_initial.py": ["/accounts/models.py"], "/characters/models.py": ["/accounts/models.py"], "/background_apps/functions.py": ["/accounts/models.py", "/characters/models.py"], "/main/views.py": ["/accounts/models.py", "/accounts/extras_.py", "/user_files/models.py", "/characters/models.py", "/behaviours/models.py", "/files_gallery/models.py"], "/api/views.py": ["/accounts/extras_.py", "/user_files/models.py", "/api/models.py"], "/user_files/views.py": ["/user_files/models.py"], "/characters/views.py": ["/characters/models.py", "/accounts/models.py"], "/accounts/tests.py": ["/accounts/models.py"], "/accounts/views.py": ["/accounts/models.py", "/accounts/extras_.py"], "/behaviours/models.py": ["/accounts/models.py"], "/behaviours/views.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/models.py": ["/accounts/models.py"], "/behaviours/forms.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/migrations/0001_initial.py": ["/files_gallery/models.py"], "/files_gallery/views.py": ["/files_gallery/models.py"], "/db_generated/views.py": ["/db_generated/models.py"], "/background/cron.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/forms.py": ["/files_gallery/models.py"], "/db_generated/admin.py": ["/db_generated/models.py"], "/behaviours/admin.py": ["/behaviours/models.py"], "/files_gallery/admin.py": ["/files_gallery/models.py"], "/payment_system/views.py": ["/payment_system/models.py"]}
17,337,411
mindfirst-admin/mindfirst
refs/heads/main
/accounts/views.py
import json from django.contrib import messages, auth from django.shortcuts import render, redirect from django.http import HttpResponseRedirect, JsonResponse from django.urls import reverse from django.contrib.auth import get_user_model from .models import * User = get_user_model() # Create your views here. def reserve_membership_spot(request): if request.POST.get('data', None): data = json.loads(request.POST.get('data')) new_waiting_member = MembershipWaitingList(email=data['email'], first_name=data['firstname'], last_name=data['lastname']) new_waiting_member.save() return JsonResponse('Done', safe=False) return render(request, 'accounts/reserve_membership_spot.html') def reserve_fd_challenge_spot(request): if request.POST.get('data', None): data = json.loads(request.POST.get('data')) new_waiting_member = FiveDayWaitingList(email=data['email'], first_name=data['firstname'], last_name=data['lastname']) new_waiting_member.save() return JsonResponse('Done', safe=False) return render(request, 'accounts/reserve_fd_challenge_spot.html') def sign_in_to_members_area(request): if request.POST: password = request.POST['password'] email = request.POST['email'] # user = User.objects.filter(email='email@gmail.com').first() # user.set_password('iaminnathemale') # user.save() if User.objects.filter(email=email).count() == 0: messages.error(request, 'Email doesn\'t exist in our database') else: user = auth.authenticate(email=email, password=password) if user is not None: user_profile = Profile.objects.filter(user=user).first() if user_profile: if user_profile.is_subscribed and user.is_active: auth.login(request, user) return HttpResponseRedirect(reverse('main:members_area')) messages.error(request, 'You are not on a membership subscription plan or your account is disabled') else: messages.error(request, 'Incorrect email or password') return render(request, 'accounts/sign_in_to_members_area.html') def user_forgot_password(request): if request.POST: email = request.POST['email'] user = User.objects.filter(email=email).first() if user is not None: password = create_password() user.set_password(password) user.save() user_auth = auth.authenticate(email=email, password=password) if user_auth: # send email via active campaign messages.error(request, 'Your password was changed successfully, an email has been sent with the new details') else: messages.error(request, 'There was an error changing your password, please try again') else: messages.error(request, 'Email doesn\'t exist') return render(request, 'accounts/forgot_password.html') def logout(request): auth.logout(request) return redirect('main:homepage')
{"/accounts/extras_.py": ["/accounts/models.py"], "/accounts/migrations/0017_auto_20210809_2204.py": ["/accounts/models.py"], "/user_files/migrations/0003_auto_20210727_2335.py": ["/user_files/models.py"], "/accounts/migrations/0001_initial.py": ["/accounts/models.py"], "/characters/models.py": ["/accounts/models.py"], "/background_apps/functions.py": ["/accounts/models.py", "/characters/models.py"], "/main/views.py": ["/accounts/models.py", "/accounts/extras_.py", "/user_files/models.py", "/characters/models.py", "/behaviours/models.py", "/files_gallery/models.py"], "/api/views.py": ["/accounts/extras_.py", "/user_files/models.py", "/api/models.py"], "/user_files/views.py": ["/user_files/models.py"], "/characters/views.py": ["/characters/models.py", "/accounts/models.py"], "/accounts/tests.py": ["/accounts/models.py"], "/accounts/views.py": ["/accounts/models.py", "/accounts/extras_.py"], "/behaviours/models.py": ["/accounts/models.py"], "/behaviours/views.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/models.py": ["/accounts/models.py"], "/behaviours/forms.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/migrations/0001_initial.py": ["/files_gallery/models.py"], "/files_gallery/views.py": ["/files_gallery/models.py"], "/db_generated/views.py": ["/db_generated/models.py"], "/background/cron.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/forms.py": ["/files_gallery/models.py"], "/db_generated/admin.py": ["/db_generated/models.py"], "/behaviours/admin.py": ["/behaviours/models.py"], "/files_gallery/admin.py": ["/files_gallery/models.py"], "/payment_system/views.py": ["/payment_system/models.py"]}
17,337,412
mindfirst-admin/mindfirst
refs/heads/main
/files_gallery/admin.py
from django.contrib import admin from .models import * # Register your models here. admin.site.register(AdminValuesImages) admin.site.register(VisionGalleryFiles)
{"/accounts/extras_.py": ["/accounts/models.py"], "/accounts/migrations/0017_auto_20210809_2204.py": ["/accounts/models.py"], "/user_files/migrations/0003_auto_20210727_2335.py": ["/user_files/models.py"], "/accounts/migrations/0001_initial.py": ["/accounts/models.py"], "/characters/models.py": ["/accounts/models.py"], "/background_apps/functions.py": ["/accounts/models.py", "/characters/models.py"], "/main/views.py": ["/accounts/models.py", "/accounts/extras_.py", "/user_files/models.py", "/characters/models.py", "/behaviours/models.py", "/files_gallery/models.py"], "/api/views.py": ["/accounts/extras_.py", "/user_files/models.py", "/api/models.py"], "/user_files/views.py": ["/user_files/models.py"], "/characters/views.py": ["/characters/models.py", "/accounts/models.py"], "/accounts/tests.py": ["/accounts/models.py"], "/accounts/views.py": ["/accounts/models.py", "/accounts/extras_.py"], "/behaviours/models.py": ["/accounts/models.py"], "/behaviours/views.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/models.py": ["/accounts/models.py"], "/behaviours/forms.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/migrations/0001_initial.py": ["/files_gallery/models.py"], "/files_gallery/views.py": ["/files_gallery/models.py"], "/db_generated/views.py": ["/db_generated/models.py"], "/background/cron.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/forms.py": ["/files_gallery/models.py"], "/db_generated/admin.py": ["/db_generated/models.py"], "/behaviours/admin.py": ["/behaviours/models.py"], "/files_gallery/admin.py": ["/files_gallery/models.py"], "/payment_system/views.py": ["/payment_system/models.py"]}
17,337,413
mindfirst-admin/mindfirst
refs/heads/main
/accounts/urls.py
from django.urls import path from . import views app_name = 'accounts' urlpatterns = [ path("membership/reserve-your-spot/", views.reserve_membership_spot, name="reserve_membership_spot"), path("5-day-challenge", views.reserve_fd_challenge_spot, name="reserve_fd_challenge_spot"), path("members-area/sign-in/", views.sign_in_to_members_area, name="sign_in_to_members_area"), path("forgot-password/", views.user_forgot_password, name="user_forgot_password"), path("logout/", views.logout, name="logout"), ]
{"/accounts/extras_.py": ["/accounts/models.py"], "/accounts/migrations/0017_auto_20210809_2204.py": ["/accounts/models.py"], "/user_files/migrations/0003_auto_20210727_2335.py": ["/user_files/models.py"], "/accounts/migrations/0001_initial.py": ["/accounts/models.py"], "/characters/models.py": ["/accounts/models.py"], "/background_apps/functions.py": ["/accounts/models.py", "/characters/models.py"], "/main/views.py": ["/accounts/models.py", "/accounts/extras_.py", "/user_files/models.py", "/characters/models.py", "/behaviours/models.py", "/files_gallery/models.py"], "/api/views.py": ["/accounts/extras_.py", "/user_files/models.py", "/api/models.py"], "/user_files/views.py": ["/user_files/models.py"], "/characters/views.py": ["/characters/models.py", "/accounts/models.py"], "/accounts/tests.py": ["/accounts/models.py"], "/accounts/views.py": ["/accounts/models.py", "/accounts/extras_.py"], "/behaviours/models.py": ["/accounts/models.py"], "/behaviours/views.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/models.py": ["/accounts/models.py"], "/behaviours/forms.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/migrations/0001_initial.py": ["/files_gallery/models.py"], "/files_gallery/views.py": ["/files_gallery/models.py"], "/db_generated/views.py": ["/db_generated/models.py"], "/background/cron.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/forms.py": ["/files_gallery/models.py"], "/db_generated/admin.py": ["/db_generated/models.py"], "/behaviours/admin.py": ["/behaviours/models.py"], "/files_gallery/admin.py": ["/files_gallery/models.py"], "/payment_system/views.py": ["/payment_system/models.py"]}
17,337,414
mindfirst-admin/mindfirst
refs/heads/main
/payment_system/views.py
import stripe from django.conf import settings from django.contrib import messages from django.shortcuts import render, redirect from .models import UserPurchases stripe.api_key = settings.STRIPE_API_KEY # Create your views here. def payment_pages(response, product): if product == 'book': return render(response, 'payments/book_payment.html', {}) elif product == 'workbook': return render(response, 'payments/workbook_payment.html', {}) elif product == 'membership': return render(response, 'payments/membership_payment.html', {}) def membership_monthly(request): session = stripe.checkout.Session.create( success_url='http://127.0.0.1:8000/payment/thank-you', cancel_url='http://127.0.0.1:8000/payment/thank-you', payment_method_types=['card'], mode='subscription', line_items=[{ 'price': 'price_1Jjn2uGjOqEuQIlnJY2BXS0I', 'quantity': 1 }], ) request.session['stripe_payment'] = 'monthly_membership' request.session['session_id'] = session.id print(session) if session: return redirect(session.url, code=302) messages.error(request, 'An error occurred, please try again') return redirect('payments:payment_pages', product='membership') def membership_annually(request): session = stripe.checkout.Session.create( success_url='http://127.0.0.1:8000/payment/thank-you', cancel_url='http://127.0.0.1:8000/payment/payment-unsuccessful', payment_method_types=['card'], mode='subscription', line_items=[{ 'price': 'price_1JCoJ7GjOqEuQIlnR7tC51sB', 'quantity': 1 }], ) request.session['stripe_payment'] = 'annual_membership' request.session['session_id'] = session.id if session: return redirect(session.url, code=302) messages.error(request, 'An error occurred, please try again') return redirect('payments:payment_pages', product='membership') def ebook_purchase(request): session = stripe.checkout.Session.create( success_url='http://127.0.0.1:8000/payment/thank-you', cancel_url='http://127.0.0.1:8000/payment/payment-unsuccessful', payment_method_types=['card'], mode='payment', line_items=[{ 'price': 'price_1Jjmx2GjOqEuQIlnMOgaTifz', 'quantity': 1 }], ) request.session['stripe_payment'] = 'ebook' request.session['session_id'] = session.id if session: return redirect(session.url, code=302) messages.error(request, 'An error occurred, please try again') return redirect('payments:payment_pages', product='book') def audiobook_purchase(request): session = stripe.checkout.Session.create( success_url='http://127.0.0.1:8000/payment/thank-you', cancel_url='http://127.0.0.1:8000/payment/payment-unsuccessful', payment_method_types=['card'], mode='payment', line_items=[{ 'price': 'price_1JjmzcGjOqEuQIlnfm1W6YsY', 'quantity': 1 }], ) request.session['stripe_payment'] = 'audiobook' request.session['session_id'] = session.id if session: return redirect(session.url, code=302) messages.error(request, 'An error occurred, please try again') return redirect('payments:payment_pages', product='book') def audiobook_n_ebook_purchase(request): session = stripe.checkout.Session.create( success_url='http://127.0.0.1:8000/payment/thank-you', cancel_url='http://127.0.0.1:8000/payment/payment-unsuccessful', payment_method_types=['card'], mode='payment', line_items=[{ 'price': 'price_1Jjn0mGjOqEuQIlnp1YMVrEu', 'quantity': 1 }], ) request.session['stripe_payment'] = 'audiobook_x_ebook' request.session['session_id'] = session.id if session: return redirect(session.url, code=302) messages.error(request, 'An error occurred, please try again') return redirect('payments:payment_pages', product='book') def workbook_purchase(request): session = stripe.checkout.Session.create( success_url='http://127.0.0.1:8000/payment/thank-you', cancel_url='http://127.0.0.1:8000/payment/payment-unsuccessful', payment_method_types=['card'], mode='payment', line_items=[{ 'price': 'price_1JjmvHGjOqEuQIlnjf3D5Fm3', 'quantity': 1 }], ) request.session['stripe_payment'] = 'workbook' request.session['session_id'] = session.id if session: return redirect(session.url, code=302) messages.error(request, 'An error occurred, please try again') return redirect('payments:payment_pages', product='workbook') def thank_you(request): purchase = request.session['stripe_payment'] retrieved_session = stripe.checkout.Session.retrieve( request.session['session_id'], ) if retrieved_session.payment_status != 'unpaid': customer_id = retrieved_session.customer email = retrieved_session.customer_details.email new_purchase = UserPurchases(purchase=purchase, stripe_customer_id=customer_id, stripe_checkout_id=retrieved_session.id, email=email) new_purchase.save() return render(request, 'payments/thank_you.html') def payment_unsuccessful(request): request.session['stripe_payment'] = '' request.session['session_id'] = '' return render(request, 'payments/payment_unsuccessful.html')
{"/accounts/extras_.py": ["/accounts/models.py"], "/accounts/migrations/0017_auto_20210809_2204.py": ["/accounts/models.py"], "/user_files/migrations/0003_auto_20210727_2335.py": ["/user_files/models.py"], "/accounts/migrations/0001_initial.py": ["/accounts/models.py"], "/characters/models.py": ["/accounts/models.py"], "/background_apps/functions.py": ["/accounts/models.py", "/characters/models.py"], "/main/views.py": ["/accounts/models.py", "/accounts/extras_.py", "/user_files/models.py", "/characters/models.py", "/behaviours/models.py", "/files_gallery/models.py"], "/api/views.py": ["/accounts/extras_.py", "/user_files/models.py", "/api/models.py"], "/user_files/views.py": ["/user_files/models.py"], "/characters/views.py": ["/characters/models.py", "/accounts/models.py"], "/accounts/tests.py": ["/accounts/models.py"], "/accounts/views.py": ["/accounts/models.py", "/accounts/extras_.py"], "/behaviours/models.py": ["/accounts/models.py"], "/behaviours/views.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/models.py": ["/accounts/models.py"], "/behaviours/forms.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/migrations/0001_initial.py": ["/files_gallery/models.py"], "/files_gallery/views.py": ["/files_gallery/models.py"], "/db_generated/views.py": ["/db_generated/models.py"], "/background/cron.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/forms.py": ["/files_gallery/models.py"], "/db_generated/admin.py": ["/db_generated/models.py"], "/behaviours/admin.py": ["/behaviours/models.py"], "/files_gallery/admin.py": ["/files_gallery/models.py"], "/payment_system/views.py": ["/payment_system/models.py"]}
17,337,415
mindfirst-admin/mindfirst
refs/heads/main
/main/urls.py
from django.urls import path from . import views app_name = 'main' urlpatterns = [ path("", views.homepage, name="homepage"), path("products", views.our_products, name="our_products"), path("members-area", views.members_area, name="members_area"), path("limiting-beliefs/", views.limiting_beliefs, name="limiting_beliefs"), path("product-details/<str:product>", views.product_details, name="product_details"), ]
{"/accounts/extras_.py": ["/accounts/models.py"], "/accounts/migrations/0017_auto_20210809_2204.py": ["/accounts/models.py"], "/user_files/migrations/0003_auto_20210727_2335.py": ["/user_files/models.py"], "/accounts/migrations/0001_initial.py": ["/accounts/models.py"], "/characters/models.py": ["/accounts/models.py"], "/background_apps/functions.py": ["/accounts/models.py", "/characters/models.py"], "/main/views.py": ["/accounts/models.py", "/accounts/extras_.py", "/user_files/models.py", "/characters/models.py", "/behaviours/models.py", "/files_gallery/models.py"], "/api/views.py": ["/accounts/extras_.py", "/user_files/models.py", "/api/models.py"], "/user_files/views.py": ["/user_files/models.py"], "/characters/views.py": ["/characters/models.py", "/accounts/models.py"], "/accounts/tests.py": ["/accounts/models.py"], "/accounts/views.py": ["/accounts/models.py", "/accounts/extras_.py"], "/behaviours/models.py": ["/accounts/models.py"], "/behaviours/views.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/models.py": ["/accounts/models.py"], "/behaviours/forms.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/migrations/0001_initial.py": ["/files_gallery/models.py"], "/files_gallery/views.py": ["/files_gallery/models.py"], "/db_generated/views.py": ["/db_generated/models.py"], "/background/cron.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/forms.py": ["/files_gallery/models.py"], "/db_generated/admin.py": ["/db_generated/models.py"], "/behaviours/admin.py": ["/behaviours/models.py"], "/files_gallery/admin.py": ["/files_gallery/models.py"], "/payment_system/views.py": ["/payment_system/models.py"]}
17,337,416
mindfirst-admin/mindfirst
refs/heads/main
/accounts/migrations/0001_initial.py
# Generated by Django 3.2.5 on 2021-10-15 23:09 import accounts.models from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Users', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), ('email', models.EmailField(max_length=255, unique=True)), ('phone_number', models.IntegerField()), ('is_active', models.BooleanField(default=True)), ('staff', models.BooleanField(default=False)), ('admin', models.BooleanField(default=False)), ], options={ 'abstract': False, }, ), migrations.CreateModel( name='FiveDayWaitingList', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('email', models.EmailField(max_length=255, unique=True)), ('first_name', models.CharField(max_length=255, unique=True)), ('last_name', models.CharField(max_length=255, unique=True)), ], ), migrations.CreateModel( name='MembershipWaitingList', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('email', models.EmailField(max_length=255, unique=True)), ('first_name', models.CharField(max_length=255, unique=True)), ('last_name', models.CharField(max_length=255, unique=True)), ], ), migrations.CreateModel( name='Profile', fields=[ ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, primary_key=True, serialize=False, to='accounts.users')), ('user_token', models.CharField(default=accounts.models.generate_user_token, max_length=36)), ('aspiration_name', models.CharField(default='Aspiration', max_length=255)), ('is_subscribed', models.BooleanField(default=False)), ('customer_id', models.CharField(default='', max_length=50)), ('scaled_habits', models.IntegerField(default=0)), ('yellow_habits', models.IntegerField(default=0)), ('red_habits', models.IntegerField(default=0)), ('green_habits', models.IntegerField(default=0)), ('negative_behaviors_done_this_week', models.CharField(default='0/0', max_length=10)), ('positive_behaviors_done_this_week', models.CharField(default='0/0', max_length=10)), ('all_positive_habits_this_week', models.CharField(default='[]', max_length=20)), ('all_scaled_habits_this_week', models.CharField(default='[]', max_length=20)), ('all_negative_habits_this_week', models.CharField(default='[]', max_length=20)), ('all_positive_habits_in_twelve_weeks', models.CharField(default='[]', max_length=40)), ('all_scaled_habits_in_twelve_weeks', models.CharField(default='[]', max_length=40)), ('all_negative_habits_in_twelve_weeks', models.CharField(default='[]', max_length=40)), ], ), ]
{"/accounts/extras_.py": ["/accounts/models.py"], "/accounts/migrations/0017_auto_20210809_2204.py": ["/accounts/models.py"], "/user_files/migrations/0003_auto_20210727_2335.py": ["/user_files/models.py"], "/accounts/migrations/0001_initial.py": ["/accounts/models.py"], "/characters/models.py": ["/accounts/models.py"], "/background_apps/functions.py": ["/accounts/models.py", "/characters/models.py"], "/main/views.py": ["/accounts/models.py", "/accounts/extras_.py", "/user_files/models.py", "/characters/models.py", "/behaviours/models.py", "/files_gallery/models.py"], "/api/views.py": ["/accounts/extras_.py", "/user_files/models.py", "/api/models.py"], "/user_files/views.py": ["/user_files/models.py"], "/characters/views.py": ["/characters/models.py", "/accounts/models.py"], "/accounts/tests.py": ["/accounts/models.py"], "/accounts/views.py": ["/accounts/models.py", "/accounts/extras_.py"], "/behaviours/models.py": ["/accounts/models.py"], "/behaviours/views.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/models.py": ["/accounts/models.py"], "/behaviours/forms.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/migrations/0001_initial.py": ["/files_gallery/models.py"], "/files_gallery/views.py": ["/files_gallery/models.py"], "/db_generated/views.py": ["/db_generated/models.py"], "/background/cron.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/forms.py": ["/files_gallery/models.py"], "/db_generated/admin.py": ["/db_generated/models.py"], "/behaviours/admin.py": ["/behaviours/models.py"], "/files_gallery/admin.py": ["/files_gallery/models.py"], "/payment_system/views.py": ["/payment_system/models.py"]}
17,386,248
guilhermegoesgarcia/API_REST_contratacao_de_frete
refs/heads/master
/cadastro_frete/serializer.py
from rest_framework import serializers from cadastro_frete.models import CadastroEmpresa,CadastroCliente,CadastroOferta,Lance from cadastro_frete.validators import * class CadastroEmpresa_Serializer(serializers.ModelSerializer): class Meta: model = CadastroEmpresa fields = '__all__' def validate(self, data): if not cnpj_valido(data['doc']): raise serializers.ValidationError({'doc': "Número de CNPJ inválido"}) if not site_valido(data['site']): raise serializers.ValidationError({'site': "Endereço de SITE inválido"}) return data class CadastroCliente_Serializer(serializers.ModelSerializer): class Meta: model = CadastroCliente fields = '__all__' def validate(self, data): if not cnpj_valido(data['doc']): raise serializers.ValidationError({'doc': "Número de CNPJ inválido"}) if not site_valido(data['site']): raise serializers.ValidationError({'site': "Endereço de SITE inválido"}) return data class CadastroOferta_Serializer(serializers.ModelSerializer): class Meta: model = CadastroOferta fields = '__all__' class Lance_Serializer(serializers.ModelSerializer): class Meta: model = Lance fields = '__all__'
{"/cadastro_frete/views.py": ["/cadastro_frete/models.py", "/cadastro_frete/serializer.py"], "/cadastro_frete/admin.py": ["/cadastro_frete/models.py"], "/cadastro_frete/serializer.py": ["/cadastro_frete/models.py", "/cadastro_frete/validators.py"]}
17,386,249
guilhermegoesgarcia/API_REST_contratacao_de_frete
refs/heads/master
/cadastro_frete/teste_modelo_padrao.py
import re modelo_0 = 'google.com.br' modelo_1 = 'https//www.google.com.br' modelo_2 = 'www.google.com' modelo_geral ='(https//)*(\S{1,30}.com.br|\S{1,30}.com)' resposta = re.findall(modelo_geral,modelo_0) if resposta: teste = 'Verdadeiro' else: teste ='Falso' print(teste, resposta)
{"/cadastro_frete/views.py": ["/cadastro_frete/models.py", "/cadastro_frete/serializer.py"], "/cadastro_frete/admin.py": ["/cadastro_frete/models.py"], "/cadastro_frete/serializer.py": ["/cadastro_frete/models.py", "/cadastro_frete/validators.py"]}
17,386,250
guilhermegoesgarcia/API_REST_contratacao_de_frete
refs/heads/master
/cadastro_frete/validators.py
import re from validate_docbr import CNPJ def cnpj_valido(numero_cnpj): cnpj = CNPJ() return cnpj.validate(numero_cnpj) def nome_valido(name): return name.isalpha() def site_valido(site): '''verifica se o site é válido''' modelo = '(https//)*(\S{1,30}.com.br|\S{1,30}.com)' resposta = re.findall(modelo,site) return resposta
{"/cadastro_frete/views.py": ["/cadastro_frete/models.py", "/cadastro_frete/serializer.py"], "/cadastro_frete/admin.py": ["/cadastro_frete/models.py"], "/cadastro_frete/serializer.py": ["/cadastro_frete/models.py", "/cadastro_frete/validators.py"]}
17,386,251
guilhermegoesgarcia/API_REST_contratacao_de_frete
refs/heads/master
/cadastro_frete/migrations/0003_auto_20211029_0025.py
# Generated by Django 3.0.8 on 2021-10-29 00:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cadastro_frete', '0002_auto_20211029_0015'), ] operations = [ migrations.AlterField( model_name='cadastrocliente', name='id', field=models.IntegerField(primary_key=True, serialize=False), ), ]
{"/cadastro_frete/views.py": ["/cadastro_frete/models.py", "/cadastro_frete/serializer.py"], "/cadastro_frete/admin.py": ["/cadastro_frete/models.py"], "/cadastro_frete/serializer.py": ["/cadastro_frete/models.py", "/cadastro_frete/validators.py"]}
17,386,252
guilhermegoesgarcia/API_REST_contratacao_de_frete
refs/heads/master
/cadastro_frete/migrations/0005_auto_20211029_0205.py
# Generated by Django 3.0.8 on 2021-10-29 05:05 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cadastro_frete', '0004_auto_20211029_0032'), ] operations = [ migrations.AlterField( model_name='cadastrocliente', name='doc', field=models.CharField(max_length=18, unique=True), ), migrations.AlterField( model_name='cadastroempresa', name='doc', field=models.CharField(max_length=18, unique=True), ), ]
{"/cadastro_frete/views.py": ["/cadastro_frete/models.py", "/cadastro_frete/serializer.py"], "/cadastro_frete/admin.py": ["/cadastro_frete/models.py"], "/cadastro_frete/serializer.py": ["/cadastro_frete/models.py", "/cadastro_frete/validators.py"]}
17,386,253
guilhermegoesgarcia/API_REST_contratacao_de_frete
refs/heads/master
/cadastro_frete/views.py
from django.shortcuts import render from rest_framework import viewsets, filters from django_filters.rest_framework import DjangoFilterBackend from cadastro_frete.models import CadastroEmpresa, CadastroCliente, CadastroOferta, Lance from cadastro_frete.serializer import * # Create your views here. class CadastroEmpresa_ViewSet(viewsets.ModelViewSet): '''Exibindo todos os cadastros''' queryset = CadastroEmpresa.objects.all() serializer_class = CadastroEmpresa_Serializer class CadastroCliente_ViewSet(viewsets.ModelViewSet): queryset = CadastroCliente.objects.all() serializer_class = CadastroCliente_Serializer class CadastroOferta_ViewSet(viewsets.ModelViewSet): queryset = CadastroOferta.objects.all() serializer_class = CadastroOferta_Serializer class Lance_ViewSet(viewsets.ModelViewSet): queryset = Lance.objects.all() serializer_class = Lance_Serializer
{"/cadastro_frete/views.py": ["/cadastro_frete/models.py", "/cadastro_frete/serializer.py"], "/cadastro_frete/admin.py": ["/cadastro_frete/models.py"], "/cadastro_frete/serializer.py": ["/cadastro_frete/models.py", "/cadastro_frete/validators.py"]}
17,386,254
guilhermegoesgarcia/API_REST_contratacao_de_frete
refs/heads/master
/cadastro_frete/migrations/0001_initial.py
# Generated by Django 3.0.8 on 2021-10-28 18:32 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='CadastroCliente', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(default='Sem_Nome_Cadastrado', max_length=50)), ('doc', models.CharField(max_length=14, unique=True)), ('about', models.CharField(max_length=250)), ('active', models.BooleanField()), ('site', models.CharField(max_length=100)), ], ), migrations.CreateModel( name='CadastroEmpresa', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(default='Sem_Nome_Cadastrado', max_length=50)), ('doc', models.CharField(max_length=14, unique=True)), ('about', models.CharField(max_length=250)), ('active', models.BooleanField()), ('site', models.CharField(max_length=100)), ], ), migrations.CreateModel( name='Lance', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('value', models.CharField(max_length=20)), ('amount', models.CharField(max_length=20)), ('id_offer', models.ForeignKey(default=1, on_delete=django.db.models.deletion.SET_DEFAULT, to='cadastro_frete.CadastroEmpresa')), ('id_provider', models.ForeignKey(default=1, on_delete=django.db.models.deletion.SET_DEFAULT, to='cadastro_frete.CadastroCliente')), ], ), migrations.CreateModel( name='CadastroOferta', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('from_de', models.CharField(max_length=20)), ('to_para', models.CharField(max_length=20)), ('initial_value', models.CharField(max_length=20)), ('amount', models.CharField(max_length=20)), ('amount_type', models.CharField(max_length=10)), ('id_customer', models.ForeignKey(default=1, on_delete=django.db.models.deletion.SET_DEFAULT, to='cadastro_frete.CadastroCliente')), ], ), ]
{"/cadastro_frete/views.py": ["/cadastro_frete/models.py", "/cadastro_frete/serializer.py"], "/cadastro_frete/admin.py": ["/cadastro_frete/models.py"], "/cadastro_frete/serializer.py": ["/cadastro_frete/models.py", "/cadastro_frete/validators.py"]}
17,386,255
guilhermegoesgarcia/API_REST_contratacao_de_frete
refs/heads/master
/cadastro_frete/apps.py
from django.apps import AppConfig class CadastroFreteConfig(AppConfig): name = 'cadastro_frete'
{"/cadastro_frete/views.py": ["/cadastro_frete/models.py", "/cadastro_frete/serializer.py"], "/cadastro_frete/admin.py": ["/cadastro_frete/models.py"], "/cadastro_frete/serializer.py": ["/cadastro_frete/models.py", "/cadastro_frete/validators.py"]}
17,386,256
guilhermegoesgarcia/API_REST_contratacao_de_frete
refs/heads/master
/cadastro_frete/models.py
from django.db import models # Create your models here. class CadastroEmpresa(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50, default='Sem_Nome_Cadastrado') doc = models.CharField(max_length=18, unique=True, blank=False) about = models.CharField(max_length=250) active = models.BooleanField() site = models.CharField(max_length=100) objects = models.Manager() def __str__(self): return str(self.id) class CadastroCliente(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50, default='Sem_Nome_Cadastrado') doc = models.CharField(max_length=18, unique=True, blank=False) about = models.CharField(max_length=250) active = models.BooleanField() site = models.CharField(max_length=100) objects = models.Manager() def __str__(self): return str(self.id) class CadastroOferta(models.Model): id_customer = models.ForeignKey(CadastroCliente, on_delete=models.SET_DEFAULT,default=1) # mudar para ID from_de = models.CharField(max_length=20, blank=False) to_para = models.CharField(max_length=20, blank=False) initial_value = models.FloatField(max_length=20) amount = models.FloatField(max_length=20) amount_type = models.CharField(max_length=10, blank=False) objects = models.Manager() def __str__(self): return self.from_de #mudar para id class Lance(models.Model): id_provider = models.ForeignKey(CadastroCliente, on_delete=models.SET_DEFAULT,default=1) #mudar para ID id_offer = models.ForeignKey(CadastroEmpresa, on_delete=models.SET_DEFAULT,default=1) #mudar para ID value = models.FloatField(max_length=20) amount = models.FloatField(max_length=20) objects = models.Manager() def __str__(self): return self.value
{"/cadastro_frete/views.py": ["/cadastro_frete/models.py", "/cadastro_frete/serializer.py"], "/cadastro_frete/admin.py": ["/cadastro_frete/models.py"], "/cadastro_frete/serializer.py": ["/cadastro_frete/models.py", "/cadastro_frete/validators.py"]}
17,386,257
guilhermegoesgarcia/API_REST_contratacao_de_frete
refs/heads/master
/cadastro_frete/migrations/0007_auto_20211029_0212.py
# Generated by Django 3.0.8 on 2021-10-29 05:12 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cadastro_frete', '0006_auto_20211029_0209'), ] operations = [ migrations.AlterField( model_name='lance', name='amount', field=models.CharField(max_length=20), ), ]
{"/cadastro_frete/views.py": ["/cadastro_frete/models.py", "/cadastro_frete/serializer.py"], "/cadastro_frete/admin.py": ["/cadastro_frete/models.py"], "/cadastro_frete/serializer.py": ["/cadastro_frete/models.py", "/cadastro_frete/validators.py"]}
17,410,091
topi-chan/Misc_projects
refs/heads/main
/projekt_bazy1.py
from sa3 import * db1 = SqlAlchemyCreate('postgresql://maciek:password@localhost/moja_baza', "dostawca") db1.sql_create_5col_cstr("id_producenta", Integer, "nazwa_producenta", String, "adres_producenta", String, "nip_producenta", Integer, "data", String, ) db2 = SqlAlchemyCreate('postgresql://maciek:password@localhost/moja_baza', "produkt") db2.sql_create_9col_cstr("id_produktu", Integer, "nazwa_producenta", String, "nazwa_produktu", String, "opis_produktu", String, "cena_netto", Integer, "cena_brutto", Integer, "netto_sprzedaz", Integer, "brutto_sprzedaz", Integer, "procent_vat_sprzedazy", Integer) db3 = SqlAlchemyCreate('postgresql://maciek:password@localhost/moja_baza', "zamówienie") db3.sql_create_4col_cstr("id_zamówienia", Integer, "id_klienta", Integer, "id_produktu", Integer, "data_zamówienia", String) db4 = SqlAlchemyCreate('postgresql://maciek:password@localhost/moja_baza', "klient") db4.sql_create_5col_cstr_2("id_klienta", Integer, "id_zamówienia", Integer, "imię", String, "nazwisko", String, "adres", String) db5 = SqlAlchemyWrite('postgresql+psycopg2://maciek:password@localhost/moja_baza', """INSERT INTO dostawca(id_producenta, nazwa_producenta, adres_producenta, nip_producenta, data) VALUES(:id_producenta, :nazwa_producenta, :adres_producenta, :nip_producenta, :data)""") data = ({"id_producenta": 1, "nazwa_producenta": "kopex", "adres_producenta": "Jara 21B Libiąż", "nip_producenta": "74859", "data": "2020-11-01"}, {"id_producenta": 2, "nazwa_producenta": "Jarex", "adres_producenta": "Wola 2 Warszawa", "nip_producenta": "8939", "data": "2020-12-01"}, {"id_producenta": 3, "nazwa_producenta": "Top_projekt", "adres_producenta": "Wolnego 4/8 Katowice", "nip_producenta": "6342", "data": "2014-12-22"}, {"id_producenta": 4, "nazwa_producenta": "Bolex", "adres_producenta": "Walicka 23 Kraków", "nip_producenta": "9453", "data": "2017-03-04"}) db5.sql_write(data) db6 = SqlAlchemyWrite('postgresql://maciek:password@localhost/moja_baza', """INSERT INTO produkt(id_produktu, nazwa_producenta, nazwa_produktu, opis_produktu, cena_netto, cena_brutto, netto_sprzedaz, brutto_sprzedaz, procent_vat_sprzedazy) VALUES(:id_produktu, :nazwa_producenta, :nazwa_produktu, :opis_produktu, :cena_netto, :cena_brutto, :netto_sprzedaz, :brutto_sprzedaz, :procent_VAT_sprzedazy)""") data = ({"id_produktu": 1, "nazwa_producenta": "kopex", "nazwa_produktu": "Skarpety", "opis_produktu": "piękne, różowe", "cena_netto": 8, "cena_brutto": 9, "netto_sprzedaz": 10, "brutto_sprzedaz": 10, "procent_VAT_sprzedazy": 23}, {"id_produktu": 2, "nazwa_producenta": "kopex", "nazwa_produktu": "Podkolanówki", "opis_produktu": "dla dziewcząt", "cena_netto": 4, "cena_brutto": 5, "netto_sprzedaz": 6, "brutto_sprzedaz": 6, "procent_VAT_sprzedazy": 23}, {"id_produktu": 3, "nazwa_producenta": "kopex", "nazwa_produktu": "Czapeczka", "opis_produktu": "z pomponem", "cena_netto": 13, "cena_brutto": 16, "netto_sprzedaz": 19, "brutto_sprzedaz": 21, "procent_VAT_sprzedazy": 23}, {"id_produktu": 4, "nazwa_producenta": "kopex", "nazwa_produktu": "Rajstopy czarne", "opis_produktu": "z ładnymi wzorkami", "cena_netto": 12, "cena_brutto": 14, "netto_sprzedaz": 15, "brutto_sprzedaz": 15, "procent_VAT_sprzedazy": 23}, {"id_produktu": 5, "nazwa_producenta": "kopex", "nazwa_produktu": "Stringi", "opis_produktu": "Wąskie!", "cena_netto": 25, "cena_brutto": 33, "netto_sprzedaz": 45, "brutto_sprzedaz": 49, "procent_VAT_sprzedazy": 23}, {"id_produktu": 6, "nazwa_producenta": "Top_projekt", "nazwa_produktu": "Program do obsługi księgowości", "opis_produktu": "webowy", "cena_netto": 150, "cena_brutto": 175, "netto_sprzedaz": 250, "brutto_sprzedaz": 290, "procent_VAT_sprzedazy": 23}, {"id_produktu": 7, "nazwa_producenta": "Top_projekt", "nazwa_produktu": "Model Machine Learning", "opis_produktu": "ubogi", "cena_netto": 2, "cena_brutto": 3, "netto_sprzedaz": 4, "brutto_sprzedaz": 4, "procent_VAT_sprzedazy": 8}, {"id_produktu": 8, "nazwa_producenta": "Top_projekt", "nazwa_produktu": "Analiza biznesowa", "opis_produktu": "zaawansowana", "cena_netto": 15000, "cena_brutto": 18500, "netto_sprzedaz": 20000, "brutto_sprzedaz": 20000, "procent_VAT_sprzedazy": 23}, {"id_produktu": 9, "nazwa_producenta": "Top_projekt", "nazwa_produktu": "Szalik", "opis_produktu": "ręcznie wyszywany", "cena_netto": 20, "cena_brutto": 30, "netto_sprzedaz": 35, "brutto_sprzedaz": 40, "procent_VAT_sprzedazy": 23}, {"id_produktu": 10, "nazwa_producenta": "Jarex", "nazwa_produktu": "Bluza", "opis_produktu": "z kapturem, mroczna", "cena_netto": 120, "cena_brutto": 148, "netto_sprzedaz": 179, "brutto_sprzedaz": 199, "procent_VAT_sprzedazy": 23}, {"id_produktu": 11, "nazwa_producenta": "Jarex", "nazwa_produktu": "Spodnie", "opis_produktu": "jeansowe, klimatyczne", "cena_netto": 130, "cena_brutto": 160, "netto_sprzedaz": 200, "brutto_sprzedaz": 229, "procent_VAT_sprzedazy": 23}, {"id_produktu": 12, "nazwa_producenta": "Jarex", "nazwa_produktu": "Koszulka", "opis_produktu": "t-shirt z pulp fiction", "cena_netto": 20, "cena_brutto": 33, "netto_sprzedaz": 58, "brutto_sprzedaz": 79, "procent_VAT_sprzedazy": 23}, {"id_produktu": 13, "nazwa_producenta": "Jarex", "nazwa_produktu": "Spodenki", "opis_produktu": "krótkie dla dziewczyny", "cena_netto": 40, "cena_brutto": 56, "netto_sprzedaz": 74, "brutto_sprzedaz": 89, "procent_VAT_sprzedazy": 23}, {"id_produktu": 14, "nazwa_producenta": "Jarex", "nazwa_produktu": "Sweterek", "opis_produktu": "czerwony", "cena_netto": 70, "cena_brutto": 90, "netto_sprzedaz": 110, "brutto_sprzedaz": 139, "procent_VAT_sprzedazy": 23}, {"id_produktu": 15, "nazwa_producenta": "Jarex", "nazwa_produktu": "Piżama", "opis_produktu": "zwykła", "cena_netto": 15, "cena_brutto": 20, "netto_sprzedaz": 25, "brutto_sprzedaz": 30, "procent_VAT_sprzedazy": 23}, {"id_produktu": 16, "nazwa_producenta": "Jarex", "nazwa_produktu": "Pullover", "opis_produktu": "coś to jest", "cena_netto": 20, "cena_brutto": 30, "netto_sprzedaz": 35, "brutto_sprzedaz": 40, "procent_VAT_sprzedazy": 23}, {"id_produktu": 17, "nazwa_producenta": "Jarex", "nazwa_produktu": "Koszula", "opis_produktu": "wyjściowa w kropki", "cena_netto": 40, "cena_brutto": 55, "netto_sprzedaz": 75, "brutto_sprzedaz": 85, "procent_VAT_sprzedazy": 23}, {"id_produktu": 18, "nazwa_producenta": "Jarex", "nazwa_produktu": "Dresy", "opis_produktu": "różowe podomki", "cena_netto": 20, "cena_brutto": 33, "netto_sprzedaz": 35, "brutto_sprzedaz": 44, "procent_VAT_sprzedazy": 23}, {"id_produktu": 19, "nazwa_producenta": "Jarex", "nazwa_produktu": "Gumka do włosów", "opis_produktu": "w czarne kropki", "cena_netto": 1, "cena_brutto": 2, "netto_sprzedaz": 3, "brutto_sprzedaz": 3, "procent_VAT_sprzedazy": 23}, {"id_produktu": 20, "nazwa_producenta": "Jarex", "nazwa_produktu": "Stanik", "opis_produktu": "sportowy, czarny", "cena_netto": 13, "cena_brutto": 15, "netto_sprzedaz": 137, "brutto_sprzedaz": 149, "procent_VAT_sprzedazy": 23}) db6.sql_write(data) db7 = SqlAlchemyWrite('postgresql://maciek:password@localhost/moja_baza', """INSERT INTO Zamówienie(id_zamówienia, id_produktu, id_klienta, data_zamówienia) VALUES(:id_zamówienia, :id_produktu, :id_klienta, :data_zamówienia)""") data = ({"id_zamówienia": 1, "id_produktu": 1, "id_klienta": 10, "data_zamówienia": "22-12-2020"}, {"id_zamówienia": 2, "id_produktu": 12, "id_klienta": 9, "data_zamówienia": "03-03-2020"}, {"id_zamówienia": 3, "id_produktu": 20, "id_klienta": 8, "data_zamówienia": "16-12-2020"}, {"id_zamówienia": 4, "id_produktu": 5, "id_klienta": 7, "data_zamówienia": "04-06-2020"}, {"id_zamówienia": 5, "id_produktu": 11, "id_klienta": 6, "data_zamówienia": "25-04-2020"}, {"id_zamówienia": 6, "id_produktu": 5, "id_klienta": 5, "data_zamówienia": "03-06-2020"}, {"id_zamówienia": 7, "id_produktu": 7, "id_klienta": 4, "data_zamówienia": "17-08-2020"}, {"id_zamówienia": 8, "id_produktu": 3, "id_klienta": 3, "data_zamówienia": "21-10-2020"}, {"id_zamówienia": 9, "id_produktu": 17, "id_klienta": 2, "data_zamówienia": "01-05-2020"}, {"id_zamówienia": 10, "id_produktu": 12, "id_klienta": 1, "data_zamówienia": "22-09-2020"}) db7.sql_write(data) db8 = SqlAlchemyWrite('postgresql://maciek:password@localhost/moja_baza', """INSERT INTO Klient(id_klienta, id_zamówienia, imię, nazwisko, adres) VALUES(:id_klienta, :id_zamówienia, :imię, :nazwisko, :adres)""") data = ({"id_klienta": 1, "id_zamówienia": 10, "imię": "Maciej", "nazwisko": "Nowicki", "adres": "Ul. Jabłonia 8/2 Malbork"}, {"id_klienta": 2, "id_zamówienia": 9, "imię": "Robert", "nazwisko": "Marecki", "adres": "Ul. Hryszczata 12 Pilzno"}, {"id_klienta": 3, "id_zamówienia": 8, "imię": "Magdalena", "nazwisko": "Moj", "adres": "Ul. Górki 1/2 Nowa Sól"}, {"id_klienta": 4, "id_zamówienia": 7, "imię": "Kasia", "nazwisko": "Kalicka", "adres": "Al. Stanisławska 1 Kluczbork"}, {"id_klienta": 5, "id_zamówienia": 6, "imię": "Wojciech", "nazwisko": "Wojerz", "adres": "Ul. Kalety 8/2 Warszawa"}, {"id_klienta": 6, "id_zamówienia": 5, "imię": "Maciej", "nazwisko": "Nowak", "adres": "Ul. Ułańska 16/19 Katowice"}, {"id_klienta": 7, "id_zamówienia": 4, "imię": "Patryk", "nazwisko": "Jakiś", "adres": "Ul. Więzienna 19/0 Warszawa"}, {"id_klienta": 8, "id_zamówienia": 3, "imię": "Tomasz", "nazwisko": "Zawadzki", "adres": "Ul. Chrobrego 12/1 Katowice"}, {"id_klienta": 9, "id_zamówienia": 2, "imię": "Jarosław", "nazwisko": "Kaszanka", "adres": "Ul. Mięsna 1 Bytom"}, {"id_klienta": 10, "id_zamówienia": 1, "imię": "Eliza", "nazwisko": "Malicka", "adres": "Ul. Krucza 12 Zwardoń"}) db8.sql_write(data) db9 = SqlAlchemyWrite('postgresql://maciek:password@localhost/moja_baza', """ALTER TABLE zamówienie ADD FOREIGN KEY (id_produktu) REFERENCES Produkt(id_produktu)""") db9.sql_any() db10 = SqlAlchemyWrite('postgresql://maciek:password@localhost/moja_baza', """ALTER TABLE dostawca ADD id_produktu Integer""") db10.sql_any() db11 = SqlAlchemyWrite('postgresql://maciek:password@localhost/moja_baza', """ALTER TABLE dostawca ADD FOREIGN KEY (id_produktu) REFERENCES Produkt(id_produktu)""") db11.sql_any() db12 = SqlAlchemyWrite('postgresql://maciek:password@localhost/moja_baza', """select * from dostawca where id_producenta = 1""") db12.sql_any_print() db13 = SqlAlchemyWrite('postgresql://maciek:password@localhost/moja_baza', "select * from produkt where nazwa_producenta = 'kopex' ORDER BY nazwa_produktu") db13.sql_any_print() db14 = SqlAlchemyWrite('postgresql://maciek:password@localhost/moja_baza', "select AVG(cena_netto) from produkt where nazwa_producenta = 'kopex'") db14.sql_any_print() db15 = SqlAlchemyWrite('postgresql://maciek:password@localhost/moja_baza', "select AVG(cena_netto) from produkt where nazwa_producenta = 'kopex'") db15.sql_any_print() db16 = SqlAlchemyCreate('postgresql://maciek:password@localhost/moja_baza', "tani_produkt") db16.sql_create_9col_cstr("id_produktu", Integer, "nazwa_producenta", String, "nazwa_produktu", String, "opis_produktu", String, "cena_netto", Integer, "cena_brutto", Integer, "netto_sprzedaz", Integer, "brutto_sprzedaz", Integer, "procent_vat_sprzedazy", Integer) db17 = SqlAlchemyCreate('postgresql://maciek:password@localhost/moja_baza', "drogi_produkt") db17.sql_create_9col_cstr("id_produktu", Integer, "nazwa_producenta", String, "nazwa_produktu", String, "opis_produktu", String, "cena_netto", Integer, "cena_brutto", Integer, "netto_sprzedaz", Integer, "brutto_sprzedaz", Integer, "procent_vat_sprzedazy", Integer) db18 = SqlAlchemyWrite('postgresql://maciek:password@localhost/moja_baza', ''' select * from produkt left join public.tani_produkt ON produkt.id_produktu = tani_produkt.id_produktu where produkt.cena_netto > 12.4 ORDER BY produkt.id_produktu ''') db18.sql_any_print() db19 = SqlAlchemyWrite('postgresql://maciek:password@localhost/moja_baza', ''' select * from produkt Left JOIN public.drogi_produkt ON produkt.id_produktu = drogi_produkt.id_produktu where produkt.cena_netto >= 12.4 ORDER BY produkt.id_produktu ''') db19.sql_any_print() db20 = SqlAlchemyWrite('postgresql://maciek:password@localhost/moja_baza', """ select nazwa_produktu from produkt inner join zamówienie on produkt.id_produktu = zamówienie.id_produktu limit 5 """) db20.sql_any_print() db21 = SqlAlchemyWrite('postgresql://maciek:password@localhost/moja_baza', """ select sum(cena_netto) from produkt inner join zamówienie on produkt.id_produktu = zamówienie.id_produktu limit 5 """) db21.sql_any_print() db22 = SqlAlchemyWrite('postgresql://maciek:password@localhost/moja_baza', """ select * from produkt inner join zamówienie on produkt.id_produktu = zamówienie.id_produktu limit 5 """) db22.sql_any_print() #nie wiem jak zadeklarować datę w słowniku przy tworzeniu tablicy w sqlalchemy. #wskazanie stringa nie działa, a nie przypiszę trzech liczb do wartości w dict. db23 = SqlAlchemyWrite('postgresql://maciek:password@localhost/moja_baza', """ alter table zamówienie ADD data DATE """) db23.sql_any() db24 = SqlAlchemyWrite('postgresql://maciek:password@localhost/moja_baza', """ update zamówienie set data = '2011-11-02' where id_zamówienia = 1 """) db24.sql_any() db25 = SqlAlchemyWrite('postgresql://maciek:password@localhost/moja_baza', """ update zamówienie set data = '2019-11-06' where id_zamówienia = 2 """) db25.sql_any() db26 = SqlAlchemyWrite('postgresql://maciek:password@localhost/moja_baza', """ update zamówienie set data = '2021-03-26' where id_zamówienia = 3 """) db26.sql_any() db27 = SqlAlchemyWrite('postgresql://maciek:password@localhost/moja_baza', """ update zamówienie set data = '2021-04-02' where id_zamówienia = 4 """) db27.sql_any() db28 = SqlAlchemyWrite('postgresql://maciek:password@localhost/moja_baza', """ update zamówienie set data = '2020-12-21' where id_zamówienia = 5 """) db28.sql_any() db29 = SqlAlchemyWrite('postgresql://maciek:password@localhost/moja_baza', """ update zamówienie set data = '2021-01-21' where id_zamówienia = 6 """) db29.sql_any() db30 = SqlAlchemyWrite('postgresql://maciek:password@localhost/moja_baza', """ update zamówienie set data = '2018-10-01' where id_zamówienia = 7 """) db30.sql_any() db31 = SqlAlchemyWrite('postgresql://maciek:password@localhost/moja_baza', """ update zamówienie set data = '2021-02-26' where id_zamówienia = 8 """) db31.sql_any() db32 = SqlAlchemyWrite('postgresql://maciek:password@localhost/moja_baza', """ update zamówienie set data = '2021-01-26' where id_zamówienia = 9 """) db32.sql_any() db33 = SqlAlchemyWrite('postgresql://maciek:password@localhost/moja_baza', """ update zamówienie set data = '2020-07-14' where id_zamówienia = 10 """) db33.sql_any() db34 = SqlAlchemyWrite('postgresql://maciek:password@localhost/moja_baza', """ select * from produkt inner join zamówienie on produkt.id_produktu = zamówienie.id_produktu order by data """) db34.sql_any_print() db35 = SqlAlchemyWrite('postgresql://maciek:password@localhost/moja_baza', """ SELECT * FROM produkt WHERE id_produktu IS NULL OR nazwa_producenta IS NULL OR nazwa_produktu IS null OR opis_produktu IS NULL OR cena_netto IS null OR cena_brutto IS null OR netto_sprzedaz IS NULL OR brutto_sprzedaz IS null OR procent_vat_sprzedazy IS NULL """) db35.sql_any_print() db36 = SqlAlchemyWrite('postgresql://maciek:password@localhost/moja_baza', """ select * from produkt inner join zamówienie on produkt.id_produktu = zamówienie.id_produktu order by data """) db36.sql_any_print() db37 = SqlAlchemyWrite('postgresql://maciek:password@localhost/moja_baza', """ select produkt.nazwa_produktu, produkt.cena_brutto, count(produkt.id_produktu) from produkt inner join zamówienie on produkt.id_produktu = zamówienie.id_produktu group by produkt.id_produktu, zamówienie.id_zamówienia ORDER BY COUNT(produkt.id_produktu) desc """) db37.sql_any_print() db38 = SqlAlchemyWrite('postgresql://maciek:password@localhost/moja_baza', """ select produkt.nazwa_produktu, produkt.cena_brutto, count(zamówienie.data) from produkt inner join zamówienie on produkt.id_produktu = zamówienie.id_produktu group by produkt.id_produktu, zamówienie.id_zamówienia ORDER BY COUNT(zamówienie.data) desc """) db38.sql_any_print()
{"/projekt_bazy1.py": ["/sa3.py"]}
17,410,092
topi-chan/Misc_projects
refs/heads/main
/second_preprocessing_ML_credit.py
import pandas as pd import numpy as np import csv from credit_scoring_ML import print_description from credit_scoring_ML import check_consistency data = pd.read_csv('credit_scoring_for_model.csv') for col in data.columns: print(col) data.applymap(np.isreal) only_num_series = data.select_dtypes(include=np.number).columns.tolist() all_series = [] for col in data.columns: all_series.append(col) non_num_series = set(only_num_series) ^ set(all_series) #still non numeric: {'earliest_cr_line', 'int_rate', 'issue_d', 'last_credit_pull_d', 'last_pymnt_d', 'loan_status', 'revol_util'} #int rate is percent, rest is date non_num_list = [item for item in all_series if item not in only_num_series] non_num_list print_description(non_num_list) data['int_rate'].dtype data['int_rate'] = data['int_rate'].astype('string') data['int_rate'].dtype for i, row in data['int_rate'].iteritems(): row_value = row.replace('%', '') data.at[i, 'int_rate'] = row_value data['int_rate'] = data['int_rate'].astype('float') data['int_rate'].mean() data['int_rate'].median() data['int_rate'].std() data['issue_d'].head(n=25) check_consistency('issue_d', '2011-12-01', '2011-11-01') #column is consisted and seems sorted - is this data necessary? data['loan_status'] #!!column to be predicted! data['earliest_cr_line'].head(n=25) df_descr = pd.read_csv('LCDataDictionary.csv') df_descr.loc[18, 'Description'] df_descr.loc[91, 'Description'] data['revol_util'].head(n=25) #! it's very important factor!/ usage of credit ratio data['revol_util'] = data['revol_util'].astype('string') data['revol_util'].dtype data['revol_util'].isnull().values.any() data['revol_util'].isna().sum() data.sum(axis=1) data.dropna(subset=['revol_util'], inplace=True) data.sum(axis=1) #dropped empty, since it's important factor for prediction and empty columns #number was not substantial for i, row in data['revol_util'].iteritems(): row_value = row.replace('%', '') data.at[i, 'revol_util'] = row_value data['revol_util'] = data['revol_util'].astype('float') data['revol_util'].dtype #I do not see the point of calculating every instance of month on which credit #was granted, last payment made etc. since it's too complicated for not enough #profit - drop only_num_series = data.select_dtypes(include=np.number).columns.tolist() all_series = [] for col in data.columns: all_series.append(col) non_num_series = set(only_num_series) ^ set(all_series) non_num_series data.drop(axis=1, labels=['earliest_cr_line', 'int_rate', 'issue_d', 'last_credit_pull_d', 'last_pymnt_d', 'loan_status', 'revol_util'], inplace=True) #export preprocessed file data.to_csv(r'credit_scoring_for_model_final.csv') #if needed for module export data
{"/projekt_bazy1.py": ["/sa3.py"]}
17,410,093
topi-chan/Misc_projects
refs/heads/main
/sa3.py
import sqlalchemy from sqlalchemy import Table, Column, Integer, String, create_engine from sqlalchemy import MetaData, ForeignKey, inspect, delete from sqlalchemy.sql import text class SqlAlchemyCreate(): """Allows to write a simple table; put database type/name in 'engine'""" def __init__(self, engine, table_name): self.engine = engine self.table_name = table_name def sql_create_test(self): metadata = MetaData() users = Table(self.table_name, metadata, Column('id', Integer)) engine = create_engine(self.engine) metadata.create_all(engine) def sql_create_3col(self, column1, column2, type1, type2): metadata = MetaData() books = Table(self.table_name, metadata, Column('id', Integer), Column(column1, type1), Column(column2, type2), ) engine = create_engine(self.engine) metadata.create_all(engine) def sql_create_4col_cstr(self, column1, type1, column2, type2, column3, type3, column4, type4): metadata = MetaData() books = Table(self.table_name, metadata, Column(column1, type1, primary_key=True, unique=True), Column(column2, type2, nullable=True), Column(column3, type3, nullable=True), Column(column4, type4, nullable=True), ) engine = create_engine(self.engine) metadata.create_all(engine) def sql_create_5col_cstr(self, column1, type1, column2, type2, column3, type3, column4, type4, column5, type5): metadata = MetaData() books = Table(self.table_name, metadata, Column(column1, type1, primary_key=True), Column(column2, type2, nullable=False), Column(column3, type3, unique=True), Column(column4, type4, nullable=True), Column(column5, type5, nullable=True), ) engine = create_engine(self.engine) metadata.create_all(engine) def sql_create_5col_cstr_2(self, column1, type1, column2, type2, column3, type3, column4, type4, column5, type5): metadata = MetaData() books = Table(self.table_name, metadata, Column(column1, type1, primary_key=True), Column(column2, type2, nullable=True), Column(column3, type3, nullable=True), Column(column4, type4, nullable=True), Column(column5, type5, nullable=True), ) engine = create_engine(self.engine) metadata.create_all(engine) def sql_create_6col(self, column1, type1, column2, type2, column3, type3, column4, type4, column5, type5, column6, type6): metadata = MetaData() books = Table(self.table_name, metadata, Column(column1, type1), Column(column2, type2), Column(column3, type3), Column(column4, type4), Column(column5, type5), Column(column6, type6), ) engine = create_engine(self.engine) metadata.create_all(engine) def sql_create_9col_cstr(self, column1, type1, column2, type2, column3, type3, column4, type4, column5, type5, column6, type6, column7, type7, column8, type8, column9, type9): metadata = MetaData() books = Table(self.table_name, metadata, Column(column1, type1, primary_key=True), Column(column2, type2, unique=False), Column(column3, type3, nullable=False), Column(column4, type4, nullable=True), Column(column5, type5, nullable=True), Column(column6, type6, nullable=True), Column(column7, type7, nullable=True), Column(column8, type8, nullable=True), Column(column9, type9, nullable=True), ) engine = create_engine(self.engine) metadata.create_all(engine) class SqlAlchemyWrite(): """Allows to pass a command into a database; put database type/name in 'engine'""" def __init__(self, engine, command): self.engine = engine self.command = command def sql_write(self, data): engine = create_engine(self.engine) with engine.connect() as con: statement = text(self.command) for line in data: con.execute(statement, **line) def sql_any(self): engine = create_engine(self.engine) with engine.connect() as con: rs = con.execute(self.command) def sql_any_print(self): engine = create_engine(self.engine) with engine.connect() as con: rs = con.execute(self.command) for row in rs: print(row) # # # def sql_delete(col_id): # engine = create_engine('sqlite:///Lista Prezentów.db') # with engine.connect() as con: # table = 'Prezenty_2020' # table.delete().where(table.c.name==col_id)
{"/projekt_bazy1.py": ["/sa3.py"]}
17,410,094
topi-chan/Misc_projects
refs/heads/main
/credit_scoring_ML.py
import pandas as pd import numpy as np import seaborn as sns from sklearn import preprocessing import matplotlib import sklearn import csv import random import statistics import re df = pd.read_csv('Loan_data.csv') empty_col = [] for col in df.columns: pct_missing = np.mean(df[col].isnull()) print('{} - {}%'.format(col, round(pct_missing*100))) if pct_missing == 1: empty_col.append(col) print(empty_col) df.head() cols = df.columns colours = ['#000099', '#ffff00'] # yellow is missing. blue is not missing sns.heatmap(df[cols].isnull(), cmap=sns.color_palette(colours)) df_minus_empty_col = df.drop(empty_col, axis=1) print(df_minus_empty_col.head(n=20)) def empty_check(df_instance): almost_empty_col = [] for col in df_instance.columns: pct_missing = np.mean(df[col].isnull()) value = float(np.mean(df[col].isnull())) print('{} - {}%'.format(col, round(pct_missing*100))) if round(pct_missing) == 1: almost_empty_col.append(col), almost_empty_col.append(value) print(almost_empty_col) return almost_empty_col almost_empty_col = empty_check(df_minus_empty_col) df = df_minus_empty_col df_descr = pd.read_csv('LCDataDictionary.csv') df_descr[df_descr.columns[:2]].head(n=10) df_descr.drop(df_descr.columns[2:], axis=1, inplace=True) df_descr.head() df_descr.iloc[:1] for col in df_descr.columns: print(col) def print_description(col_name_list): loc = [] for element in col_name_list: loc.append(df_descr.index[df_descr['LoanStatNew'] == element].tolist()) for l in loc: print(df_descr.loc[l, 'Description']) if __name__ == '__main__': print_description(col_name_list) print_description(almost_empty_col) df_descr.loc[50, 'Description'] df_descr.loc[52, 'Description'] df_descr.loc[58, 'Description'] df_descr.loc[145, 'Description'] df_descr.loc[146, 'Description'] df_descr.loc[147, 'Description'] df_descr.loc[148, 'Description'] df_descr.loc[149, 'Description'] df_descr.loc[150, 'Description'] # for l in loc: # print(df_descr.loc[l, 'LoanStatNew']) df['mths_since_last_delinq'].head() df['mths_since_last_delinq'].mean() df['mths_since_last_delinq'].median() df['mths_since_last_delinq'].max() df['mths_since_last_delinq'].quantile([0.25, 0.5, 0.75]) df['mths_since_last_delinq'] = pd.qcut(df ['mths_since_last_delinq'].values, q=10).codes+1 df['mths_since_last_delinq'] = df['mths_since_last_delinq'].replace(to_replace=0, value=20) df['mths_since_last_delinq'].head(n=25) df['mths_since_last_record'].head() df['mths_since_last_record'].mean() df['mths_since_last_record'].median() df['mths_since_last_record'].max() df['mths_since_last_record'].quantile([0.25, 0.5, 0.75]) df['mths_since_last_record'] = pd.qcut(df['mths_since_last_record'].values, q=10, duplicates='drop').codes+1 df['mths_since_last_record'] = df['mths_since_last_record'].replace(to_replace=0, value=20) df['mths_since_last_record'].mean() df = df.drop(['next_pymnt_d', 'debt_settlement_flag_date', 'settlement_status', 'debt_settlement_flag_date', 'settlement_date', 'settlement_amount', 'settlement_percentage', 'settlement_term'], axis=1) cols = df.columns[:30] colours = ['#000099', '#ffff00'] # yellow is missing. blue is not missing sns.heatmap(df[cols].isnull(), cmap=sns.color_palette(colours)) df['desc'].head() df.loc[random.randrange(1, 40520), 'desc'] # borrowers with description seems more reliable, as they care enough to provide # valid reason for taking a loan; let's try to assign value up to 1 to borrowers # with description and 0 to ones with no description. # (assuming the description avaibility depends on the lender, but stil we can # analyse description lenght) max_str_len = 0 sum_str_len = 0 list_for_median = [] for row in df['desc']: row = str(row) row_len = len(row) sum_str_len += row_len list_for_median.append(row_len) if row_len > max_str_len: max_str_len = len(row) print(max_str_len) sum_str_len mean_str_len = sum_str_len / 40520 print(mean_str_len) str_median_len = statistics.median(list_for_median) print(str_median_len) for i, row in df['desc'].iteritems(): row = str(row) row_len = len(row) if row_len == 0: row_value = 0 elif row_len <= str_median_len: row_value = 0.5 elif row_len <= mean_str_len: row_value = 0.75 else: row_value = 1 df.at[i, 'desc'] = row_value df['desc'].head(n=15) cols = df.columns[29:] colours = ['#000099', '#ffff00'] # yellow is missing. blue is not missing sns.heatmap(df[cols].isnull(), cmap=sns.color_palette(colours)) empty_check(df) df.loc[random.randrange(1, 40520), 'emp_title'] df.loc[random.randrange(1, 40520), 'emp_length'] emp_col = ['emp_title', 'emp_length'] print_description(emp_col) df_descr.loc[20, 'Description'] df_descr.loc[19, 'Description'] for i, row in df['emp_length'].iteritems(): row = str(row) if re.search("10", row): emp_lenght_value = 10 elif re.findall("[1-9]", row): re_list = (re.findall("[1-9]", row)) emp_lenght_value = int(re_list.pop(0)) else: emp_lenght_value = 0 df.at[i, 'emp_length'] = emp_lenght_value df['emp_length'].head(n=25) df = df.drop(['emp_title'], axis=1) empty_check(df) df.loc[random.randrange(1, 40520), 'pub_rec_bankruptcies'] print_description(['pub_rec_bankruptcies']) df['pub_rec_bankruptcies'] = df['pub_rec_bankruptcies'].fillna( df['pub_rec_bankruptcies'].mean()) empty_check(df) df['pub_rec_bankruptcies'].head(n=15) # check if dataframe contains only numeric values def numeric_check(): str_elem = df.apply(lambda s: pd.to_numeric(s, errors='coerce').notnull().all()) only_numeric_elements = [] for i, row in str_elem.iteritems(): row = str(row) if row == 'False': only_numeric_elements.append(i) print(only_numeric_elements) if __name__ == '__main__': numeric_check() numeric_check() df['id'].head(n=25) df.applymap(lambda x: isinstance(x, (int, float))) # these for which to_numeric returned true df['id'] df['desc'] df['mths_since_last_delinq'] df['mths_since_last_record'] df['pub_rec_bankruptcies'] df.head(n=2) for i, row in df['id'].iteritems(): try: row = int(row) except: print(i, row) df = df.drop(39786) numeric_check() def check_non_num_rows(col_name): for i, row in df[col_name].iteritems(): try: row = int(row) except: print(i, row) if __name__ == '__main__': check_non_num_rows(col_name) check_non_num_rows('term') def check_consistency(column, *phrases): for i, row in df[column].iteritems(): row = str(row) found = False for r in range(len(phrases)): if re.search(phrases[r], row): found = True if found != True: print(i, row) if __name__ == '__main__': check_consistency(column, *phrases) check_consistency('term', '36 months', '60 months') # change months into integers for i, row in df['term'].iteritems(): row = str(row) if re.search("36 months", row): term = 0 elif re.search("60 months", row): term = 1 df.at[i, 'term'] = term # 0 = 36 months; 1 = 60 months; no other value is present check_non_num_rows('int_rate') # change % into floats df['int_rate'].dtypes # for i, row in df['term'].iteritems(): # row = float(row) # print(row) # maybe this will suffice? as data is hardly converted here # TODO: check whether % values work with model check_non_num_rows('grade') # possibly leave it like that or change into integers for coherency and speed # let's use hot encoding. def hot_encoding(col): global df df = pd.concat([df.drop(col, axis=1), pd.get_dummies(df[col])], axis=1) return df df = hot_encoding('grade') df.head() check_non_num_rows('sub_grade') # as above df = hot_encoding('sub_grade') df.head() check_non_num_rows('home_ownership') # as above + check if there is any abbreviation from the rule # MORTGAGE OWN RENT check_consistency('home_ownership', 'MORTGAGE', 'OWN', 'RENT') df.at[39786, 'home_ownership'] = 'NONE' df = hot_encoding('home_ownership') check_non_num_rows('annual_inc') # set empty rows to mean or median or 0 or drop them # df['annual_inc'].head(n=25) # for i, row in df['annual_inc'].iteritems(): # if row == 0.00: # print(i, row) # df['annual_inc'].replace(to_replace=np.nan, value=0) # dropping is probably a better idea, since nan may be missing value and may # cloud a model df = df.drop(labels=[39786, 42450, 42451, 42481, 42534]) check_non_num_rows('verification_status') # check whether there are only 3 values and change them into integers check_consistency('verification_status', 'Not Verified', 'Verified', 'Source Verified') # ok! df = hot_encoding('verification_status') check_non_num_rows('issue_d') # change into dates / numbers df['issue_d'] = pd.to_datetime(df['issue_d']) df['issue_d'] = df['issue_d'].dt.date # changed into date, can it be properly understood by the model? check_non_num_rows('loan_status') # check whether there are only 2 values and change them into integers #!! this is value to be predicted by the model!! check_consistency('loan_status', 'Fully Paid', 'Charged Off') #df = df.drop(labels=39786) dropped one empty row before - useless for the model #df = hot_encoding('loan_status') - leave it! check_non_num_rows('pymnt_plan') # check if there is other value than "N" and if not - drop column check_consistency('pymnt_plan', 'n') df = df.drop(labels='pymnt_plan', axis=1) check_non_num_rows('url') # drop, seems irrelevant; also: url-s needs login, don't know if working df = df.drop(labels='url', axis=1) check_non_num_rows('purpose') # assign randomly generated numbers for 'purpose' items or clean and hot encoding row_list = [] for i, row in df['purpose'].iteritems(): row_list.append(row) list(set(row_list)) df['purpose'].fillna("other", inplace=True) check_consistency('purpose', 'major_purchase', 'home_improvement', 'debt_consolidation', 'wedding', 'small_business', 'house', 'renewable_energy', 'car', 'credit_card', 'medical', 'educational', 'moving', 'other', 'vacation') df = hot_encoding('purpose') check_non_num_rows('title') # many values - drop? title_series = df['title'].value_counts() title_series.head(n=55) title_series.head(n=55).sum() consolidation = personal = home = medical = wedding = bussines = other = 0 for i, row in df['title'].iteritems(): row = str(row) if re.search("consolidation", row, re.IGNORECASE): consolidation += 1 elif re.search("personal", row, re.IGNORECASE): personal += 1 elif re.search("home", row, re.IGNORECASE): home += 1 elif re.search("medical", row, re.IGNORECASE): medical += 1 elif re.search("wedding", row, re.IGNORECASE) or re.search("ring", row, re.IGNORECASE): wedding += 1 elif re.search("business", row, re.IGNORECASE): bussines += 1 else: other += 1 print(consolidation, personal, home, medical, wedding, bussines, other) sum = consolidation + personal + home + medical + wedding + bussines + other sum df['title'] df['title'].isnull().values.any() df['title'].isna().sum() df['title'].fillna("other", inplace=True) for i, row in df['title'].iteritems(): row = str(row) if re.search("consolidation", row, re.IGNORECASE): row_value = "consolidation" elif re.search("personal", row, re.IGNORECASE): row_value = "personal" elif re.search("home", row, re.IGNORECASE): row_value = "home" elif re.search("medical", row, re.IGNORECASE): row_value = "medical" elif re.search("wedding", row, re.IGNORECASE) or re.search("ring", row, re.IGNORECASE): row_value = "wedding" elif re.search("business", row, re.IGNORECASE): row_value = "bussines" else: row_value = "other" df.at[i, 'title'] = row_value df['title'].value_counts() df = hot_encoding('title') def generate_checklist(col): row_list = [] for i, row in df[col].iteritems(): row_list.append(row) print(list(set(row_list))) print(len(list(set(row_list)))) check_non_num_rows('zip_code') # drop the 'xx'? check if it's relevant at all generate_checklist('zip_code') # dunno what to do with it. 838 values but seems relevant. # choosen - label encoding, as number of variables is substantial. df['zip_code'] = preprocessing.LabelEncoder().fit_transform(df['zip_code']) df.head() check_non_num_rows('addr_state') # assign into numbers generate_checklist('addr_state') # label encoding or hot encoding? # TODO: choose encoding - atm: label encoding df['addr_state'] = preprocessing.LabelEncoder().fit_transform(df['addr_state']) check_non_num_rows('delinq_2yrs') df['delinq_2yrs'].head(n=35) # replace nan with median() value df['delinq_2yrs'] = df['delinq_2yrs'].fillna(df['delinq_2yrs'].median()) check_non_num_rows('earliest_cr_line') # change into dates df['earliest_cr_line'] = pd.to_datetime(df['earliest_cr_line']) df['earliest_cr_line'] = df['earliest_cr_line'].dt.date check_non_num_rows('inq_last_6mths') # it is important value; also there is a pattern - on last rows severas columns # are missing - let's drop them for consistency (but check other columns first) df.loc[42525] df.loc[42526] df = df.drop(df.index[42515:]) check_non_num_rows('open_acc') # replace nan with mean() value or drop last columns - repeating 'nan' pattern df['open_acc'].mean() df['open_acc'].median() df['open_acc'].std() df['open_acc'] = df['open_acc'].fillna(df['open_acc'].median()) check_non_num_rows('pub_rec') # as above # repeating pattern of missing values for some records, eg. 42450 - drop. df.drop(labels=[42460, 42473, 42484, 42495, 42510], inplace=True) check_non_num_rows('revol_util') # change % into floats # TODO: check for 'int_rate' and apply same rules check_non_num_rows('total_acc') # replace nan with mean() value or drop last columns - repeating 'nan' pattern df.drop(labels=[42515,42516,42517,42518], inplace=True) check_non_num_rows('initial_list_status') # investigate this column and its meaning for i, row in df['initial_list_status'].iteritems(): row = str(row) if row == "w": print(row) elif row != "f": print("Found something else!") df['initial_list_status'].value_counts() # column is "broken" - contains only 'f' values, hence is irrelevant df.drop(columns='initial_list_status', inplace=True) check_non_num_rows('last_pymnt_d') # change into dates / numbers? df['last_pymnt_d'] = pd.to_datetime(df['last_pymnt_d']) df['last_pymnt_d'] = df['last_pymnt_d'].dt.date check_non_num_rows('last_credit_pull_d') # as above df['last_credit_pull_d'] = pd.to_datetime(df['last_credit_pull_d']) df['last_credit_pull_d'] = df['last_credit_pull_d'].dt.date check_non_num_rows('collections_12_mths_ex_med') # replace nan with mean() value or drop last columns - repeating 'nan' pattern df['collections_12_mths_ex_med'].mean() df['collections_12_mths_ex_med'].median() df['collections_12_mths_ex_med'].std() df['collections_12_mths_ex_med'].sum() df['collections_12_mths_ex_med'] #empty column - drop df.drop(columns='collections_12_mths_ex_med', inplace=True) check_non_num_rows('application_type') # check if there is other than "individual" and if not - drop column generate_checklist('application_type') df.drop(columns='application_type', inplace=True) #no other value - drop check_non_num_rows('acc_now_delinq') # replace nan with mean() value or drop last columns - repeating 'nan' pattern #update: already solved by dropping above columns check_non_num_rows('chargeoff_within_12_mths') # replace nan with mean() value or drop last columns - repeating 'nan' pattern # or maybe a median() value df['chargeoff_within_12_mths'].mean() df['chargeoff_within_12_mths'].median() df['chargeoff_within_12_mths'].std() df['chargeoff_within_12_mths'] #either null or nan - drop df.drop(columns='chargeoff_within_12_mths', inplace=True) check_non_num_rows('delinq_amnt') # replace nan with mean() value or drop last columns - repeating 'nan' pattern #update: already solved by dropping above columns check_non_num_rows('tax_liens') # replace nan with mean() value or drop last columns - repeating 'nan' pattern df['tax_liens'].mean() df['tax_liens'].median() df['tax_liens'].std() #it seems like an important feature - keep the column, fix nan's df['tax_liens'].head(n=45) generate_checklist('tax_liens') check_consistency('tax_liens', '0.0', '1.0') df['tax_liens'].value_counts() #this column will be irrelevant for the model - single value '1' will be either #in test or train data; though for larger database it could matter df.drop(columns='tax_liens', inplace=True) check_non_num_rows('hardship_flag') # check if there is other than "N" and if not - drop column df['hardship_flag'].value_counts() df.drop(columns='hardship_flag', inplace=True)#single value present in column check_non_num_rows('disbursement_method') # check if there is other than "cash" and if not - drop column df['disbursement_method'].value_counts()#single value present in column df.drop(columns='disbursement_method', inplace=True) check_non_num_rows('debt_settlement_flag') # check if there is other than "cash" and if not - drop column df['debt_settlement_flag'].value_counts() df['debt_settlement_flag'] = df['debt_settlement_flag'].replace('Y', 1) df['debt_settlement_flag'] = df['debt_settlement_flag'].replace('N', 0) #id is irrelevant df.drop(columns='id', inplace=True) #checking if all values are numeric if df.apply(lambda s: pd.to_numeric(s, errors='coerce').notnull().all()) is True: print("All values are numeric!") else: print("Something went wrong.") df.applymap(np.isreal) only_num_series = df.select_dtypes(include=np.number).columns.tolist() all_series = [] for col in df.columns: all_series.append(col) non_num_series = set(only_num_series) ^ set(all_series) non_num_series df['desc'].head(n=15) df['desc'].value_counts() df['earliest_cr_line'].head(n=15) df['earliest_cr_line'].value_counts() df['emp_length'].head(n=15) df['emp_length'].value_counts() df['int_rate'].head(n=15) df['int_rate'].value_counts() df['issue_d'].head(n=15) df['issue_d'].value_counts() df['last_credit_pull_d'].head(n=15) df['last_credit_pull_d'].value_counts() df['last_pymnt_d'].head(n=15) df['last_pymnt_d'].value_counts() df['revol_util'].head(n=15) df['revol_util'].value_counts() df['term'].head(n=15) df['term'].value_counts() #export preprocessed file df.to_csv(r'credit_scoring_for_model.csv') #if needed for module export df
{"/projekt_bazy1.py": ["/sa3.py"]}
17,410,095
topi-chan/Misc_projects
refs/heads/main
/new_tetris.py
import random class Tetris: '''A simple game.''' def __init__(self): self.i_shape = [[1, 1, 1, 1]] self.l_shape = [[1], [1], [1, 1]] self.j_shape = [[0, 1], [0, 1], [1, 1]] self.s_shape = [[0, 1], [1, 1], [1, 0]] self.o_shape = [[1, 1], [1, 1]] self.current_shape = None self.boards=[[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]] self.new_boards = [] self.current_pos = [] self.pos_dict = {} self.new_pos = [] self.new_pos_dict = {} def draw_screen(self): '''Draws first screen, makes first block not overlaping with borders.''' num_of_ones = sum(num.count(1) for num in self.boards) board_func = self.boards while True: shape = random.choice([self.i_shape, self.l_shape, self.j_shape, self.s_shape, self.o_shape]) position = random.randint(1, 20) m = 0 for i in range(len(shape)): sub_shape = shape[m] n = 0 pos = position for i in range(len(sub_shape)): if sub_shape[n] == 1 and pos <= 21: board_func[m][pos] = 1 pos += 1 n += 1 m += 1 if (num_of_ones+4) == (sum(num.count(1) for num in board_func)): break else: board_func=[[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]] self.boards = board_func self.current_shape = shape for board in self.boards: print(*["*" if elem == 1 else " " for elem in board], sep='') self.current_pos.append([i for i, x in enumerate(board) if x == 1]) for pos in self.current_pos: pos.remove(0) pos.remove(21) for i, pos in enumerate(self.current_pos[:-1]): if len(pos) > 0: self.pos_dict[i] = pos self.move() def move(self): ''' Operate block fragments on the board; implemented for a/d and partially for w. Pressing q quits the game; pressing any other key changes currently operated block into a new one, emerging on top of the board. ''' num_of_ones = sum(num.count(1) for num in self.boards) self.new_boards = self.boards #'print' here and below - if uncommented, user can see changing coordinates # print(self.pos_dict) while True: if num_of_ones != (sum(num.count(1) for num in self.new_boards)): self.redraw() for board in self.new_boards: print(*["*" if elem == 1 else " " for elem in board], sep='') move = input() for k in self.pos_dict.keys(): for item in self.pos_dict.get(k): self.new_boards[k][item] = 0 if move == "d": # print(self.pos_dict) for k in self.pos_dict.keys(): for item in self.pos_dict.get(k): self.new_boards[k+1][item+1] = 1 self.pos_dict = {k+1: v for k, v in self.pos_dict.items()} self.pos_dict = {k: [x+1 for x in v] for k, v in self.pos_dict.items()} # print(self.pos_dict) continue if move == "a": # print(self.pos_dict) for k in self.pos_dict.keys(): for item in self.pos_dict.get(k): self.new_boards[k+1][item-1]=1 self.pos_dict = {k+1: v for k, v in self.pos_dict.items()} self.pos_dict = {k: [x-1 for x in v] for k, v in self.pos_dict.items()} # print(self.pos_dict) continue if move == "w": # print(self.pos_dict) if self.current_shape == [[1, 1], [1, 1]]: for k in self.pos_dict.keys(): for item in self.pos_dict.get(k): self.new_boards[k+1][item+1] = 1 self.pos_dict = {k+1: v for k, v in self.pos_dict.items()} self.pos_dict = {k: [x+1 for x in v] for k, v in self.pos_dict.items()} elif self.current_shape == [[1, 1, 1, 1]]: self.pos_dict = {k+1: v for k, v in self.pos_dict.items()} row = list(self.pos_dict.keys())[0] col = self.pos_dict.get(row)[-1] #0 for 's' key for i in range(4): self.new_boards[row-i][col] = 1 pass #unfinished block: update pos_dict # #{9: [10, 11, 12, 13]}into: #10:10, 9:10, 8:10, 7:10 # print(self.pos_dict) continue #unfinished for j and l shapes #if move == "s": rotate clockwise thrice elif move == "q": quit() else: continue def redraw(self): '''Re-draws board after a fragment collided with another/with frame''' self.new_pos = [] self.current_pos = [] self.pos_dict = {} for board in self.boards: self.current_pos.append([i for i, x in enumerate(board) if x == 1]) for pos in self.current_pos: pos.remove(0) pos.remove(21) for i, pos in enumerate(self.current_pos[:-1]): if len(pos) > 0: self.pos_dict[i] = pos for board in self.boards: print(*["*" if elem == 1 else " " for elem in board], sep='') self.current_pos.append([i for i, x in enumerate(board) if x == 1]) num_of_ones = sum(num.count(1) for num in self.boards) board_func = self.boards while True: shape = random.choice([self.i_shape, self.l_shape, self.j_shape, self.s_shape, self.o_shape]) position = random.randint(1, 20) m = 0 for i in range(len(shape)): sub_shape = shape[m] n = 0 pos = position for i in range(len(sub_shape)): if sub_shape[n] == 1 and pos <= 21: board_func[m][pos] = 1 pos += 1 n += 1 m += 1 if (num_of_ones+4) == (sum(num.count(1) for num in board_func)): break else: board_func = self.boards for board in board_func: self.new_pos.append([i for i, x in enumerate(board) if x == 1]) print(self.new_pos) for pos in self.new_pos: pos.remove(0) pos.remove(21) for i, pos in enumerate(self.new_pos[:-1]): if len(pos) > 0: self.new_pos_dict[i] = pos for key in self.pos_dict.keys() & self.new_pos_dict.keys(): del self.new_pos_dict[key] self.pos_dict = self.new_pos_dict self.new_pos_dict = {} self.boards = board_func self.current_shape = shape for board in self.boards: print(*["*" if elem == 1 else " " for elem in board], sep='') self.move() game = Tetris() game.draw_screen()
{"/projekt_bazy1.py": ["/sa3.py"]}
17,410,096
topi-chan/Misc_projects
refs/heads/main
/api_wf.py
import requests, sys, json, csv class WeatherForecast(): '''Allows you to forecast rain probability from API, write results into file''' def __init__(self): self.forecast_dict = {} self.forecast_date = None self.forecast_file_dict = {} self.list = [] def main(self, api_key, forecast_date): querystring = {"lat":"50","lon":"19","unit_system":"si", "start_time":forecast_date, "end_time":forecast_date, "fields":"precipitation_probability", "apikey":api_key} response = requests.request("GET", "https://api.climacell.co/v3/weather/forecast/daily", params=querystring) self.forecast_date = forecast_date api_response_list = [] for line in response.json(): api_response_list.append(line) return_list = api_response_list[0] rain_list = return_list['precipitation_probability'] rain = rain_list['value'] if rain == 0: print("Nie będzie padać") self.forecast_dict[forecast_date] = "Nie będzie padać" elif rain <= 50: print("Nie wiem") self.forecast_dict[forecast_date] = "Nie wiem" else: print("Będzie padać") self.forecast_dict[forecast_date] = "Będzie padać" def csv_save(self, file_name): datafile = open(file_name) for line in datafile: if self.forecast_date in line: return self.dict_save(file_name) with open(file_name, "a+", newline="") as file: writer = csv.writer(file, delimiter=',', lineterminator="\r") writer.writerow(self.forecast_dict.keys()) writer.writerow(self.forecast_dict.values()) self.dict_save(file_name) def dict_save(self, file_name): with open(file_name) as f: for line in f: line = line.rstrip() self.list.append(line) it = iter(self.list) self.forecast_file_dict = dict(zip(it, it)) def items(self): for item in self.forecast_file_dict.items(): yield item def __getitem__(self, key): return self.forecast_file_dict[key] wf = WeatherForecast() wf.main("{}".format(sys.argv[1]), "{}".format(sys.argv[2])) wf.csv_save("dates.csv") for item in wf.items(): print(item) print(wf["2020-12-16"])
{"/projekt_bazy1.py": ["/sa3.py"]}
17,410,097
topi-chan/Misc_projects
refs/heads/main
/credit_scoring_ML_model.py
import pandas as pd import numpy as np import csv import matplotlib.pyplot as plt import seaborn as sns import re data = pd.read_csv('credit_scoring_for_model_final.csv') only_num_series = data.select_dtypes(include=np.number).columns.tolist() all_series = [] for col in data.columns: all_series.append(col) non_num_series = set(only_num_series) ^ set(all_series) non_num_series data['loan_status'].head(n=12) for i, row in data['loan_status'].iteritems(): if row == "Charged Off": row_value = 0.0 elif row == "Fully Paid": row_value = 1.0 data.at[i, 'loan_status'] = row_value y = data['loan_status'] x_data = data.drop(columns='loan_status') x = (x_data - np.min(x_data))/(np.max(x_data)-np.min(x_data)).values for col in x.columns: print(col) x.drop(axis=1, labels=['Unnamed: 0', 'Unnamed: 0.1'], inplace=True) list_of_important_cols = x.columns.tolist print(type(list_of_important_cols)) #####Here prediction analysis begin###### data.corr() print(len(data.columns)) y = data['loan_status'] y = data['loan_status'].astype(float) data['loan_status'] = data['loan_status'].astype(float) data['loan_status'].dtype x_important_cols = data[['loan_status', 'loan_amnt', 'int_rate', 'zip_code', 'A', 'B', 'C', 'D', § 'E', 'F', 'G']] x_important_cols.head() x_important_cols.corr() #here it's weird, since F and G are more payable than E/D - unregistered income? data.columns.tolist() x_2important_cols = [] x_2important_cols = data[['loan_status','A1', 'A2', 'A3', 'A4', 'A5', 'B1', 'B2', 'B3', 'B4', 'B5', 'C1', 'C2', 'C3', 'C4', 'C5', 'D1', 'D2', 'D3', 'D4', 'D5', 'E1', 'E2', 'E3', 'E4', 'E5', 'F1', 'F2', 'F3', 'F4', 'F5', 'G1', 'G2', 'G3', 'G4', 'G5']] dd = x_2important_cols.corr() dd for col in dd: if re.search("A", col): print(col) print("x") display(data['loan_status'].dtypes) x['loan_amnt'].head(n=15) plt.scatter(x.loan_amnt, y) sns.heatmap(x.corr(), xticklabels=x.corr().columns, yticklabels=x.corr().columns) col_mapping_dict = {c[0]:c[1] for c in enumerate(x.columns)} col_mapping_dict #use iloc for columns optimization x.loan_amnt.head(n=15) plt.scatter(x.loan_amnt, y) np.corrcoef(x.loan_amnt, y) tittles = x.iloc[:,103:] title_corr = tittles.corr() sns.heatmap(title_corr, xticklabels=title_corr.columns, yticklabels=y.columns) sns.heatmap(corr, xticklabels=x.corr.columns, yticklabels=x.corr.columns) # # df_combined = [x, y] # # data.concat()
{"/projekt_bazy1.py": ["/sa3.py"]}
17,410,098
topi-chan/Misc_projects
refs/heads/main
/csvpcjs.py
import csv, os, sys, json, pickle import pandas as pd class FileReader: '''Allows you to open a csv/json/pickle (or any other) files with use of designed Class (name: 'File_formatReader'), appends its content into a list, then changes its content, according to given atributes. For saving a file call the 'FileSave' Class. Pandas library is needed solely for PickleReader.''' #'change_list' to będzie nasz argv[3:] def __init__(self, filepath, change_list): self.filepath = filepath self.change_list = change_list self.original_list = [] self.new_list = [] def detect(filepath, change_list): '''add another 'elif' if you want to add another file format''' path = os.path.splitext(filepath) extension = path[-1] if extension == ".csv": return CsvReader(filepath, change_list) elif extension == ".json": return JsonReader(filepath, change_list) elif extension == ".pickle": return PickleReader(filepath, change_list) else: print("Błąd - nie rozpoznano typu pliku") def define(self): for arg in self.change_list: arg = arg.split(",") X = int(arg[0]) Y = int(arg[1]) content = arg[2] self.original_list[X][Y] = content self.new_list = self.original_list class CsvReader(FileReader): '''Reads csv file and passes its content into a list within 'FileReader' Class''' def read(self): with open(self.filepath, "r") as f: reader = csv.reader(f) for line in reader: self.original_list.append(line) self.define() class JsonReader(FileReader): '''Reads json file and passes its content into a list within 'FileReader' Class''' def read(self): with open(self.filepath) as json_file: reader = json.load(json_file) for line in reader: self.original_list.append(line) self.define() class PickleReader(FileReader): '''Reads pickle file and passes its content into a list within 'FileReader' Class''' def read(self): reader = pd.read_pickle(self.filepath) for line in reader: self.original_list.append(line) self.define() class FileSave(): '''It detects to which file format you want to save file as, then passes a filepath argument into its derived class (namely: File_formatSave)''' def __init__(self, filepath, file_read_list): self.filepath = filepath self.file_read_list = file_read_list def detect(self): '''add another 'elif' if you want to add another file format''' path = os.path.splitext(self.filepath) extension = path[-1] if extension == ".csv": return CsvSave(self.filepath, self.file_read_list) elif extension == ".json": return JsonSave(self.filepath, self.file_read_list) elif extension == ".pickle": return PickleSave(self.filepath, self.file_read_list) else: print("Błąd - nie rozpoznano typu pliku") class CsvSave(FileSave): '''Rewrites and saves a CSV file content, received from 'FileReader' Class''' def save(self): print(self.file_read_list) with open(self.filepath, "w") as f: writer = csv.writer(f) for line in self.file_read_list: writer.writerow(line) class PickleSave(FileSave): '''Saves a pickle file content, received from 'FileReader' Class''' def save(self): with open(self.filepath, 'wb') as f: pickle.dump(self.file_read_list, f) class JsonSave(FileSave): '''Saves a json file received from 'FileReader' Class''' def save(self): with open(self.filepath, 'w') as f: json.dump(self.file_read_list, f) if os.path.isfile(sys.argv[1]): fr = FileReader.detect(sys.argv[1], sys.argv[3:]) else: print("Błąd", "\n", os.listdir()) quit() fr.read() save = FileSave(sys.argv[2],fr2.new_list) save.detect().save() quit()
{"/projekt_bazy1.py": ["/sa3.py"]}
17,566,587
seizans/sandbox-django
refs/heads/master
/sandbox/settings/_store_base.py
# coding=utf8 # storeアプリケーション(表側)に共通の設定 from ._base import * # NOQA IS_FRONT = True # 表側アプリか管理アプリか SESSION_COOKIE_AGE = 60 * 60 * 24 * 30 # 30日間 INSTALLED_APPS += ( 'store', )
{"/sandbox/core/search_indexes.py": ["/sandbox/core/models.py"], "/sandbox/settings/store_stg.py": ["/sandbox/settings/_store_base.py", "/sandbox/settings/_stg.py"], "/sandbox/settings/store_dev.py": ["/sandbox/settings/_store_base.py", "/sandbox/settings/_dev.py"], "/sandbox/settings/_store_base.py": ["/sandbox/settings/_base.py"], "/sandbox/settings/_back_base.py": ["/sandbox/settings/_base.py"], "/sandbox/settings/back_stg.py": ["/sandbox/settings/_back_base.py", "/sandbox/settings/_stg.py"], "/sandbox/settings/back_dev.py": ["/sandbox/settings/_back_base.py", "/sandbox/settings/_dev.py"]}
17,566,588
seizans/sandbox-django
refs/heads/master
/sandbox/settings/_base.py
# coding=utf8 # 全アプリ、全環境に共通の設定 INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'core.urls' WSGI_APPLICATION = 'core.wsgi.application' # Internationalization # https://docs.djangoproject.com/en/1.6/topics/i18n/ LANGUAGE_CODE = 'ja' TIME_ZONE = 'Asia/Tokyo' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.6/howto/static-files/ STATIC_URL = '/static/'
{"/sandbox/core/search_indexes.py": ["/sandbox/core/models.py"], "/sandbox/settings/store_stg.py": ["/sandbox/settings/_store_base.py", "/sandbox/settings/_stg.py"], "/sandbox/settings/store_dev.py": ["/sandbox/settings/_store_base.py", "/sandbox/settings/_dev.py"], "/sandbox/settings/_store_base.py": ["/sandbox/settings/_base.py"], "/sandbox/settings/_back_base.py": ["/sandbox/settings/_base.py"], "/sandbox/settings/back_stg.py": ["/sandbox/settings/_back_base.py", "/sandbox/settings/_stg.py"], "/sandbox/settings/back_dev.py": ["/sandbox/settings/_back_base.py", "/sandbox/settings/_dev.py"]}
17,566,589
seizans/sandbox-django
refs/heads/master
/sandbox/core/urls.py
from django.conf import settings from django.conf.urls import patterns, include, url if settings.IS_FRONT: urlpatterns = patterns( '', url(r'^store/', include('store.urls')), ) else: from django.contrib import admin admin.autodiscover() urlpatterns = patterns( '', url(r'^back/', include('back.urls')), url(r'^admin/', include(admin.site.urls)), )
{"/sandbox/core/search_indexes.py": ["/sandbox/core/models.py"], "/sandbox/settings/store_stg.py": ["/sandbox/settings/_store_base.py", "/sandbox/settings/_stg.py"], "/sandbox/settings/store_dev.py": ["/sandbox/settings/_store_base.py", "/sandbox/settings/_dev.py"], "/sandbox/settings/_store_base.py": ["/sandbox/settings/_base.py"], "/sandbox/settings/_back_base.py": ["/sandbox/settings/_base.py"], "/sandbox/settings/back_stg.py": ["/sandbox/settings/_back_base.py", "/sandbox/settings/_stg.py"], "/sandbox/settings/back_dev.py": ["/sandbox/settings/_back_base.py", "/sandbox/settings/_dev.py"]}
17,566,590
seizans/sandbox-django
refs/heads/master
/sandbox/settings/store_dev.py
# coding=utf8 # 表側アプリケーションの、開発環境用の設定 from ._store_base import * # NOQA from ._dev import * # NOQA # .dev で定義されている追加分を追加する INSTALLED_APPS += INSTALLED_APPS_PLUS MIDDLEWARE_CLASSES += MIDDLEWARE_CLASSES_PLUS
{"/sandbox/core/search_indexes.py": ["/sandbox/core/models.py"], "/sandbox/settings/store_stg.py": ["/sandbox/settings/_store_base.py", "/sandbox/settings/_stg.py"], "/sandbox/settings/store_dev.py": ["/sandbox/settings/_store_base.py", "/sandbox/settings/_dev.py"], "/sandbox/settings/_store_base.py": ["/sandbox/settings/_base.py"], "/sandbox/settings/_back_base.py": ["/sandbox/settings/_base.py"], "/sandbox/settings/back_stg.py": ["/sandbox/settings/_back_base.py", "/sandbox/settings/_stg.py"], "/sandbox/settings/back_dev.py": ["/sandbox/settings/_back_base.py", "/sandbox/settings/_dev.py"]}
17,566,591
seizans/sandbox-django
refs/heads/master
/sandbox/settings/back_dev.py
# coding=utf8 # 管理用アプリケーションの、開発環境用の設定 from ._back_base import * # NOQA from ._dev import * # NOQA # .dev で定義されている追加分を追加する INSTALLED_APPS += INSTALLED_APPS_PLUS MIDDLEWARE_CLASSES += MIDDLEWARE_CLASSES_PLUS
{"/sandbox/core/search_indexes.py": ["/sandbox/core/models.py"], "/sandbox/settings/store_stg.py": ["/sandbox/settings/_store_base.py", "/sandbox/settings/_stg.py"], "/sandbox/settings/store_dev.py": ["/sandbox/settings/_store_base.py", "/sandbox/settings/_dev.py"], "/sandbox/settings/_store_base.py": ["/sandbox/settings/_base.py"], "/sandbox/settings/_back_base.py": ["/sandbox/settings/_base.py"], "/sandbox/settings/back_stg.py": ["/sandbox/settings/_back_base.py", "/sandbox/settings/_stg.py"], "/sandbox/settings/back_dev.py": ["/sandbox/settings/_back_base.py", "/sandbox/settings/_dev.py"]}
17,566,592
seizans/sandbox-django
refs/heads/master
/sandbox/store/views.py
from django.shortcuts import render def hello(request): d = {'from_hello_view': 'From Hello View'} return render(request, 'store/hello.html', d)
{"/sandbox/core/search_indexes.py": ["/sandbox/core/models.py"], "/sandbox/settings/store_stg.py": ["/sandbox/settings/_store_base.py", "/sandbox/settings/_stg.py"], "/sandbox/settings/store_dev.py": ["/sandbox/settings/_store_base.py", "/sandbox/settings/_dev.py"], "/sandbox/settings/_store_base.py": ["/sandbox/settings/_base.py"], "/sandbox/settings/_back_base.py": ["/sandbox/settings/_base.py"], "/sandbox/settings/back_stg.py": ["/sandbox/settings/_back_base.py", "/sandbox/settings/_stg.py"], "/sandbox/settings/back_dev.py": ["/sandbox/settings/_back_base.py", "/sandbox/settings/_dev.py"]}
17,566,593
seizans/sandbox-django
refs/heads/master
/sandbox/settings/_dev.py
# coding=utf8 # 開発用の環境で共通の設定 # base系の後で import * されるので、上書きをする挙動になる # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'n+i_fly3y8v%(hgp#n(9h3@brw6qjiae)$gauqd)mee1t3dp1u' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } INSTALLED_APPS_PLUS = ( 'debug_toolbar', ) # django-debug-toolbar 用の設定 MIDDLEWARE_CLASSES_PLUS = ('debug_toolbar.middleware.DebugToolbarMiddleware',) DEBUG_TOOLBAR_PANELS = ( 'debug_toolbar.panels.version.VersionDebugPanel', 'debug_toolbar.panels.timer.TimerDebugPanel', 'debug_toolbar.panels.settings_vars.SettingsVarsDebugPanel', 'debug_toolbar.panels.headers.HeaderDebugPanel', 'debug_toolbar.panels.request_vars.RequestVarsDebugPanel', 'debug_toolbar.panels.template.TemplateDebugPanel', 'debug_toolbar.panels.sql.SQLDebugPanel', 'debug_toolbar.panels.signals.SignalDebugPanel', 'debug_toolbar.panels.logger.LoggingPanel', ) def custom_show_toolbar(request): return True # Always show toolbar, for example purposes only. DEBUG_TOOLBAR_CONFIG = { 'INTERCEPT_REDIRECTS': False, 'SHOW_TOOLBAR_CALLBACK': custom_show_toolbar, # 'EXTRA_SIGNALS': ['myproject.signals.MySignal'], 'HIDE_DJANGO_SQL': False, 'TAG': 'div', 'ENABLE_STACKTRACES': True, }
{"/sandbox/core/search_indexes.py": ["/sandbox/core/models.py"], "/sandbox/settings/store_stg.py": ["/sandbox/settings/_store_base.py", "/sandbox/settings/_stg.py"], "/sandbox/settings/store_dev.py": ["/sandbox/settings/_store_base.py", "/sandbox/settings/_dev.py"], "/sandbox/settings/_store_base.py": ["/sandbox/settings/_base.py"], "/sandbox/settings/_back_base.py": ["/sandbox/settings/_base.py"], "/sandbox/settings/back_stg.py": ["/sandbox/settings/_back_base.py", "/sandbox/settings/_stg.py"], "/sandbox/settings/back_dev.py": ["/sandbox/settings/_back_base.py", "/sandbox/settings/_dev.py"]}
17,566,594
seizans/sandbox-django
refs/heads/master
/sandbox/settings/_back_base.py
# coding=utf8 # backアプリケーション(管理用)に共通の設定 from ._base import * # NOQA IS_FRONT = False # 表側アプリか管理アプリか SESSION_EXPIRE_AT_BROWSER_CLOSE = True # 管理アプリではブラウザ閉じるとセッション期限切れにする INSTALLED_APPS += ( 'django.contrib.admin', 'back', )
{"/sandbox/core/search_indexes.py": ["/sandbox/core/models.py"], "/sandbox/settings/store_stg.py": ["/sandbox/settings/_store_base.py", "/sandbox/settings/_stg.py"], "/sandbox/settings/store_dev.py": ["/sandbox/settings/_store_base.py", "/sandbox/settings/_dev.py"], "/sandbox/settings/_store_base.py": ["/sandbox/settings/_base.py"], "/sandbox/settings/_back_base.py": ["/sandbox/settings/_base.py"], "/sandbox/settings/back_stg.py": ["/sandbox/settings/_back_base.py", "/sandbox/settings/_stg.py"], "/sandbox/settings/back_dev.py": ["/sandbox/settings/_back_base.py", "/sandbox/settings/_dev.py"]}
17,599,318
Vishakha-Bhosale/VishakhaB
refs/heads/main
/Contact.py
import requests headers = { 'content-type': "application/json", 'accept': "application/json", 'authorization': "Bearer 2uIcSpFAlNluC5FMiBYU7aMipLdFMg9NCJ-K_0nfPBU" } response = requests.get("https://api.sandbox.split.cash/contacts", headers = headers) print(response.status_code) print(response.text) #getting a single customer details from id print("\nIndividual Customer\n") response = requests.get("https://api.sandbox.split.cash/contacts/2e115cc1-1566-41d4-ad66-56814e1c55b6", headers = headers) print(response.text) #getting your bank account id print("\nMy Bank ID\n") response = requests.get("https://api.sandbox.split.cash/bank_accounts", headers = headers) print(response.text) #making a payment print("\nMaking a payment to a contact\n") payload = "{\"description\":\"The SuperPackage\",\"matures_at\":\"2021-01-19T00:00:00Z\",\"your_bank_account_id\":\"8cd332a0-8cf3-479b-9e80-c17a22bf63ad\",\"payouts\":[{\"amount\":30,\"description\":\"testing payments via code\",\"recipient_contact_id\":\"2e115cc1-1566-41d4-ad66-56814e1c55b6\",\"metadata\":{\"invoice_ref\":\"BILL-0001\",\"invoice_id\":\"c80a9958-e805-47c0-ac2a-c947d7fd778d\",\"custom_key\":\"Custom string\",\"another_custom_key\":\"Maybe a URL\"}},{\"amount\":30,\"description\":\"A scuba dive SDS5464\",\"recipient_contact_id\":\"2e115cc1-1566-41d4-ad66-56814e1c55b6\"}]}" response = requests.post("https://api.sandbox.split.cash/payments", payload, headers = headers) print(response.text) #create a contact print("\Creating a Split contact") payload = "{\"name\":\"contactadded with api\",\"email\":\"withapi@gmail.com\",\"branch_code\":\"123056\",\"account_number\":\"099999999\"}" response = requests.post("https://api.sandbox.split.cash/contacts/anyone",payload,headers = headers) print(response.status_code) #propose an unassigned agreement print("\n Propose an agreement\n") payload = "{\"expiry_in_seconds\":6000,\"single_use\":false,\"terms\":{\"per_payout\":{\"min_amount\":null,\"max_amount\":10000},\"per_frequency\":{\"days\":7,\"max_amount\":1000000}}}" response = requests.post("https://api.sandbox.split.cash/unassigned_agreements", payload, headers = headers) print(response.text) #Direct Debit a contact print("\nDirect Debit a contact\n") payload = "{\"description\":\"Direct Debiting a contact via api\",\"matures_at\":\"20121-01-20T02:10:56.000Z\",\"amount\":1000,\"authoriser_contact_id\":\"c4e6d5b7-a6a0-4b68-b481-0caaac0d3875\",\"your_bank_account_id\":\"8cd332a0-8cf3-479b-9e80-c17a22bf63ad\",\"precheck_funds\":false,\"metadata\":{\"custom_key\":\"Custom string\",\"another_custom_key\":\"Maybe a URL\"}}" response = requests.post("https://api.sandbox.split.cash/payment_requests",payload, headers = headers) print(response.text)
{"/Contact.py": ["/Methods.py"]}
17,603,504
stillnurs/meso
refs/heads/master
/users/serializers.py
import datetime import logging from django.utils.translation import ugettext as _ from phonenumber_field.serializerfields import PhoneNumberField from rest_framework import serializers from django.contrib.auth import authenticate from dateutil.relativedelta import relativedelta from .models import User from .backends import get_sms_backend logger = logging.getLogger(__name__) class PhoneSerializer(serializers.Serializer): phone_number = PhoneNumberField() class SMSVerificationSerializer(serializers.Serializer): phone_number = PhoneNumberField(required=True) session_token = serializers.CharField(required=True) security_code = serializers.CharField(required=True) def validate(self, attrs): attrs = super().validate(attrs) phone_number = attrs.get("phone_number", None) security_code, session_token = ( attrs.get("security_code", None), attrs.get("session_token", None), ) backend = get_sms_backend(phone_number=phone_number) verification, token_validatation = backend.validate_security_code( security_code=security_code, phone_number=phone_number, session_token=session_token, ) if verification is None: raise serializers.ValidationError(_("Security code is not valid")) elif token_validatation == backend.SESSION_TOKEN_INVALID: raise serializers.ValidationError(_("Session Token mis-match")) elif token_validatation == backend.SECURITY_CODE_EXPIRED: raise serializers.ValidationError(_("Security code has expired")) elif token_validatation == backend.SECURITY_CODE_VERIFIED: raise serializers.ValidationError(_("Security code is already verified")) return attrs class UserSerializer(serializers.ModelSerializer): age = serializers.SerializerMethodField() password = serializers.CharField( max_length=128, min_length=8, write_only=True ) class Meta: model = User fields = [ 'id', 'first_name', 'last_name', 'age', 'username', 'email', 'birthday', 'gender', 'phone', 'about_me', 'image', 'address', 'zip_code', 'country', 'city', 'state', 'points', 'avg_rating', 'rating_count', 'avg_rating_last_ten', 'canceled_posts', 'created_posts', 'password', 'token'] read_only_fields = ['token', 'password'] def get_age(self, instance): age = relativedelta(datetime.datetime.now(), instance.birthday).years return age def points_validation(self, instance): if instance.points < 20: return "You have no points" def update(self, instance, validated_data): password = validated_data.pop('password', None) for (key, value) in validated_data.items(): setattr(instance, key, value) if password is not None: instance.set_password(password) instance.save() return instance class RegistrationSerializer(serializers.ModelSerializer): password = serializers.CharField( max_length=128, min_length=8, style={'input_type': 'password'}, write_only=True ) password2 = serializers.CharField( style={'input_type': 'password'}, write_only=True ) token = serializers.CharField( max_length=256, read_only=True ) class Meta: model = User fields = [ 'id', 'first_name', 'last_name', 'username', 'email', 'birthday', 'gender', 'phone', 'about_me', 'image', 'address', 'zip_code', 'country', 'city', 'state', 'password', 'password2', 'token', ] extra_kwargs = { 'password': {'write_only': True} } def create(self, validated_data): account = User( first_name=self.validated_data['first_name'], last_name=self.validated_data['last_name'], username=self.validated_data['username'], email=self.validated_data['email'], birthday=self.validated_data['birthday'], gender=self.validated_data['gender'], phone=self.validated_data['phone'], address=self.validated_data['address'], zip_code=self.validated_data['zip_code'], country=self.validated_data['country'], city=self.validated_data['city'], state=self.validated_data['state'], about_me=self.validated_data['about_me'], image=self.validated_data['image'] ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({ 'password': 'Passwords must match.' }) account.set_password(password) account.save() return account class LoginSerializer(serializers.Serializer): email = serializers.CharField(max_length=256) password = serializers.CharField(max_length=128, write_only=True) token = serializers.CharField(max_length=256, read_only=True) def validate(self, data): email = data.get('email', None) password = data.get('password', None) if email is None: raise serializers.ValidationError( 'An email address is required to log in.' ) if password is None: raise serializers.ValidationError( 'A password is required to log in.' ) user = authenticate(username=email, password=password) if user is None: raise serializers.ValidationError( 'A user with this email and password was not found or has been banned.' ) return user class RatingSerializer(serializers.ModelSerializer): requester = serializers.HiddenField(default=serializers.CurrentUserDefault()) class Meta: model = Rating fields = '__all__' class RatingReadableSerializer(serializers.ModelSerializer): requester = UserSerializer() provider = UserSerializer() class Meta: model = Rating fields = '__all__'
{"/catalog/urls.py": ["/catalog/views.py"], "/catalog/serializers.py": ["/catalog/models.py"], "/catalog/views.py": ["/catalog/serializers.py"], "/users/serializers.py": ["/users/models.py"], "/users/admin.py": ["/users/models.py"], "/users/backends/twilio.py": ["/users/models.py"], "/users/api.py": ["/users/serializers.py", "/users/services.py"], "/users/urls.py": ["/users/views.py"]}
17,603,505
stillnurs/meso
refs/heads/master
/users/views.py
from django.contrib.sites.shortcuts import get_current_site from django.core.mail import EmailMessage from django.http import JsonResponse from django.template.loader import render_to_string from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode from rest_framework import status, generics, viewsets from rest_framework.decorators import action from rest_framework.filters import SearchFilter from rest_framework.generics import RetrieveUpdateAPIView from rest_framework.permissions import AllowAny, IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView from .base import response from .permissions import IsOwnerOrReadOnly from .serializers import * from .services import send_security_code_and_generate_session_token class VerificationViewSet(viewsets.GenericViewSet): @action( detail=False, methods=["POST"], permission_classes=[AllowAny], serializer_class=PhoneSerializer, ) def register(self, request): serializer = PhoneSerializer(data=request.data) serializer.is_valid(raise_exception=True) session_token = send_security_code_and_generate_session_token( str(serializer.validated_data["phone_number"]) ) return response.Ok({"session_token": session_token}) @action( detail=False, methods=["POST"], permission_classes=[AllowAny], serializer_class=SMSVerificationSerializer, ) def verify(self, request): serializer = SMSVerificationSerializer(data=request.data) serializer.is_valid(raise_exception=True) return response.Ok({"message": "Security code is valid."}) class RegistrationAPIView(APIView): permission_classes = (AllowAny, ) serializer_class = RegistrationSerializer def post(self, request): serializer = self.serializer_class(data=request.data) data = {} if serializer.is_valid(): user = serializer.save() user.is_active = False user.save() <<<<<<< HEAD ======= current_site = get_current_site(request) mail_subject = 'Email verification' message = render_to_string('users/acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) to_email = serializer.data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() >>>>>>> 25a0499c69ba927db3fd79ec0f083e2e6db023d9 data['response'] = "Successfully created a new user. Please check your email and verify your account." data['email'] = user.email data['token'] = user.token else: data = serializer.errors return Response(data) class LoginAPIView(APIView): permission_classes = (AllowAny,) serializer_class = LoginSerializer def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) return Response(serializer.data, status=status.HTTP_200_OK) class UserRetrieveUpdateAPIView(RetrieveUpdateAPIView): permission_classes = (IsOwnerOrReadOnly, ) serializer_class = UserSerializer queryset = User.objects.all() def retrieve(self, request, *args, **kwargs): users = self.queryset.all() serializer = self.serializer_class(users, many=True) return Response(serializer.data, status=status.HTTP_200_OK) def update(self, request, *args, **kwargs): serializer_data = request.data.get('user', {}) serializer = self.serializer_class( request.user, data=serializer_data, partial=True ) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) class UserUpdateAPIView(APIView): permission_classes = (IsAuthenticated, ) serializer_class = UserSerializer queryset = User.objects.all() def post(self, request): try: serializer = self.serializer_class(request.user, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) except: return JsonResponse({'status': 0, 'message': 'Error on user update'}) class CurrentUserView(APIView): serializer_class = UserSerializer def get(self, request): serializer = self.serializer_class(request.user) return Response(serializer.data) class UserListAPIView(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserSerializer filter_backends = (SearchFilter, ) search_fields = ('email', )
{"/catalog/urls.py": ["/catalog/views.py"], "/catalog/serializers.py": ["/catalog/models.py"], "/catalog/views.py": ["/catalog/serializers.py"], "/users/serializers.py": ["/users/models.py"], "/users/admin.py": ["/users/models.py"], "/users/backends/twilio.py": ["/users/models.py"], "/users/api.py": ["/users/serializers.py", "/users/services.py"], "/users/urls.py": ["/users/views.py"]}
17,603,506
stillnurs/meso
refs/heads/master
/users/services.py
# -*- coding: utf-8 -*- from __future__ import absolute_import import logging # Third Party Stuff from django.conf import settings from django.core.exceptions import ImproperlyConfigured # phone_verify stuff from .backends import get_sms_backend logger = logging.getLogger(__name__) # iOS uses "session code" to parse the security code and support copying on clipboard. DEFAULT_MESSAGE = ( "Welcome to {app}, use session code {security_code} for authentication." ) DEFAULT_APP_NAME = "Phone Verify" class PhoneVerificationService(object): try: phone_settings = settings.PHONE_VERIFICATION except AttributeError: raise ImproperlyConfigured("Please define PHONE_VERIFICATION in settings") verification_message = phone_settings.get("MESSAGE", DEFAULT_MESSAGE) def __init__(self, phone_number, backend=None): self._check_required_settings() if backend is None: self.backend = get_sms_backend(phone_number=phone_number) def send_verification(self, number, security_code): """ Send a verification text to the given number to verify. :param number: the phone number of recipient. """ message = self._generate_message(security_code) self.backend.send_sms(number, message) def _generate_message(self, security_code): return self.verification_message.format( app=settings.PHONE_VERIFICATION.get("APP_NAME", DEFAULT_APP_NAME), security_code=security_code, ) def _check_required_settings(self): required_settings = { "BACKEND", "OPTIONS", "TOKEN_LENGTH", "MESSAGE", "APP_NAME", "SECURITY_CODE_EXPIRATION_TIME", "VERIFY_SECURITY_CODE_ONLY_ONCE", } user_settings = set(settings.PHONE_VERIFICATION.keys()) if not required_settings.issubset(user_settings): raise ImproperlyConfigured( "Please specify following settings in settings.py: {}".format( ", ".join(required_settings - user_settings) ) ) def send_security_code_and_generate_session_token(phone_number): sms_backend = get_sms_backend(phone_number) security_code, session_token = sms_backend.create_security_code_and_session_token( phone_number ) service = PhoneVerificationService(phone_number=phone_number) try: service.send_verification(phone_number, security_code) except service.backend.exception_class as exc: logger.error( "Error in sending verification code to {phone_number}: " "{error}".format(phone_number=phone_number, error=exc) ) return session_token
{"/catalog/urls.py": ["/catalog/views.py"], "/catalog/serializers.py": ["/catalog/models.py"], "/catalog/views.py": ["/catalog/serializers.py"], "/users/serializers.py": ["/users/models.py"], "/users/admin.py": ["/users/models.py"], "/users/backends/twilio.py": ["/users/models.py"], "/users/api.py": ["/users/serializers.py", "/users/services.py"], "/users/urls.py": ["/users/views.py"]}
17,603,507
stillnurs/meso
refs/heads/master
/users/models.py
import jwt import datetime import uuid from django.utils.translation import ugettext_lazy as _ from phonenumber_field.modelfields import PhoneNumberField from datetime import datetime, timedelta from django.db import models from django.conf import settings from django.dispatch import receiver from django.core.mail import EmailMessage from django.template.loader import render_to_string from django.db.models.signals import post_save from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.core.mail import EmailMultiAlternatives from django_rest_passwordreset.signals import reset_password_token_created class UUIDModel(AbstractBaseUser, PermissionsMixin): """ An abstract base class model that makes primary key `id` as UUID instead of default auto incremented number. """ id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) class Meta: abstract = True class TimeStampedUUIDModel(UUIDModel): """An abstract base class model that provides self-updating ``created`` and ``modified`` fields with UUID as primary_key field. """ created_at = models.DateTimeField(auto_now_add=True, editable=False) modified_at = models.DateTimeField(auto_now=True, editable=False) class Meta: abstract = True class SMSVerification(TimeStampedUUIDModel): security_code = models.CharField(_("Security Code"), max_length=120) phone_number = PhoneNumberField(_("Phone Number")) session_token = models.CharField(_("Device Session Token"), max_length=500) is_verified = models.BooleanField(_("Security Code Verified"), default=False) class Meta: db_table = "sms_verification" verbose_name = _("SMS Verification") verbose_name_plural = _("SMS Verifications") ordering = ("-modified_at",) unique_together = ("security_code", "phone_number", "session_token") def __str__(self): return "{}: {}".format(str(self.phone_number), self.security_code) class MyUserManager(BaseUserManager): def create_user(self, username, email, phone, password=None): if not email: raise TypeError("Please, enter your email.") if not phone: raise TypeError("Please, enter your phone.") user = self.model( phone=phone, username=username, email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, password): if password is None: raise TypeError('Superusers must have a password.') user = self.create_user( username=username, email=email, phone=self.phone, password=password, ) user.is_active = True user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=64) last_name = models.CharField(max_length=64) username = models.CharField(max_length=64, unique=True, null=True, blank=True) email = models.EmailField(unique=True) birthday = models.DateField(null=True) phone_number = models.CharField(max_length=64, unique=True) country = models.CharField(max_length=128, null=True, blank=True) zip_code = models.CharField(max_length=32, null=True, blank=True) state = models.CharField(max_length=128, null=True, blank=True) city = models.CharField(max_length=128, null=True, blank=True) address = models.CharField(max_length=128, null=True, blank=True) about_me = models.TextField(max_length=512, null=True, blank=True) image = models.ImageField(upload_to='users', null=True, blank=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'phone' REQUIRED_FIELDS = ['username', 'password'] objects = MyUserManager() def __str__(self): return '%s %s' % (self.first_name, self.last_name) @property def token(self): return self._generate_jwt_token() def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True def _generate_jwt_token(self): dt = datetime.now() + timedelta(days=60) token = jwt.encode({ 'id': self.pk, 'exp': dt.utcfromtimestamp(dt.timestamp()) }, settings.SECRET_KEY, algorithm='HS256') return token.decode('utf-8') @receiver(reset_password_token_created) def password_reset_token_created(sender, instance, reset_password_token, *args, **kwargs): # send an e-mail to the user context = { 'current_user': reset_password_token.user, 'username': reset_password_token.user.username, 'email': reset_password_token.user.email, 'reset_password_url': "https://vrmates.co/change-password/?token={token}".format(token=reset_password_token.key) } @receiver(post_save, sender=User) def banned_notifications(sender, instance, created, **kwargs): if instance.is_banned: instance.is_active = False mail_subject = 'Your account has been banned | Vrmates team' message = render_to_string('users/account_ban.html', { 'user': instance.first_name }) to_email = instance.email email = EmailMessage( mail_subject, message, to=[to_email] ) email.send()
{"/catalog/urls.py": ["/catalog/views.py"], "/catalog/serializers.py": ["/catalog/models.py"], "/catalog/views.py": ["/catalog/serializers.py"], "/users/serializers.py": ["/users/models.py"], "/users/admin.py": ["/users/models.py"], "/users/backends/twilio.py": ["/users/models.py"], "/users/api.py": ["/users/serializers.py", "/users/services.py"], "/users/urls.py": ["/users/views.py"]}
17,603,508
stillnurs/meso
refs/heads/master
/users/admin.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django.contrib import admin from .models import User, Rating, SMSVerification class MyUserAdmin(admin.ModelAdmin): list_display = ['id', 'first_name', 'last_name', 'username', 'email', 'points', 'avg_rating', 'rating_count', 'avg_rating_last_ten', 'canceled_posts', 'created_posts', 'is_active'] list_display_links = ['id', 'first_name', 'last_name', 'username'] list_filter = ['is_active'] search_fields = ['email', 'first_name', 'last_name'] class Meta: model = User class RatingAdmin(admin.ModelAdmin): list_display = [field.name for field in Rating._meta.fields] class Meta: model = Rating class SMSVerificationAdmin(admin.ModelAdmin): list_display = ("id", "security_code", "phone_number", "is_verified", "created_at") search_fields = ("phone_number",) ordering = ("phone_number",) readonly_fields = ( "security_code", "phone_number", "session_token", "is_verified", "created_at", "modified_at", ) admin.site.register(User, MyUserAdmin) admin.site.register(Rating, RatingAdmin) admin.site.register(SMSVerificationAdmin)
{"/catalog/urls.py": ["/catalog/views.py"], "/catalog/serializers.py": ["/catalog/models.py"], "/catalog/views.py": ["/catalog/serializers.py"], "/users/serializers.py": ["/users/models.py"], "/users/admin.py": ["/users/models.py"], "/users/backends/twilio.py": ["/users/models.py"], "/users/api.py": ["/users/serializers.py", "/users/services.py"], "/users/urls.py": ["/users/views.py"]}
17,603,509
stillnurs/meso
refs/heads/master
/users/backends/twilio.py
# -*- coding: utf-8 -*- from __future__ import absolute_import # Third Party Stuff from twilio.base.exceptions import TwilioRestException from twilio.rest import Client as TwilioRestClient # Local from users.base import BaseBackend from users.models import SMSVerification class TwilioBackend(BaseBackend): def __init__(self, **options): super(TwilioBackend, self).__init__(**options) # Lower case it just to be sure options = {key.lower(): value for key, value in options.items()} self._sid = options.get("sid", None) self._secret = options.get("secret", None) # auth_token self._from = options.get("from", None) self.client = TwilioRestClient(self._sid, self._secret) self.exception_class = TwilioRestException def send_sms(self, number, message): self.client.messages.create(to=number, body=message, from_=self._from) def send_bulk_sms(self, numbers, message): for number in numbers: self.send_sms(number=number, message=message) class TwilioSandboxBackend(BaseBackend): def __init__(self, **options): super(TwilioSandboxBackend, self).__init__(**options) # Lower case it just to be sure options = {key.lower(): value for key, value in options.items()} self._sid = options.get("sid", None) self._secret = options.get("secret", None) # auth_token self._from = options.get("from", None) self._token = options.get("sandbox_token") self.client = TwilioRestClient(self._sid, self._secret) self.exception_class = TwilioRestException def send_sms(self, number, message): self.client.messages.create(to=number, body=message, from_=self._from) def send_bulk_sms(self, numbers, message): for number in numbers: self.send_sms(number=number, message=message) def generate_security_code(self): """ Returns a fixed security code """ return self._token def validate_security_code(self, security_code, phone_number, session_token): return SMSVerification.objects.none(), self.SECURITY_CODE_VALID
{"/catalog/urls.py": ["/catalog/views.py"], "/catalog/serializers.py": ["/catalog/models.py"], "/catalog/views.py": ["/catalog/serializers.py"], "/users/serializers.py": ["/users/models.py"], "/users/admin.py": ["/users/models.py"], "/users/backends/twilio.py": ["/users/models.py"], "/users/api.py": ["/users/serializers.py", "/users/services.py"], "/users/urls.py": ["/users/views.py"]}
17,603,510
stillnurs/meso
refs/heads/master
/users/api.py
# -*- coding: utf-8 -*- # Third Party Stuff from rest_framework import viewsets from rest_framework.decorators import action from rest_framework.permissions import AllowAny from .base import response from .serializers import PhoneSerializer, SMSVerificationSerializer from .services import send_security_code_and_generate_session_token class VerificationViewSet(viewsets.GenericViewSet): @action( detail=False, methods=["POST"], permission_classes=[AllowAny], serializer_class=PhoneSerializer, ) def register(self, request): serializer = PhoneSerializer(data=request.data) serializer.is_valid(raise_exception=True) session_token = send_security_code_and_generate_session_token( str(serializer.validated_data["phone_number"]) ) return response.Ok({"session_token": session_token}) @action( detail=False, methods=["POST"], permission_classes=[AllowAny], serializer_class=SMSVerificationSerializer, ) def verify(self, request): serializer = SMSVerificationSerializer(data=request.data) serializer.is_valid(raise_exception=True) return response.Ok({"message": "Security code is valid."})
{"/catalog/urls.py": ["/catalog/views.py"], "/catalog/serializers.py": ["/catalog/models.py"], "/catalog/views.py": ["/catalog/serializers.py"], "/users/serializers.py": ["/users/models.py"], "/users/admin.py": ["/users/models.py"], "/users/backends/twilio.py": ["/users/models.py"], "/users/api.py": ["/users/serializers.py", "/users/services.py"], "/users/urls.py": ["/users/views.py"]}
17,603,511
stillnurs/meso
refs/heads/master
/users/urls.py
from django.conf.urls import url from django.urls import path, include from django_rest_passwordreset import views # Third Party Stuff from rest_framework.routers import DefaultRouter # phone_verify # from .api import VerificationViewSet from .views import * default_router = DefaultRouter(trailing_slash=False) default_router.register("phone", VerificationViewSet, basename="phone") app_name = 'users' urlpatterns = [ list(default_router.urls), path('backend/users/', UserRetrieveUpdateAPIView.as_view(), name='users'), path('backend/users/me/', CurrentUserView.as_view(), name='me'), path('backend/users/update/', UserUpdateAPIView.as_view(), name='update_user'), path('backend/users/registration/', RegistrationAPIView.as_view(), name='registration'), path('backend/users/login/', LoginAPIView.as_view(), name='login'), path('backend/users/password-reset/', include('django_rest_passwordreset.urls', namespace='password_reset')), path('backend/users/search/', UserListAPIView.as_view(), name='user-search'), # email verification # url(r'backend/activate/(?P<uid64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', # activate, name='activate'), ]
{"/catalog/urls.py": ["/catalog/views.py"], "/catalog/serializers.py": ["/catalog/models.py"], "/catalog/views.py": ["/catalog/serializers.py"], "/users/serializers.py": ["/users/models.py"], "/users/admin.py": ["/users/models.py"], "/users/backends/twilio.py": ["/users/models.py"], "/users/api.py": ["/users/serializers.py", "/users/services.py"], "/users/urls.py": ["/users/views.py"]}
17,721,632
Tofs/BrainSweat
HEAD
/guiMain.py
from Tkinter import * import Utils import logging as log import FileManager listbox = None def getFiles(): global listbox for item in FileManager.getAllFiles("./"): log.debug("Add item to listbox: {0}".format(item)) listbox.insert(END, item) def buildGUI(): global listbox log.debug("build GUI ...") root = Tk() root.title("BreainSweat") paths = StringVar() mainFrame = Frame(root) mainFrame.grid(column=0, row=0, sticky=(N, W, E, S)) mainFrame.columnconfigure(0, weight=1) mainFrame.rowconfigure(0, weight=1) listbox = Listbox(mainFrame) listbox.grid(column=0,row=0, sticky=(W, E)) Button(mainFrame, text="Load", command=getFiles).grid(column=0,row=1, sticky=(W, E)) log.info("GUI Done!") return root if __name__ == "__main__": Utils.initLogger() log.info("Program start") tk = buildGUI() tk.mainloop() log.info("Program stop")
{"/guiMain.py": ["/Utils.py", "/FileManager.py"]}
17,721,633
Tofs/BrainSweat
HEAD
/Utils.py
import logging.config def initLogger(): logging.config.fileConfig('./Config/log.conf')
{"/guiMain.py": ["/Utils.py", "/FileManager.py"]}
17,721,634
Tofs/BrainSweat
HEAD
/FileManager.py
import os from logging import * import Utils # option to exclude things def getAllFiles(path): f = [] info("Retrives files") for (dirpath, dirnames, filenames) in os.walk(path): for filename in filenames: absPath = os.path.abspath(dirpath + filename) info("File: {0}".format(absPath)) f.append(absPath) return f if __name__ == "__main__": info("Start") Utils.initLogger() print getAllFiles("./") info("Stop")
{"/guiMain.py": ["/Utils.py", "/FileManager.py"]}
17,782,630
Claurre/pasa_palabra
refs/heads/master
/juegoBD/models.py
from django.db import models # Create your models here. class Pregunta(models.Model): texto = models.TextField ( verbose_name='Definición' ) categoria = models.CharField ( verbose_name='categoía de la pregunta' , max_length=30) letra = models.CharField ( max_length=1 , verbose_name='letra en el rosco') respuesta = models.CharField ( verbose_name='respuesta' , max_length=60) def __str__(self): return self.texto class Rosco_pregunta(models.Model): letra_rosco = models.CharField(max_length=1) contestada = models.BooleanField(default=False) contestada_correcta = models.BooleanField(default=False)
{"/juegoBD/admin.py": ["/juegoBD/models.py"], "/juegoBD/forms.py": ["/juegoBD/models.py"]}
17,809,427
ThanosBb3/Database_Project
refs/heads/main
/app/backend/__init__.py
from .base import base from .records import records from .views import views from .covid import covid
{"/app/backend/__init__.py": ["/app/backend/home.py", "/app/backend/records.py", "/app/backend/views.py", "/app/backend/covid.py", "/app/backend/statistics.py", "/app/backend/register.py"], "/db_initialization/addServices.py": ["/db_initialization/connection.py"], "/app/backend/statistics.py": ["/app/__init__.py"], "/db_initialization/addAreas.py": ["/db_initialization/connection.py"], "/db_initialization/addVisitAndUse.py": ["/db_initialization/connection.py"], "/db_initialization/addAccess.py": ["/db_initialization/connection.py"], "/main_db.py": ["/db_initialization/addCustomers.py", "/db_initialization/addAreas.py", "/db_initialization/addServices.py", "/db_initialization/addRegister.py", "/db_initialization/addProvide.py", "/db_initialization/addAccess.py", "/db_initialization/addVisitAndUse.py"], "/__init__.py": ["/main_app.py"], "/app/backend/covid.py": ["/app/__init__.py"], "/db_initialization/addProvide.py": ["/db_initialization/connection.py"], "/db_initialization/addRegister.py": ["/db_initialization/connection.py"], "/app/backend/records.py": ["/app/__init__.py"], "/db_initialization/addCustomers.py": ["/db_initialization/connection.py"], "/app/__init__.py": ["/app/backend/__init__.py"], "/main_app.py": ["/app/__init__.py"], "/app/backend/views.py": ["/app/__init__.py"]}
17,893,038
Ktnnn3/RaspberrPi
refs/heads/master
/ModePage.py
from tkinter import * # import ResultPage f = ("Arial Black", 55) styleBox = ("Bahnschrift SemiBold SemiConden", 50) choose = 0 test = 0 def chooseOption(ch): global test test = ch print('choose = ', test) nextPage() def nextPage(): tkWindow.destroy() import ResultPage # window tkWindow = Tk() tkWindow.attributes("-fullscreen", True) tkWindow.bind("<Escape>", lambda event: tkWindow.attributes( "-fullscreen", False)) tkWindow.configure(background='#3d2c32') # Label Enose Label(tkWindow, text='> > Electric Nose Mode < < ', font=f, background='#3d2c32', fg='#f9ad5a').place(relx=0.5, rely=0.15, anchor=CENTER) # Buttin Mode choose = Button(tkWindow, text='Detect Racid Order', bg="White", command=lambda: chooseOption( 1), font=styleBox, relief=FLAT, background='#f9ad5a', fg='#333D51', width=20).place(relx=0.40, rely=0.35, anchor=CENTER) choose = Button(tkWindow, text='Detect Racid Order', bg="White", command=lambda: chooseOption( 1), font=styleBox, relief=FLAT, background='#f4a896', fg='#3d2c32', width=20).place(relx=0.38, rely=0.33, anchor=CENTER) choose = Button(tkWindow, text='Detect Fungi Order', bg="White", command=lambda: chooseOption( 2), font=styleBox, relief=FLAT, background='#f9ad5a', fg='#333D51',width=20).place(relx=0.60, rely=0.58, anchor=CENTER) choose = Button(tkWindow, text='Detect Fungi Order', bg="White", command=lambda: chooseOption( 2), font=styleBox, relief=FLAT, background='#f4a896', fg='#3d2c32',width=20).place(relx=0.58, rely=0.56, anchor=CENTER) choose = Button(tkWindow, text='Detect Insect Order', bg="White", command=lambda: chooseOption( 3), font=styleBox, relief=FLAT, background='#f9ad5a', fg='#333D51',width=20).place(relx=0.40, rely=0.81, anchor=CENTER) choose = Button(tkWindow, text='Detect Insect Order', bg="White", command=lambda: chooseOption( 3), font=styleBox, relief=FLAT, background='#f4a896', fg='#3d2c32',width=20).place(relx=0.38, rely=0.79, anchor=CENTER) # exec(open('ModePage.py').read()) tkWindow.mainloop()
{"/ModePage.py": ["/ResultPage.py"], "/LoginPage.py": ["/ModePage.py"], "/ResultPage.py": ["/ModePage.py"]}
17,893,039
Ktnnn3/RaspberrPi
refs/heads/master
/LoginPage.py
from tkinter import * from functools import partial #from tkinter import messagebox #from tkinter import font #from tkinter.font import families style = ('Arial Black',55) styleTEXT = ('Bahnschrift SemiBold SemiConden',50) styleBOX = ('Bahnschrift SemiBold SemiConden',45) def nextPage(): tkWindow.destroy() import ModePage #check username n password def validateLogin(username, password): if (username.get()=='cmu' and password.get()=='1234'): nextPage() else: messagebox.showerror("Can not Login","Incorrect username or password, Please fill it corectly",) print("username entered :", username.get()) print("password entered :", password.get()) #window tkWindow = Tk() tkWindow.attributes("-fullscreen", True) tkWindow.bind("<Escape>", lambda event: tkWindow.attributes("-fullscreen", False)) tkWindow.configure(background='#3d2c32') #Enose Login Label(tkWindow,text=" > > Electrical Nose < <" ,font=style,fg='#f9ad5a',background='#3d2c32').place(relx=0.5, rely=0.43, anchor=CENTER) #username label and text entry box usernameLabel = Label(tkWindow, text="Username",font=styleTEXT,fg='#f4a896',background='#3d2c32').place(relx=0.36, rely=0.57, anchor=CENTER) username = StringVar() usernameEntry = Entry(tkWindow, textvariable=username,width=12,font=styleBOX,borderwidth=40, relief= FLAT,background='#f4a896',fg='#3d2c32').place(relx=0.63, rely=0.58, anchor=CENTER,height=70) #password label and password entry box passwordLabel = Label(tkWindow,text="Password",font=styleTEXT,fg='#f4a896',background='#3d2c32').place(relx=0.36, rely=0.7, anchor=CENTER) password = StringVar() passwordEntry = Entry(tkWindow, textvariable=password, show='*',width=12,font=styleBOX, borderwidth=40, relief= FLAT,background='#f4a896',fg='#3d2c32').place(relx=0.63, rely=0.7, anchor=CENTER,height=70) validateLogin = partial(validateLogin, username, password) #login button loginButton = Button(tkWindow, text="Login", command=validateLogin,width=7,font=styleTEXT, relief=GROOVE,fg='#3d2c32',background='#f9ad5a').place(relx=0.5, rely=0.83, anchor=CENTER,height=90) loginButton = Button(tkWindow, text="Login", command=validateLogin,width=7,font=styleTEXT, relief=GROOVE,fg='#3d2c32',background='#f4a896').place(relx=0.49, rely=0.84, anchor=CENTER,height=90) tkWindow.mainloop()
{"/ModePage.py": ["/ResultPage.py"], "/LoginPage.py": ["/ModePage.py"], "/ResultPage.py": ["/ModePage.py"]}
17,893,040
Ktnnn3/RaspberrPi
refs/heads/master
/ResultPage.py
import tkinter from ModePage import test from tkinter import * tkWindow = Tk() tkWindow.attributes("-fullscreen", True) tkWindow.bind("<Escape>", lambda event: tkWindow.attributes("-fullscreen", False)) print ('choosePage3 = ',test) #Label Detect Rancid Order if (test == 1): global order order = 'Rancid' LabelOrder=Label(tkWindow,text='Detect Rancid Order') LabelOrder.place(relx=0.5, rely=0.1, anchor=CENTER) elif(test==2): order = 'Fungi' LabelOrder=Label(tkWindow,text='Detect Fungi Order') LabelOrder.place(relx=0.5, rely=0.1, anchor=CENTER) elif(test==3): order = 'Insect' LabelOrder=Label(tkWindow,text='Detect Insect Order') LabelOrder.place(relx=0.5, rely=0.1, anchor=CENTER) # LabelOrder=Label(tkWindow,text='Detect Rancid Order') # LabelOrder.place(relx=0.5, rely=0.1, anchor=CENTER) #Label Status LabelStatus=Label(tkWindow,text='Status of Electrical Nose') LabelStatus.place(relx=0.5, rely=0.12, anchor=CENTER) tkWindow.mainloop()
{"/ModePage.py": ["/ResultPage.py"], "/LoginPage.py": ["/ModePage.py"], "/ResultPage.py": ["/ModePage.py"]}
17,893,041
Ktnnn3/RaspberrPi
refs/heads/master
/Hello.py
import tkinter button1 = ttk.Button(self, text="anything", command=random command) button1.pack() button1 = Button(self, text = "Quit", command = self.quit, anchor = W) button1.configure(width = 10, activebackground = "#33B5E5", relief = FLAT) button1_window = canvas1.create_window(10, 10, anchor=NW, window=button1)
{"/ModePage.py": ["/ResultPage.py"], "/LoginPage.py": ["/ModePage.py"], "/ResultPage.py": ["/ModePage.py"]}
17,945,307
ArjunRameshV/HackOverflow
refs/heads/main
/funiegan_test.py
import os import time import ntpath import numpy as np from PIL import Image from os.path import join, exists from keras.models import model_from_json ## local libs from utils.data_utils import getPaths, read_and_resize, preprocess, deprocess ## for testing arbitrary local data img_path = r"F:\Docs\Hackathon\Hackerflow\Dataset\test\test_1.jpeg" # from utils.data_utils import get_local_test_data # test_paths = getPaths(data_dir) # print ("{0} test images are loaded".format(len(test_paths))) ## create dir for log and (sampled) validation data output_dir = r"F:\Docs\Hackathon\Hackerflow\\" if not exists("samples_dir"): os.makedirs("samples_dir") checkpoint_dir = 'models/gen_p/' model_name_by_epoch = "model_15320_" model_h5 = checkpoint_dir + model_name_by_epoch + ".h5" model_json = checkpoint_dir + model_name_by_epoch + ".json" assert (exists(model_h5) and exists(model_json)) # load model with open(model_json, "r") as json_file: loaded_model_json = json_file.read() funie_gan_generator = model_from_json(loaded_model_json) funie_gan_generator.load_weights(model_h5) print("\nLoaded data and model") times = []; s = time.time() inp_img = read_and_resize(img_path, (256, 256)) im = preprocess(inp_img) im = np.expand_dims(im, axis=0) # (1,256,256,3) s = time.time() gen = funie_gan_generator.predict(im) gen_img = deprocess(gen)[0] tot = time.time()-s times.append(tot) img_name = ntpath.basename(img_path) output_file_path = join(output_dir,img_name) out_img = gen_img.astype('uint8') Image.fromarray(out_img).resize((1280,720)).save(output_file_path) del funie_gan_generator #Call YOLO on image
{"/main.py": ["/utils.py"]}
17,945,308
ArjunRameshV/HackOverflow
refs/heads/main
/web_page.py
import os from flask import Flask, flash, request, redirect, url_for, render_template from werkzeug.utils import secure_filename import json import numpy as np import glob import random import os import time import ntpath import numpy as np from PIL import Image from os.path import join, exists from keras.models import model_from_json ## local libs from utils.data_utils import getPaths, read_and_resize, preprocess, deprocess UPLOAD_FOLDER = 'F:\Docs\Hackathon\Hackerflow\\' ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'} IMAGE_EXTENSIONS = ALLOWED_EXTENSIONS app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER import cv2 @app.route('/') def upload_file(): return render_template("upload.html") count = 23 with open("count_value.txt", "r") as f: a = f.readlines() print("The file contents are : ") print(a) count = int(a[0]) + 1 print(count) @app.route('/upload', methods=['GET', 'POST']) def load_faces(): global count Files = request.files.getlist("files") # ID = request.form.get("personID") print(Files) imagelist = list() num = list() F = Files[0] print(F.filename) if(F.filename == ""): return render_template("upload.html") if F.filename.rsplit('.', 1)[1].lower() in IMAGE_EXTENSIONS: for f in Files: if f.filename.rsplit('.', 1)[1].lower() in IMAGE_EXTENSIONS: f.save("static/images/"+f.filename) path = "static/images/"+f.filename # imagelist.append(path) # img = cv2.imread(path, 0) # cv2.imwrite("static/images/modified_image.jpeg", img) """ADD the model here""" img_path = path # from utils.data_utils import get_local_test_data # test_paths = getPaths(data_dir) # print ("{0} test images are loaded".format(len(test_paths))) ## create dir for log and (sampled) validation data output_dir = r"F:\Docs\Hackathon\Hackerflow\static\images" if not exists("samples_dir"): os.makedirs("samples_dir") checkpoint_dir = 'models/gen_p/' model_name_by_epoch = "model_15320_" model_h5 = checkpoint_dir + model_name_by_epoch + ".h5" model_json = checkpoint_dir + model_name_by_epoch + ".json" assert (exists(model_h5) and exists(model_json)) # load model with open(model_json, "r") as json_file: loaded_model_json = json_file.read() funie_gan_generator = model_from_json(loaded_model_json) funie_gan_generator.load_weights(model_h5) print("\nLoaded data and model") times = []; s = time.time() inp_img = read_and_resize(img_path, (256, 256)) im = preprocess(inp_img) im = np.expand_dims(im, axis=0) # (1,256,256,3) s = time.time() gen = funie_gan_generator.predict(im) gen_img = deprocess(gen)[0] tot = time.time()-s times.append(tot) img_name = ntpath.basename(img_path) output_file_path = join(output_dir,"processed_"+img_name) out_img = gen_img.astype('uint8') Image.fromarray(out_img).resize((1280,720)).save(output_file_path) del funie_gan_generator net = cv2.dnn.readNet("yolov3_training_last.weights", "yolov3_testing.cfg") # Name custom object classes = ["gate", "obstacle", "bucket"] # Images path # images_path = glob.glob(r'F:\Docs\Computer Vision\Projects\Object Detection using YOLO\Classification using YOLO\Dataset\Datasets\car\2182.jpg') # images_path.extend(glob.glob(r"F:\Docs\Computer Vision\Projects\Object Detection using YOLO\DataSet\bmw10_release\bmw10_ims\Test_dataset\car.jpeg")) # images_path.append(r'F:\Docs\Computer Vision\Projects\Object Detection using YOLO\DataSet\bmw10_release\bmw10_ims\Test_dataset\8057028683_a8eb0a2605_z.jpeg') images_path = [output_file_path] print(images_path) layer_names = net.getLayerNames() output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()] colors = np.random.uniform(0, 255, size=(len(classes), 3)) # Insert here the path of your images random.shuffle(images_path) # loop through all the images input_image = cv2.imread(path) for img_path in images_path: # Loading image img = cv2.imread(img_path) shape = img.shape shape = shape[0 : 2] shape = list(shape) shape[0], shape[1] = shape[1], shape[0] shape = tuple(shape) print(shape) img = cv2.resize(img, None, fx=0.4, fy=0.4) input_image = cv2.resize(input_image, None, fx=0.4, fy=0.4) height, width, channels = img.shape # Detecting objects blob = cv2.dnn.blobFromImage(img, 0.00392, (416, 416), (0, 0, 0), True, crop=False) net.setInput(blob) outs = net.forward(output_layers) # Showing informations on the screen class_ids = [] confidences = [] boxes = [] for out in outs: for detection in out: scores = detection[5:] class_id = np.argmax(scores) confidence = scores[class_id] if confidence > 0.5: # Object detected print(class_id) center_x = int(detection[0] * width) center_y = int(detection[1] * height) w = int(detection[2] * width) h = int(detection[3] * height) # Rectangle coordinates x = int(center_x - w / 2) y = int(center_y - h / 2) boxes.append([x, y, w, h]) confidences.append(float(confidence)) class_ids.append(class_id) indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4) print(indexes) font = cv2.FONT_HERSHEY_PLAIN for i in range(len(boxes)): if i in indexes: x, y, w, h = boxes[i] label = str(classes[class_ids[i]]) print(label) if(label == "gate"): color = colors[class_ids[i]] cv2.rectangle(input_image, (x, y), (x + w, y + h), color, 2) cv2.circle(input_image, center = (x + w//2, y + h//2), radius = 5, color = color, thickness = -1) cv2.putText(input_image, "class : " + label + " confidence : " + "{:.2f}".format(confidences[i]), (x, y + 30), font, 1, color, 2) # cv2.imshow("Image", input_image) img = cv2.resize(input_image, shape) print("static/images/modified_image_" + str(count) + ".jpeg") cv2.imwrite("static/images/modified_image_" + str(count) + ".jpeg", input_image) # key = cv2.waitKey(0) # cv2.destroyAllWindows() """Model ends here""" imagelist.append("static/images/modified_image_" + str(count) + ".jpeg") # this shd contain the path to the final modified image h = "GATE FOUND" response = json.dumps( h)+str(app.response_class(response=json.dumps(h), status=200, mimetype='application/json')) print(response) count += 1 print(count) with open("count_value.txt", "w") as f: f.write(str(count)) # Return = {"imagelist": imagelist, "array": num} # encodedNumpyData = json.dumps(Return, cls=NumpyArrayEncoder) # return Response(encodedNumpyData) return render_template("extract.html", results=imagelist) if(__name__ == "__main__"): app.run(debug = True)
{"/main.py": ["/utils.py"]}
17,953,081
VB6Hobbyst7/xl_vb2py
refs/heads/master
/vb2pygui/finddialog.py
#@+leo-ver=4-thin #@+node:pap.20070203003236:@thin finddialog.py #@<< finddialog declarations >> #@+node:pap.20070203003236.1:<< finddialog declarations >> #!/usr/bin/python __version__ = "0.1" from wxPython import wx from PythonCard import model, dialog from vb2py import converter, vbparser, utils import os import time #@-node:pap.20070203003236.1:<< finddialog declarations >> #@nl #@+others #@+node:pap.20070203003236.2:class FindDialog class FindDialog(model.CustomDialog): """Find dialog""" #@ << class FindDialog declarations >> #@+node:pap.20070203003236.3:<< class FindDialog declarations >> options = ["Python", "VB"] #@-node:pap.20070203003236.3:<< class FindDialog declarations >> #@nl #@ @+others #@+node:pap.20070203003236.4:__init__ def __init__(self, *args, **kw): """Load the options file""" model.CustomDialog.__init__(self, *args, **kw) self.components.optSearchIn.SetSelection(self.options.index(self.parent.find_language)) self.components.txtFind.text = self.parent.find_text self.components.txtFind.SetFocus() self.components.txtFind.SetSelection(0, len(self.parent.find_text)) #@-node:pap.20070203003236.4:__init__ #@+node:pap.20070203003236.5:on_btnFind_mouseClick def on_btnFind_mouseClick(self, event): """Click the find button""" self.parent.find_text = self.components.txtFind.text self.parent.find_language = self.options[self.components.optSearchIn.GetSelection()] self.parent.findText(self.parent.find_text, self.parent.find_language) #@-node:pap.20070203003236.5:on_btnFind_mouseClick #@+node:pap.20070203003236.6:on_btnFindNext_mouseClick def on_btnFindNext_mouseClick(self, event): """Click the find next button""" self.parent.find_text = self.components.txtFind.text self.parent.find_language = self.options[self.components.optSearchIn.GetSelection()] self.parent.findText(self.parent.find_text, self.parent.find_language, next=1) #@-node:pap.20070203003236.6:on_btnFindNext_mouseClick #@-others #@-node:pap.20070203003236.2:class FindDialog #@-others if __name__ == '__main__': app = model.PythonCardApp(FindDialog) app.MainLoop() #@-node:pap.20070203003236:@thin finddialog.py #@-leo
{"/vb2py/PythonCard/twistedModel.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/dialog.py": ["/vb2py/PythonCard/font.py"], "/vb2py/test/testall.py": ["/vb2py/utils.py"], "/vb2py/PythonCard/component.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testsubs.py": ["/vb2py/test/testframework.py"], "/vb2py/PythonCard/event.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/resource.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/sandbox/makewebsite.py": ["/vb2py/utils.py"], "/vb2py/test/testgrammarmodes.py": ["/vb2py/utils.py", "/vb2py/parserclasses.py"], "/vb2py/test_at_scale/file_tester.py": ["/vb2py/parserclasses.py", "/vb2py/conversionserver.py"], "/vb2py/vbfunctions.py": ["/vb2py/PythonCard/graphic.py"], "/vb2py/test/testlanguagedetection.py": ["/vb2py/conversionserver.py"], "/vb2py/test/testframework.py": ["/vb2py/vbfunctions.py", "/vb2py/parserclasses.py"], "/vb2py/test/testdirectives.py": ["/vb2py/test/testframework.py"], "/vb2py/test/testifs.py": ["/vb2py/test/testframework.py"], "/vb2py/test/testfailures.py": ["/vb2py/test/testframework.py"], "/vb2py/PythonCard/model.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testdotnet_execution.py": ["/vb2py/test/testframework.py", "/vb2py/utils.py", "/vb2py/parserclasses.py"], "/vb2py/sandbox/commandline.py": ["/vb2py/parserclasses.py"], "/vb2py/PythonCard/menu.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test_at_scale/retest_failures.py": ["/vb2py/utils.py"], "/vb2py/test/testcommandline.py": ["/vb2py/utils.py"], "/vb2py/PythonCard/log.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/debug.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/font.py": ["/vb2py/PythonCard/__init__.py"], "/setup.py": ["/vb2py/utils.py"], "/vb2py/targets/pythoncard/__init__.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testserver.py": ["/vb2py/test/testframework.py", "/vb2py/conversionserver.py", "/vb2py/parserclasses.py", "/vb2py/utils.py", "/vb2py/vbfunctions.py"], "/vb2py/PythonCard/configuration.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testdotnet.py": ["/vb2py/test/testframework.py", "/vb2py/utils.py"]}
17,953,082
VB6Hobbyst7/xl_vb2py
refs/heads/master
/vb2pygui/finddialog.rsrc.py
#@+leo-ver=4 #@+node:@file finddialog.rsrc.py {'type':'CustomDialog', 'name':'Find', 'title':'Find', 'position':(467, 157), 'size':(437, 164), 'components': [ {'type':'Button', 'name':'btnFindNext', 'position':(347, 30), 'label':'Find Next', }, {'type':'RadioGroup', 'name':'optSearchIn', 'position':(10, 40), 'size':(151, 47), 'items':['Python', 'VB'], 'label':'Search in', 'layout':'horizontal', 'max':1, 'selected':'Python', }, {'type':'TextField', 'name':'txtFind', 'position':(67, 7), 'size':(272, -1), }, {'type':'StaticText', 'name':'StaticText1', 'position':(11, 10), 'text':'Find what', }, {'type':'Button', 'id':5100, 'name':'btnFind', 'position':(347, 6), 'label':'Find', }, {'type':'Button', 'id':5101, 'name':'btnCancel', 'position':(347, 55), 'label':'Close', }, ] # end components } # end CustomDialog #@-node:@file finddialog.rsrc.py #@-leo
{"/vb2py/PythonCard/twistedModel.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/dialog.py": ["/vb2py/PythonCard/font.py"], "/vb2py/test/testall.py": ["/vb2py/utils.py"], "/vb2py/PythonCard/component.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testsubs.py": ["/vb2py/test/testframework.py"], "/vb2py/PythonCard/event.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/resource.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/sandbox/makewebsite.py": ["/vb2py/utils.py"], "/vb2py/test/testgrammarmodes.py": ["/vb2py/utils.py", "/vb2py/parserclasses.py"], "/vb2py/test_at_scale/file_tester.py": ["/vb2py/parserclasses.py", "/vb2py/conversionserver.py"], "/vb2py/vbfunctions.py": ["/vb2py/PythonCard/graphic.py"], "/vb2py/test/testlanguagedetection.py": ["/vb2py/conversionserver.py"], "/vb2py/test/testframework.py": ["/vb2py/vbfunctions.py", "/vb2py/parserclasses.py"], "/vb2py/test/testdirectives.py": ["/vb2py/test/testframework.py"], "/vb2py/test/testifs.py": ["/vb2py/test/testframework.py"], "/vb2py/test/testfailures.py": ["/vb2py/test/testframework.py"], "/vb2py/PythonCard/model.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testdotnet_execution.py": ["/vb2py/test/testframework.py", "/vb2py/utils.py", "/vb2py/parserclasses.py"], "/vb2py/sandbox/commandline.py": ["/vb2py/parserclasses.py"], "/vb2py/PythonCard/menu.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test_at_scale/retest_failures.py": ["/vb2py/utils.py"], "/vb2py/test/testcommandline.py": ["/vb2py/utils.py"], "/vb2py/PythonCard/log.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/debug.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/font.py": ["/vb2py/PythonCard/__init__.py"], "/setup.py": ["/vb2py/utils.py"], "/vb2py/targets/pythoncard/__init__.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testserver.py": ["/vb2py/test/testframework.py", "/vb2py/conversionserver.py", "/vb2py/parserclasses.py", "/vb2py/utils.py", "/vb2py/vbfunctions.py"], "/vb2py/PythonCard/configuration.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testdotnet.py": ["/vb2py/test/testframework.py", "/vb2py/utils.py"]}
17,953,083
VB6Hobbyst7/xl_vb2py
refs/heads/master
/vb2pygui/interactive.rsrc.py
{'application':{'type':'Application', 'name':'Template', 'backgrounds': [ {'type':'Background', 'name':'bgTemplate', 'title':'vb2Py Code Conversion', 'size':(973, 836), 'backgroundColor':(243, 243, 243), 'icon':'vb2Py.ico', 'components': [ {'type':'ImageButton', 'name':'HelpConversionStyle', 'position':(917, 17), 'size':(29, 29), 'border':'transparent', 'file':'images/help.jpg', }, {'type':'ImageButton', 'name':'HelpConvertAs', 'position':(289, 15), 'size':(30, 29), 'border':'transparent', 'file':'images/help.jpg', }, {'type':'Image', 'name':'PythonPane', 'position':(607, 679), 'file':'images/pythonpane.jpg', }, {'type':'Image', 'name':'VBPane', 'position':(134, 679), 'file':'images/vbpane.jpg', }, {'type':'RadioGroup', 'name':'Pythonicity', 'position':(585, 6), 'size':(327, -1), 'items':['Make sure it works', 'Make it look like Python'], 'label':'Conversion style', 'layout':'horizontal', 'max':1, 'stringSelection':'Make sure it works', }, {'type':'RadioGroup', 'name':'CodeContext', 'position':(19, 5), 'items':['Code module', 'Class module', 'Form'], 'label':'Convert as', 'layout':'horizontal', 'max':1, 'stringSelection':'Code module', }, {'type':'TextArea', 'name':'LogWindow', 'position':(15, 678), 'size':(914, 91), 'backgroundColor':(236, 236, 255, 255), 'visible':False, }, {'type':'Button', 'name':'Convert', 'position':(438, 11), 'size':(-1, 35), 'label':'Convert -->', }, {'type':'CodeEditor', 'name':'Python', 'position':(473, 60), 'size':(473, 615), 'backgroundColor':(255, 255, 255, 255), }, {'type':'CodeEditor', 'name':'VB', 'position':(16, 60), 'size':(448, 615), 'backgroundColor':(255, 255, 255, 255), }, ] # end components } # end background ] # end backgrounds } }
{"/vb2py/PythonCard/twistedModel.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/dialog.py": ["/vb2py/PythonCard/font.py"], "/vb2py/test/testall.py": ["/vb2py/utils.py"], "/vb2py/PythonCard/component.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testsubs.py": ["/vb2py/test/testframework.py"], "/vb2py/PythonCard/event.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/resource.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/sandbox/makewebsite.py": ["/vb2py/utils.py"], "/vb2py/test/testgrammarmodes.py": ["/vb2py/utils.py", "/vb2py/parserclasses.py"], "/vb2py/test_at_scale/file_tester.py": ["/vb2py/parserclasses.py", "/vb2py/conversionserver.py"], "/vb2py/vbfunctions.py": ["/vb2py/PythonCard/graphic.py"], "/vb2py/test/testlanguagedetection.py": ["/vb2py/conversionserver.py"], "/vb2py/test/testframework.py": ["/vb2py/vbfunctions.py", "/vb2py/parserclasses.py"], "/vb2py/test/testdirectives.py": ["/vb2py/test/testframework.py"], "/vb2py/test/testifs.py": ["/vb2py/test/testframework.py"], "/vb2py/test/testfailures.py": ["/vb2py/test/testframework.py"], "/vb2py/PythonCard/model.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testdotnet_execution.py": ["/vb2py/test/testframework.py", "/vb2py/utils.py", "/vb2py/parserclasses.py"], "/vb2py/sandbox/commandline.py": ["/vb2py/parserclasses.py"], "/vb2py/PythonCard/menu.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test_at_scale/retest_failures.py": ["/vb2py/utils.py"], "/vb2py/test/testcommandline.py": ["/vb2py/utils.py"], "/vb2py/PythonCard/log.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/debug.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/font.py": ["/vb2py/PythonCard/__init__.py"], "/setup.py": ["/vb2py/utils.py"], "/vb2py/targets/pythoncard/__init__.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testserver.py": ["/vb2py/test/testframework.py", "/vb2py/conversionserver.py", "/vb2py/parserclasses.py", "/vb2py/utils.py", "/vb2py/vbfunctions.py"], "/vb2py/PythonCard/configuration.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testdotnet.py": ["/vb2py/test/testframework.py", "/vb2py/utils.py"]}
17,953,084
VB6Hobbyst7/xl_vb2py
refs/heads/master
/vb2pygui/testingview.py
#@+leo-ver=4-thin #@+node:pap.20070203003321:@thin testingview.py #@<< testingview declarations >> #@+node:pap.20070203003321.1:<< testingview declarations >> #!/usr/bin/python """ __version__ = "$Revision: 1.1 $" __date__ = "$Date: 2004/01/26 07:21:13 $" """ from PythonCard import model from vb2py.test.scripttest import testCode from vb2py.vbparser import convertVBtoPython, VBCodeModule #@-node:pap.20070203003321.1:<< testingview declarations >> #@nl #@+others #@+node:pap.20070203003321.2:class TestingView class TestingView(model.Background): #@ << class TestingView declarations >> #@+node:pap.20070203003321.3:<< class TestingView declarations >> left_pc = 33 mid_pc = 33 panel_top = 25 panel_height_border = 80 panel_width_border = 20 label_top = 5 label_left = 5 #@-node:pap.20070203003321.3:<< class TestingView declarations >> #@nl #@ @+others #@+node:pap.20070203003321.4:on_openBackground def on_openBackground(self, event): # if you have any initialization # including sizer setup, do it here self._positionWidgets() #@-node:pap.20070203003321.4:on_openBackground #@+node:pap.20070203003321.5:_positionWidgets def _positionWidgets(self, event=None): """Put widgets in the right place depending on the screen size""" if event: width, height = event.size else: width, height = self.panel.GetSize() height += 50 # Why do we have to do this? width += 5 # # Get relative sizes width1 = width*self.left_pc/100.0 width2 = width*(self.left_pc + self.mid_pc)/100.0 # # Main panel size self.panel.SetSize((width,height)) # # Label positions self.components.VBLabel.position = (self.label_left, self.label_top) self.components.PythonLabel.position = (self.label_left+width1, self.label_top) self.components.ResultLabel.position = (self.label_left+width2, self.label_top) # # Panels self.components.VBCodeEditor.position = (self.label_left, self.panel_top) self.components.VBCodeEditor.size = (width1, height-self.panel_height_border) # self.components.PythonCodeEditor.position = (self.label_left+width1, self.panel_top) self.components.PythonCodeEditor.size = (width2-width1, height-self.panel_height_border) # self.components.ResultsView.position = (self.label_left+width2, self.panel_top) self.components.ResultsView.size = (width-width2-self.panel_width_border, height-self.panel_height_border) #@-node:pap.20070203003321.5:_positionWidgets #@+node:pap.20070203003321.6:on_TestingView_size def on_TestingView_size(self, event): """Resize event""" self._positionWidgets(event) #@-node:pap.20070203003321.6:on_TestingView_size #@+node:pap.20070203003321.7:on_menuFileExit_select def on_menuFileExit_select(self, event): """Quit this window""" self.Close() #@-node:pap.20070203003321.7:on_menuFileExit_select #@+node:pap.20070203003321.8:on_menuTestCode_select def on_menuTestCode_select(self, event): """Test the code""" vb = self.components.VBCodeEditor.text self.components.PythonCodeEditor.text = convertVBtoPython(vb, container=VBCodeModule()) try: output = testCode(vb, verbose=2) except Exception, err: self.components.ResultsView.text = str(err) else: self.components.ResultsView.text = "\n".join(output) #@-node:pap.20070203003321.8:on_menuTestCode_select #@-others #@-node:pap.20070203003321.2:class TestingView #@-others if __name__ == '__main__': app = model.PythonCardApp(TestingView) app.MainLoop() #@-node:pap.20070203003321:@thin testingview.py #@-leo
{"/vb2py/PythonCard/twistedModel.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/dialog.py": ["/vb2py/PythonCard/font.py"], "/vb2py/test/testall.py": ["/vb2py/utils.py"], "/vb2py/PythonCard/component.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testsubs.py": ["/vb2py/test/testframework.py"], "/vb2py/PythonCard/event.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/resource.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/sandbox/makewebsite.py": ["/vb2py/utils.py"], "/vb2py/test/testgrammarmodes.py": ["/vb2py/utils.py", "/vb2py/parserclasses.py"], "/vb2py/test_at_scale/file_tester.py": ["/vb2py/parserclasses.py", "/vb2py/conversionserver.py"], "/vb2py/vbfunctions.py": ["/vb2py/PythonCard/graphic.py"], "/vb2py/test/testlanguagedetection.py": ["/vb2py/conversionserver.py"], "/vb2py/test/testframework.py": ["/vb2py/vbfunctions.py", "/vb2py/parserclasses.py"], "/vb2py/test/testdirectives.py": ["/vb2py/test/testframework.py"], "/vb2py/test/testifs.py": ["/vb2py/test/testframework.py"], "/vb2py/test/testfailures.py": ["/vb2py/test/testframework.py"], "/vb2py/PythonCard/model.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testdotnet_execution.py": ["/vb2py/test/testframework.py", "/vb2py/utils.py", "/vb2py/parserclasses.py"], "/vb2py/sandbox/commandline.py": ["/vb2py/parserclasses.py"], "/vb2py/PythonCard/menu.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test_at_scale/retest_failures.py": ["/vb2py/utils.py"], "/vb2py/test/testcommandline.py": ["/vb2py/utils.py"], "/vb2py/PythonCard/log.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/debug.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/font.py": ["/vb2py/PythonCard/__init__.py"], "/setup.py": ["/vb2py/utils.py"], "/vb2py/targets/pythoncard/__init__.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testserver.py": ["/vb2py/test/testframework.py", "/vb2py/conversionserver.py", "/vb2py/parserclasses.py", "/vb2py/utils.py", "/vb2py/vbfunctions.py"], "/vb2py/PythonCard/configuration.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testdotnet.py": ["/vb2py/test/testframework.py", "/vb2py/utils.py"]}
17,953,085
VB6Hobbyst7/xl_vb2py
refs/heads/master
/vb2pygui/vb2pyGUI.rsrc.py
#@+leo-ver=4-thin #@+node:pap.20070203004134:@thin vb2pyGUI.rsrc.py {'application':{'type':'Application', 'name':'Template', 'backgrounds': [ {'type':'Background', 'name':'vb2pyGUI', 'title':'vb2Py : VB to Python Conversion Toolkit', 'position':(340, 102), 'size':(608, 637), 'style':['resizeable'], 'menubar': {'type':'MenuBar', 'menus': [ {'type':'Menu', 'name':'menuFile', 'label':'&File', 'items': [ {'type':'MenuItem', 'name':'menuFileOpen', 'label':'&Open\tCtrl+O', }, {'type':'MenuItem', 'name':'menuFileSave', 'label':'&Save\tCtrl+S', }, {'type':'MenuItem', 'name':'menuFileExit', 'label':'E&xit\tCtrl+X', }, ] }, {'type':'Menu', 'name':'menuEdit', 'label':'Edit', 'items': [ {'type':'MenuItem', 'name':'menuFind', 'label':'Find\tCtrl+F', }, {'type':'MenuItem', 'name':'menuFindNext', 'label':'Find next\tF3', }, ] }, {'type':'Menu', 'name':'menuView', 'label':'View', 'items': [ {'type':'MenuItem', 'name':'menuOptions', 'label':'Options ...', }, {'type':'MenuItem', 'name':'menuViewStructure', 'label':'View Structure', }, {'type':'MenuItem', 'name':'menuTestView', 'label':'Testing Window', }, ] }, {'type':'Menu', 'name':'menuConversion', 'label':'Convert', 'items': [ {'type':'MenuItem', 'name':'menuConvert', 'label':'Convert active\tCtrl+A', }, {'type':'MenuItem', 'name':'menuConvertSelection', 'label':'Convert selection\tCtrl+Shift+S', }, {'type':'MenuItem', 'name':'menuSep1', 'label':'-', }, {'type':'MenuItem', 'name':'menuCodeModuleContext', 'label':'Code Module', 'checkable':1, 'checked':1, }, {'type':'MenuItem', 'name':'menuClassModuleContext', 'label':'Class Module', 'checkable':1, }, {'type':'MenuItem', 'name':'menuFormModuleContext', 'label':'Form Module', 'checkable':1, }, ] }, {'type':'Menu', 'name':'menuHelp', 'label':'Help', 'items': [ {'type':'MenuItem', 'name':'menuHelp', 'label':'vb2Py Help\tF1', }, {'type':'MenuItem', 'name':'menuHelpGUI', 'label':'GUI Help', }, {'type':'MenuItem', 'name':'menuSep2', 'label':'-', }, {'type':'MenuItem', 'name':'menuAbout', 'label':'About vb2Py', }, ] }, ] }, 'components': [ {'type':'StaticText', 'name':'txtStatus', 'position':(3, 560), 'size':(191, 16), 'text':'Loading file ...', 'visible':0, }, {'type':'Gauge', 'name':'prgProgress', 'position':(199, 558), 'size':(394, 19), 'layout':'horizontal', 'max':100, 'value':0, 'visible':0, }, {'type':'TextArea', 'name':'logWindow', 'position':(0, 455), 'size':(595, 100), 'alignment':'left', 'backgroundColor':(204, 204, 255), 'editable':0, }, {'type':'TextArea', 'name':'vbText', 'position':(270, 0), 'size':(325, 181), 'alignment':'left', 'font':{'faceName': 'Courier New', 'family': 'sansSerif', 'size': 8}, }, {'type':'CodeEditor', 'name':'pythonText', 'position':(269, 186), 'size':(325, 270), 'backgroundColor':(255, 255, 255), }, {'type':'Tree', 'name':'parseTree', 'position':(0, 0), 'size':(264, 455), 'backgroundColor':(255, 255, 255), 'command':'treeClick', }, ] # end components } # end background ] # end backgrounds } } #@-node:pap.20070203004134:@thin vb2pyGUI.rsrc.py #@-leo
{"/vb2py/PythonCard/twistedModel.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/dialog.py": ["/vb2py/PythonCard/font.py"], "/vb2py/test/testall.py": ["/vb2py/utils.py"], "/vb2py/PythonCard/component.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testsubs.py": ["/vb2py/test/testframework.py"], "/vb2py/PythonCard/event.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/resource.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/sandbox/makewebsite.py": ["/vb2py/utils.py"], "/vb2py/test/testgrammarmodes.py": ["/vb2py/utils.py", "/vb2py/parserclasses.py"], "/vb2py/test_at_scale/file_tester.py": ["/vb2py/parserclasses.py", "/vb2py/conversionserver.py"], "/vb2py/vbfunctions.py": ["/vb2py/PythonCard/graphic.py"], "/vb2py/test/testlanguagedetection.py": ["/vb2py/conversionserver.py"], "/vb2py/test/testframework.py": ["/vb2py/vbfunctions.py", "/vb2py/parserclasses.py"], "/vb2py/test/testdirectives.py": ["/vb2py/test/testframework.py"], "/vb2py/test/testifs.py": ["/vb2py/test/testframework.py"], "/vb2py/test/testfailures.py": ["/vb2py/test/testframework.py"], "/vb2py/PythonCard/model.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testdotnet_execution.py": ["/vb2py/test/testframework.py", "/vb2py/utils.py", "/vb2py/parserclasses.py"], "/vb2py/sandbox/commandline.py": ["/vb2py/parserclasses.py"], "/vb2py/PythonCard/menu.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test_at_scale/retest_failures.py": ["/vb2py/utils.py"], "/vb2py/test/testcommandline.py": ["/vb2py/utils.py"], "/vb2py/PythonCard/log.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/debug.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/font.py": ["/vb2py/PythonCard/__init__.py"], "/setup.py": ["/vb2py/utils.py"], "/vb2py/targets/pythoncard/__init__.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testserver.py": ["/vb2py/test/testframework.py", "/vb2py/conversionserver.py", "/vb2py/parserclasses.py", "/vb2py/utils.py", "/vb2py/vbfunctions.py"], "/vb2py/PythonCard/configuration.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testdotnet.py": ["/vb2py/test/testframework.py", "/vb2py/utils.py"]}
17,953,086
VB6Hobbyst7/xl_vb2py
refs/heads/master
/vb2pygui/vb2pyMain.rsrc.py
{'application':{'type':'Application', 'name':'Template', 'backgrounds': [ {'type':'Background', 'name':'Wizard', 'title':'vb2Py : Conversion', 'size':(608, 637), 'backgroundColor':(255, 255, 255), 'style':['resizeable'], 'menubar': {'type':'MenuBar', 'menus': [ {'type':'Menu', 'name':'menuFile', 'label':'&File', 'items': [ {'type':'MenuItem', 'name':'menuFileOpen', 'label':'&Open\tCtrl+O', }, {'type':'MenuItem', 'name':'menuFileSave', 'label':'&Save\tCtrl+S', }, {'type':'MenuItem', 'name':'menuFileExit', 'label':'E&xit\tCtrl+X', }, ] }, {'type':'Menu', 'name':'menuEdit', 'label':'Edit', 'items': [ {'type':'MenuItem', 'name':'menuFind', 'label':'Find\tCtrl+F', }, {'type':'MenuItem', 'name':'menuFindNext', 'label':'Find next\tF3', }, ] }, {'type':'Menu', 'name':'menuView', 'label':'View', 'items': [ {'type':'MenuItem', 'name':'menuOptions', 'label':'Options ...', }, {'type':'MenuItem', 'name':'menuViewStructure', 'label':'View Structure', }, {'type':'MenuItem', 'name':'menuTestView', 'label':'Testing Window', }, ] }, {'type':'Menu', 'name':'menuConversion', 'label':'Convert', 'items': [ {'type':'MenuItem', 'name':'menuConvert', 'label':'Convert active\tCtrl+A', }, {'type':'MenuItem', 'name':'menuConvertSelection', 'label':'Convert selection\tCtrl+Shift+S', }, {'type':'MenuItem', 'name':'menuSep1', 'label':'-', }, {'type':'MenuItem', 'name':'menuCodeModuleContext', 'label':'Code Module', 'checkable':1, 'checked':1, }, {'type':'MenuItem', 'name':'menuClassModuleContext', 'label':'Class Module', 'checkable':1, }, {'type':'MenuItem', 'name':'menuFormModuleContext', 'label':'Form Module', 'checkable':1, }, ] }, {'type':'Menu', 'name':'menuHelp', 'label':'Help', 'items': [ {'type':'MenuItem', 'name':'menuHelp', 'label':'vb2Py Help\tF1', }, {'type':'MenuItem', 'name':'menuHelpGUI', 'label':'GUI Help', }, {'type':'MenuItem', 'name':'menuSep2', 'label':'-', }, {'type':'MenuItem', 'name':'menuAbout', 'label':'About vb2Py', }, ] }, ] }, 'components': [ {'type':'Button', 'name':'GoInteractive', 'position':(231, 108), 'label':'Convert code snippets interactively', }, {'type':'Image', 'name':'Image3', 'position':(80, 381), 'file':'images/project.jpg', }, {'type':'Image', 'name':'Image2', 'position':(86, 214), 'file':'images/file.jpg', }, {'type':'Image', 'name':'Image1', 'position':(91, 69), 'file':'images/interactive.jpg', }, ] # end components } # end background ] # end backgrounds } }
{"/vb2py/PythonCard/twistedModel.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/dialog.py": ["/vb2py/PythonCard/font.py"], "/vb2py/test/testall.py": ["/vb2py/utils.py"], "/vb2py/PythonCard/component.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testsubs.py": ["/vb2py/test/testframework.py"], "/vb2py/PythonCard/event.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/resource.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/sandbox/makewebsite.py": ["/vb2py/utils.py"], "/vb2py/test/testgrammarmodes.py": ["/vb2py/utils.py", "/vb2py/parserclasses.py"], "/vb2py/test_at_scale/file_tester.py": ["/vb2py/parserclasses.py", "/vb2py/conversionserver.py"], "/vb2py/vbfunctions.py": ["/vb2py/PythonCard/graphic.py"], "/vb2py/test/testlanguagedetection.py": ["/vb2py/conversionserver.py"], "/vb2py/test/testframework.py": ["/vb2py/vbfunctions.py", "/vb2py/parserclasses.py"], "/vb2py/test/testdirectives.py": ["/vb2py/test/testframework.py"], "/vb2py/test/testifs.py": ["/vb2py/test/testframework.py"], "/vb2py/test/testfailures.py": ["/vb2py/test/testframework.py"], "/vb2py/PythonCard/model.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testdotnet_execution.py": ["/vb2py/test/testframework.py", "/vb2py/utils.py", "/vb2py/parserclasses.py"], "/vb2py/sandbox/commandline.py": ["/vb2py/parserclasses.py"], "/vb2py/PythonCard/menu.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test_at_scale/retest_failures.py": ["/vb2py/utils.py"], "/vb2py/test/testcommandline.py": ["/vb2py/utils.py"], "/vb2py/PythonCard/log.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/debug.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/font.py": ["/vb2py/PythonCard/__init__.py"], "/setup.py": ["/vb2py/utils.py"], "/vb2py/targets/pythoncard/__init__.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testserver.py": ["/vb2py/test/testframework.py", "/vb2py/conversionserver.py", "/vb2py/parserclasses.py", "/vb2py/utils.py", "/vb2py/vbfunctions.py"], "/vb2py/PythonCard/configuration.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testdotnet.py": ["/vb2py/test/testframework.py", "/vb2py/utils.py"]}
17,953,087
VB6Hobbyst7/xl_vb2py
refs/heads/master
/vb2pygui/testingview.rsrc.py
{'stack':{'type':'Stack', 'name':'Template', 'backgrounds': [ {'type':'Background', 'name':'TestingView', 'title':'Testing View', 'position':(134, 220), 'size':(1013, 613), 'style':['resizeable'], 'menubar': {'type':'MenuBar', 'menus': [ {'type':'Menu', 'name':'menuFile', 'label':'&File', 'items': [ {'type':'MenuItem', 'name':'menuFileExit', 'label':'E&xit', }, ] }, {'type':'Menu', 'name':'menuTest', 'label':'Test', 'items': [ {'type':'MenuItem', 'name':'menuTestCode', 'label':'Test Code\tCtrl+T', }, {'type':'MenuItem', 'name':'menuGeneratePythonScript', 'label':'Generate Python Script\tCtrl+P', }, {'type':'MenuItem', 'name':'menuGenerateVBScript', 'label':'Generate VB Script\tCtrl+B', }, ] }, ] }, 'components': [ {'type':'StaticText', 'name':'ResultLabel', 'position':(605, 3), 'size':(109, 17), 'text':'Results', }, {'type':'StaticText', 'name':'PythonLabel', 'position':(322, 4), 'size':(155, 18), 'text':'Python Code', }, {'type':'StaticText', 'name':'VBLabel', 'position':(11, 6), 'size':(113, 17), 'text':'VB Code', }, {'type':'TextArea', 'name':'ResultsView', 'position':(599, 21), 'size':(328, 449), 'alignment':'left', }, {'type':'CodeEditor', 'name':'PythonCodeEditor', 'position':(311, 23), 'size':(279, 452), 'backgroundColor':(255, 255, 255), }, {'type':'CodeEditor', 'name':'VBCodeEditor', 'position':(13, 28), 'size':(296, 452), 'backgroundColor':(255, 255, 255), }, ] # end components } # end background ] # end backgrounds } }
{"/vb2py/PythonCard/twistedModel.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/dialog.py": ["/vb2py/PythonCard/font.py"], "/vb2py/test/testall.py": ["/vb2py/utils.py"], "/vb2py/PythonCard/component.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testsubs.py": ["/vb2py/test/testframework.py"], "/vb2py/PythonCard/event.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/resource.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/sandbox/makewebsite.py": ["/vb2py/utils.py"], "/vb2py/test/testgrammarmodes.py": ["/vb2py/utils.py", "/vb2py/parserclasses.py"], "/vb2py/test_at_scale/file_tester.py": ["/vb2py/parserclasses.py", "/vb2py/conversionserver.py"], "/vb2py/vbfunctions.py": ["/vb2py/PythonCard/graphic.py"], "/vb2py/test/testlanguagedetection.py": ["/vb2py/conversionserver.py"], "/vb2py/test/testframework.py": ["/vb2py/vbfunctions.py", "/vb2py/parserclasses.py"], "/vb2py/test/testdirectives.py": ["/vb2py/test/testframework.py"], "/vb2py/test/testifs.py": ["/vb2py/test/testframework.py"], "/vb2py/test/testfailures.py": ["/vb2py/test/testframework.py"], "/vb2py/PythonCard/model.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testdotnet_execution.py": ["/vb2py/test/testframework.py", "/vb2py/utils.py", "/vb2py/parserclasses.py"], "/vb2py/sandbox/commandline.py": ["/vb2py/parserclasses.py"], "/vb2py/PythonCard/menu.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test_at_scale/retest_failures.py": ["/vb2py/utils.py"], "/vb2py/test/testcommandline.py": ["/vb2py/utils.py"], "/vb2py/PythonCard/log.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/debug.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/font.py": ["/vb2py/PythonCard/__init__.py"], "/setup.py": ["/vb2py/utils.py"], "/vb2py/targets/pythoncard/__init__.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testserver.py": ["/vb2py/test/testframework.py", "/vb2py/conversionserver.py", "/vb2py/parserclasses.py", "/vb2py/utils.py", "/vb2py/vbfunctions.py"], "/vb2py/PythonCard/configuration.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testdotnet.py": ["/vb2py/test/testframework.py", "/vb2py/utils.py"]}
17,953,088
VB6Hobbyst7/xl_vb2py
refs/heads/master
/vb2pygui/vb2pyOptions.rsrc.py
{'type':'CustomDialog', 'name':'vb2PyOptions', 'title':'vb2Py : Options', 'position':(503, 41), 'size':(736, 599), 'components': [ {'type':'Button', 'name':'btnApply', 'position':(490, 519), 'label':'Apply', }, {'type':'CodeEditor', 'name':'optionText', 'position':(10, 10), 'size':(710, 506), 'backgroundColor':(255, 255, 255), }, {'type':'Button', 'id':5100, 'name':'btnOK', 'position':(646, 519), 'label':'OK', }, {'type':'Button', 'id':5101, 'name':'btnCancel', 'position':(569, 519), 'label':'Cancel', }, ] # end components } # end CustomDialog
{"/vb2py/PythonCard/twistedModel.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/dialog.py": ["/vb2py/PythonCard/font.py"], "/vb2py/test/testall.py": ["/vb2py/utils.py"], "/vb2py/PythonCard/component.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testsubs.py": ["/vb2py/test/testframework.py"], "/vb2py/PythonCard/event.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/resource.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/sandbox/makewebsite.py": ["/vb2py/utils.py"], "/vb2py/test/testgrammarmodes.py": ["/vb2py/utils.py", "/vb2py/parserclasses.py"], "/vb2py/test_at_scale/file_tester.py": ["/vb2py/parserclasses.py", "/vb2py/conversionserver.py"], "/vb2py/vbfunctions.py": ["/vb2py/PythonCard/graphic.py"], "/vb2py/test/testlanguagedetection.py": ["/vb2py/conversionserver.py"], "/vb2py/test/testframework.py": ["/vb2py/vbfunctions.py", "/vb2py/parserclasses.py"], "/vb2py/test/testdirectives.py": ["/vb2py/test/testframework.py"], "/vb2py/test/testifs.py": ["/vb2py/test/testframework.py"], "/vb2py/test/testfailures.py": ["/vb2py/test/testframework.py"], "/vb2py/PythonCard/model.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testdotnet_execution.py": ["/vb2py/test/testframework.py", "/vb2py/utils.py", "/vb2py/parserclasses.py"], "/vb2py/sandbox/commandline.py": ["/vb2py/parserclasses.py"], "/vb2py/PythonCard/menu.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test_at_scale/retest_failures.py": ["/vb2py/utils.py"], "/vb2py/test/testcommandline.py": ["/vb2py/utils.py"], "/vb2py/PythonCard/log.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/debug.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/font.py": ["/vb2py/PythonCard/__init__.py"], "/setup.py": ["/vb2py/utils.py"], "/vb2py/targets/pythoncard/__init__.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testserver.py": ["/vb2py/test/testframework.py", "/vb2py/conversionserver.py", "/vb2py/parserclasses.py", "/vb2py/utils.py", "/vb2py/vbfunctions.py"], "/vb2py/PythonCard/configuration.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testdotnet.py": ["/vb2py/test/testframework.py", "/vb2py/utils.py"]}
17,953,089
VB6Hobbyst7/xl_vb2py
refs/heads/master
/vb2pygui/vb2pyOptions.py
#@+leo-ver=4-thin #@+node:pap.20070203003353:@thin vb2pyOptions.py #@<< vb2pyOptions declarations >> #@+node:pap.20070203003353.1:<< vb2pyOptions declarations >> #!/usr/bin/python __version__ = "0.1" from wxPython import wx from PythonCard import model, dialog from vb2py import converter, vbparser, utils import os import time #@-node:pap.20070203003353.1:<< vb2pyOptions declarations >> #@nl #@+others #@+node:pap.20070203003353.2:class vb2pyOptions class vb2pyOptions(model.CustomDialog): """GUI for the vb2Py converter""" #@ @+others #@+node:pap.20070203003353.3:__init__ def __init__(self, logger, *args, **kw): """Load the options file""" model.CustomDialog.__init__(self, *args, **kw) self.log = logger self.log.info("Opening INI file") fle = open(utils.relativePath("vb2py.ini"), "r") try: text = fle.read() self.components.optionText.text = text finally: fle.close() #@-node:pap.20070203003353.3:__init__ #@+node:pap.20070203003353.4:on_btnOK_mouseClick def on_btnOK_mouseClick(self, event): """Pressed OK""" self.saveINI() self.Close() #@-node:pap.20070203003353.4:on_btnOK_mouseClick #@+node:pap.20070203003353.5:saveINI def saveINI(self): """Save the INI file""" self.log.info("Saving INI file") fle = open(utils.relativePath("vb2py.ini"), "w") try: fle.write(self.components.optionText.text) self.log.info("Succeeded!") finally: fle.close() #@-node:pap.20070203003353.5:saveINI #@+node:pap.20070203003353.6:on_btnApply_mouseClick def on_btnApply_mouseClick(self, event): """User clicked the apply button""" self.saveINI() self.parent.rereadOptions() self.parent.updateView() #@-node:pap.20070203003353.6:on_btnApply_mouseClick #@-others #@-node:pap.20070203003353.2:class vb2pyOptions #@-others if __name__ == '__main__': app = model.PythonCardApp(vb2pyOptions) app.MainLoop() #@-node:pap.20070203003353:@thin vb2pyOptions.py #@-leo
{"/vb2py/PythonCard/twistedModel.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/dialog.py": ["/vb2py/PythonCard/font.py"], "/vb2py/test/testall.py": ["/vb2py/utils.py"], "/vb2py/PythonCard/component.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testsubs.py": ["/vb2py/test/testframework.py"], "/vb2py/PythonCard/event.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/resource.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/sandbox/makewebsite.py": ["/vb2py/utils.py"], "/vb2py/test/testgrammarmodes.py": ["/vb2py/utils.py", "/vb2py/parserclasses.py"], "/vb2py/test_at_scale/file_tester.py": ["/vb2py/parserclasses.py", "/vb2py/conversionserver.py"], "/vb2py/vbfunctions.py": ["/vb2py/PythonCard/graphic.py"], "/vb2py/test/testlanguagedetection.py": ["/vb2py/conversionserver.py"], "/vb2py/test/testframework.py": ["/vb2py/vbfunctions.py", "/vb2py/parserclasses.py"], "/vb2py/test/testdirectives.py": ["/vb2py/test/testframework.py"], "/vb2py/test/testifs.py": ["/vb2py/test/testframework.py"], "/vb2py/test/testfailures.py": ["/vb2py/test/testframework.py"], "/vb2py/PythonCard/model.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testdotnet_execution.py": ["/vb2py/test/testframework.py", "/vb2py/utils.py", "/vb2py/parserclasses.py"], "/vb2py/sandbox/commandline.py": ["/vb2py/parserclasses.py"], "/vb2py/PythonCard/menu.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test_at_scale/retest_failures.py": ["/vb2py/utils.py"], "/vb2py/test/testcommandline.py": ["/vb2py/utils.py"], "/vb2py/PythonCard/log.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/debug.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/font.py": ["/vb2py/PythonCard/__init__.py"], "/setup.py": ["/vb2py/utils.py"], "/vb2py/targets/pythoncard/__init__.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testserver.py": ["/vb2py/test/testframework.py", "/vb2py/conversionserver.py", "/vb2py/parserclasses.py", "/vb2py/utils.py", "/vb2py/vbfunctions.py"], "/vb2py/PythonCard/configuration.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testdotnet.py": ["/vb2py/test/testframework.py", "/vb2py/utils.py"]}
17,953,090
VB6Hobbyst7/xl_vb2py
refs/heads/master
/website/docs/__init__.py
# Created by Leo from: C:\Development\Python22\Lib\site-packages\vb2py\vb2py.leo pass
{"/vb2py/PythonCard/twistedModel.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/dialog.py": ["/vb2py/PythonCard/font.py"], "/vb2py/test/testall.py": ["/vb2py/utils.py"], "/vb2py/PythonCard/component.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testsubs.py": ["/vb2py/test/testframework.py"], "/vb2py/PythonCard/event.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/resource.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/sandbox/makewebsite.py": ["/vb2py/utils.py"], "/vb2py/test/testgrammarmodes.py": ["/vb2py/utils.py", "/vb2py/parserclasses.py"], "/vb2py/test_at_scale/file_tester.py": ["/vb2py/parserclasses.py", "/vb2py/conversionserver.py"], "/vb2py/vbfunctions.py": ["/vb2py/PythonCard/graphic.py"], "/vb2py/test/testlanguagedetection.py": ["/vb2py/conversionserver.py"], "/vb2py/test/testframework.py": ["/vb2py/vbfunctions.py", "/vb2py/parserclasses.py"], "/vb2py/test/testdirectives.py": ["/vb2py/test/testframework.py"], "/vb2py/test/testifs.py": ["/vb2py/test/testframework.py"], "/vb2py/test/testfailures.py": ["/vb2py/test/testframework.py"], "/vb2py/PythonCard/model.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testdotnet_execution.py": ["/vb2py/test/testframework.py", "/vb2py/utils.py", "/vb2py/parserclasses.py"], "/vb2py/sandbox/commandline.py": ["/vb2py/parserclasses.py"], "/vb2py/PythonCard/menu.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test_at_scale/retest_failures.py": ["/vb2py/utils.py"], "/vb2py/test/testcommandline.py": ["/vb2py/utils.py"], "/vb2py/PythonCard/log.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/debug.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/font.py": ["/vb2py/PythonCard/__init__.py"], "/setup.py": ["/vb2py/utils.py"], "/vb2py/targets/pythoncard/__init__.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testserver.py": ["/vb2py/test/testframework.py", "/vb2py/conversionserver.py", "/vb2py/parserclasses.py", "/vb2py/utils.py", "/vb2py/vbfunctions.py"], "/vb2py/PythonCard/configuration.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testdotnet.py": ["/vb2py/test/testframework.py", "/vb2py/utils.py"]}
17,953,091
VB6Hobbyst7/xl_vb2py
refs/heads/master
/vb2pygui/setup.py
"""Install vb2Py GUI Much of the following code is copied from the PythonCard installation script because the original setup.py would copy files to all sorts of weird location on Linux. You must run this to create the setup distribution from the site-packages! """ WIN_DEFAULT_COMMAND = "install" APPLICATION_NAME = "vb2pygui" from distutils.core import setup from distutils.command.install_data import install_data import glob, os, sys if len(sys.argv) == 1 and sys.platform.startswith("win"): sys.argv.append(WIN_DEFAULT_COMMAND) """ This script is setup.py of the vb2py package. """ class smart_install_data(install_data): def run(self): #need to change self.install_dir to the actual library dir install_cmd = self.get_finalized_command('install') self.install_dir = getattr(install_cmd, 'install_lib') return install_data.run(self) def recurseDir(startDir): # This should all be replaced by calls to os.path.walk, but later listX=[startDir] for fyle in os.listdir(startDir): file=os.path.join(startDir,fyle) if os.path.isdir(file): listX.extend(recurseDir(file)) return listX def makeDataDirs(rootDir=APPLICATION_NAME, dataDirs=[]): "Construct a list of the data directories to be included" # This function will return a list of tuples, each tuple being of the form; # ( <target_directory_name>, [<list_of_files>] ) listX=[] results=[] for directory in dataDirs: directories=recurseDir(directory) results.extend(directories) for directory in results: if os.path.split(directory)[1]!='CVS': # Add this directory and its contents to list files=[] for file in os.listdir(directory): if file!='CVS' and file!='.cvsignore' and os.path.splitext(file)[1].lower() <> ".htm": if os.path.isfile(os.path.join(directory, file)): files.append(os.path.join(directory, file)) listX.append((rootDir+'/'+directory, files)) # list.append((rootDir, 'stc_styles.cfg')) return listX setup(name=APPLICATION_NAME, version="0.2.1", description="Visual Basic to Python Converter GUI", author="Paul Paterson", author_email="paulpaterson@users.sourceforge.net", url="http://vb2py.sourceforge.net", packages=["vb2pygui",], package_dir={APPLICATION_NAME: '.'}, license="BSD", cmdclass = { 'install_data': smart_install_data}, data_files=makeDataDirs(dataDirs=[".",]), )
{"/vb2py/PythonCard/twistedModel.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/dialog.py": ["/vb2py/PythonCard/font.py"], "/vb2py/test/testall.py": ["/vb2py/utils.py"], "/vb2py/PythonCard/component.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testsubs.py": ["/vb2py/test/testframework.py"], "/vb2py/PythonCard/event.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/resource.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/sandbox/makewebsite.py": ["/vb2py/utils.py"], "/vb2py/test/testgrammarmodes.py": ["/vb2py/utils.py", "/vb2py/parserclasses.py"], "/vb2py/test_at_scale/file_tester.py": ["/vb2py/parserclasses.py", "/vb2py/conversionserver.py"], "/vb2py/vbfunctions.py": ["/vb2py/PythonCard/graphic.py"], "/vb2py/test/testlanguagedetection.py": ["/vb2py/conversionserver.py"], "/vb2py/test/testframework.py": ["/vb2py/vbfunctions.py", "/vb2py/parserclasses.py"], "/vb2py/test/testdirectives.py": ["/vb2py/test/testframework.py"], "/vb2py/test/testifs.py": ["/vb2py/test/testframework.py"], "/vb2py/test/testfailures.py": ["/vb2py/test/testframework.py"], "/vb2py/PythonCard/model.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testdotnet_execution.py": ["/vb2py/test/testframework.py", "/vb2py/utils.py", "/vb2py/parserclasses.py"], "/vb2py/sandbox/commandline.py": ["/vb2py/parserclasses.py"], "/vb2py/PythonCard/menu.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test_at_scale/retest_failures.py": ["/vb2py/utils.py"], "/vb2py/test/testcommandline.py": ["/vb2py/utils.py"], "/vb2py/PythonCard/log.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/debug.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/font.py": ["/vb2py/PythonCard/__init__.py"], "/setup.py": ["/vb2py/utils.py"], "/vb2py/targets/pythoncard/__init__.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testserver.py": ["/vb2py/test/testframework.py", "/vb2py/conversionserver.py", "/vb2py/parserclasses.py", "/vb2py/utils.py", "/vb2py/vbfunctions.py"], "/vb2py/PythonCard/configuration.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testdotnet.py": ["/vb2py/test/testframework.py", "/vb2py/utils.py"]}
17,953,092
VB6Hobbyst7/xl_vb2py
refs/heads/master
/vb2pygui/interactive.py
#@+leo-ver=4-thin #@+node:pap.20070203172243.1:@thin interactive.py #@<< interactive declarations >> #@+node:pap.20070203172243.2:<< interactive declarations >> #!/usr/bin/python from vb2py import converter, vbparser, config, utils from vb2pyGUI import LogInterceptor from PythonCard import model #@-node:pap.20070203172243.2:<< interactive declarations >> #@nl #@+others #@+node:pap.20070203172243.3:class Interactive class Interactive(model.Background): #@ @+others #@+node:pap.20070203172243.4:on_initialize def on_initialize(self, event): self.log = converter.log = vbparser.log = LogInterceptor(self.logText) # Redirect logs to our window self.components.VB.SetLexerLanguage("vb") self.components.Python.SetLexerLanguage("python") self.components.VBPane.Raise() #@-node:pap.20070203172243.4:on_initialize #@+node:pap.20070203175538:on_Convert_mouseClick def on_Convert_mouseClick(self, event): """Convert the code""" self.components.VBPane.Raise() text = self.getSelectedText() self.logText("Converting code") print self.components.CodeContext.stringSelection try: py = vbparser.parseVB(text, container=self.getConversionContext()) py_text = py.renderAsCode() self.components.Python.text = py_text except Exception, err: err_msg = "Unable to parse: '%s'" % err self.logText(err_msg) self.components.Python.text = err_msg else: self.logText("Succeeded!") #@-node:pap.20070203175538:on_Convert_mouseClick #@+node:pap.20070203185350:on_HelpConvertAs_mouseClick def on_HelpConvertAs_mouseClick(self, event): """Help on converting as""" print "hello" #@nonl #@-node:pap.20070203185350:on_HelpConvertAs_mouseClick #@+node:pap.20070203185511:on_HelpConversionStyle_mouseClick def on_HelpConversionStyle_mouseClick(self, event): """Help on converting as""" print "hello" #@nonl #@-node:pap.20070203185511:on_HelpConversionStyle_mouseClick #@+node:pap.20070203185706:on_CodeContext_mouseEnter def on_CodeContext_mouseEnter(self, event): """Mouse over the code context""" print "Over!" #@nonl #@-node:pap.20070203185706:on_CodeContext_mouseEnter #@+node:pap.20070203175538.1:getSelectedText def getSelectedText(self): """Return the highlighted text or the whole thing if not selected""" start, finish = self.components.VB.GetSelection() if start < finish: text = self.components.VB.text[start:finish] else: text = self.components.VB.text return text #@-node:pap.20070203175538.1:getSelectedText #@+node:pap.20070203191301:getConversionContext def getConversionContext(self): """Return the current conversion context""" contexts = { "Code module" : vbparser.VBCodeModule, "Class module" : vbparser.VBClassModule, "Form" : vbparser.VBFormModule, } return contexts[self.components.CodeContext.stringSelection]() #@nonl #@-node:pap.20070203191301:getConversionContext #@+node:pap.20070203175538.2:logText def logText(self, text): """Log some text""" self.components.LogWindow.AppendText("%s\n" % text) #@nonl #@-node:pap.20070203175538.2:logText #@-others #@-node:pap.20070203172243.3:class Interactive #@-others if __name__ == '__main__': app = model.Application(Interactive) app.MainLoop() #@-node:pap.20070203172243.1:@thin interactive.py #@-leo
{"/vb2py/PythonCard/twistedModel.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/dialog.py": ["/vb2py/PythonCard/font.py"], "/vb2py/test/testall.py": ["/vb2py/utils.py"], "/vb2py/PythonCard/component.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testsubs.py": ["/vb2py/test/testframework.py"], "/vb2py/PythonCard/event.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/resource.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/sandbox/makewebsite.py": ["/vb2py/utils.py"], "/vb2py/test/testgrammarmodes.py": ["/vb2py/utils.py", "/vb2py/parserclasses.py"], "/vb2py/test_at_scale/file_tester.py": ["/vb2py/parserclasses.py", "/vb2py/conversionserver.py"], "/vb2py/vbfunctions.py": ["/vb2py/PythonCard/graphic.py"], "/vb2py/test/testlanguagedetection.py": ["/vb2py/conversionserver.py"], "/vb2py/test/testframework.py": ["/vb2py/vbfunctions.py", "/vb2py/parserclasses.py"], "/vb2py/test/testdirectives.py": ["/vb2py/test/testframework.py"], "/vb2py/test/testifs.py": ["/vb2py/test/testframework.py"], "/vb2py/test/testfailures.py": ["/vb2py/test/testframework.py"], "/vb2py/PythonCard/model.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testdotnet_execution.py": ["/vb2py/test/testframework.py", "/vb2py/utils.py", "/vb2py/parserclasses.py"], "/vb2py/sandbox/commandline.py": ["/vb2py/parserclasses.py"], "/vb2py/PythonCard/menu.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test_at_scale/retest_failures.py": ["/vb2py/utils.py"], "/vb2py/test/testcommandline.py": ["/vb2py/utils.py"], "/vb2py/PythonCard/log.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/debug.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/font.py": ["/vb2py/PythonCard/__init__.py"], "/setup.py": ["/vb2py/utils.py"], "/vb2py/targets/pythoncard/__init__.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testserver.py": ["/vb2py/test/testframework.py", "/vb2py/conversionserver.py", "/vb2py/parserclasses.py", "/vb2py/utils.py", "/vb2py/vbfunctions.py"], "/vb2py/PythonCard/configuration.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testdotnet.py": ["/vb2py/test/testframework.py", "/vb2py/utils.py"]}
17,953,093
VB6Hobbyst7/xl_vb2py
refs/heads/master
/vb2pygui/vb2pyMain.py
#@+leo-ver=4-thin #@+node:pap.20070203162417.1:@thin vb2pyMain.py #@<< vb2pyUI declarations >> #@+node:pap.20070203162417.2:<< vb2pyUI declarations >> """ __version__ = "$Revision: 1.3 $" __date__ = "$Date: 2004/08/12 19:14:23 $" """ from PythonCard import model import interactive #@-node:pap.20070203162417.2:<< vb2pyUI declarations >> #@nl #@+others #@+node:pap.20070203162417.3:class UI class UI(model.Background): """vb2Py UI for doing conversion""" #@ @+others #@+node:pap.20070203172243:on_GoInteractive_mouseClick def on_GoInteractive_mouseClick(self, event): """Hit the interactive button""" form = model.childWindow(self, interactive.Interactive) form.visible = True #@-node:pap.20070203172243:on_GoInteractive_mouseClick #@-others #@-node:pap.20070203162417.3:class UI #@-others if __name__ == '__main__': app = model.Application(UI) app.MainLoop() #@-node:pap.20070203162417.1:@thin vb2pyMain.py #@-leo
{"/vb2py/PythonCard/twistedModel.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/dialog.py": ["/vb2py/PythonCard/font.py"], "/vb2py/test/testall.py": ["/vb2py/utils.py"], "/vb2py/PythonCard/component.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testsubs.py": ["/vb2py/test/testframework.py"], "/vb2py/PythonCard/event.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/resource.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/sandbox/makewebsite.py": ["/vb2py/utils.py"], "/vb2py/test/testgrammarmodes.py": ["/vb2py/utils.py", "/vb2py/parserclasses.py"], "/vb2py/test_at_scale/file_tester.py": ["/vb2py/parserclasses.py", "/vb2py/conversionserver.py"], "/vb2py/vbfunctions.py": ["/vb2py/PythonCard/graphic.py"], "/vb2py/test/testlanguagedetection.py": ["/vb2py/conversionserver.py"], "/vb2py/test/testframework.py": ["/vb2py/vbfunctions.py", "/vb2py/parserclasses.py"], "/vb2py/test/testdirectives.py": ["/vb2py/test/testframework.py"], "/vb2py/test/testifs.py": ["/vb2py/test/testframework.py"], "/vb2py/test/testfailures.py": ["/vb2py/test/testframework.py"], "/vb2py/PythonCard/model.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testdotnet_execution.py": ["/vb2py/test/testframework.py", "/vb2py/utils.py", "/vb2py/parserclasses.py"], "/vb2py/sandbox/commandline.py": ["/vb2py/parserclasses.py"], "/vb2py/PythonCard/menu.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test_at_scale/retest_failures.py": ["/vb2py/utils.py"], "/vb2py/test/testcommandline.py": ["/vb2py/utils.py"], "/vb2py/PythonCard/log.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/debug.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/PythonCard/font.py": ["/vb2py/PythonCard/__init__.py"], "/setup.py": ["/vb2py/utils.py"], "/vb2py/targets/pythoncard/__init__.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testserver.py": ["/vb2py/test/testframework.py", "/vb2py/conversionserver.py", "/vb2py/parserclasses.py", "/vb2py/utils.py", "/vb2py/vbfunctions.py"], "/vb2py/PythonCard/configuration.py": ["/vb2py/PythonCard/__init__.py"], "/vb2py/test/testdotnet.py": ["/vb2py/test/testframework.py", "/vb2py/utils.py"]}
17,993,268
katiechambe/chemical-torus-imaging
refs/heads/main
/scripts/bootstrap_optimize.py
# Standard library import atexit import os os.environ["OMP_NUM_THREADS"] = "1" import sys import traceback # Third-party from astropy.utils import iers iers.conf.auto_download = False import astropy.table as at import numpy as np # This project from totoro.config import cache_path from totoro.data import datasets, elem_names from totoro.objective import TorusImagingObjective def worker(task): i, obj, x0, tmp_filename = task res = None try: res = obj.minimize(x0=x0, method="nelder-mead", options=dict(maxiter=250)) print(f"{i} finished optimizing: {res}") except Exception as e: print(f"{i} failed: {str(e)}") traceback.print_exc() if res is None or not res.success: xopt = np.nan * np.array(x0) else: xopt = res.x xopt = { 'zsun': [xopt[0]], 'vzsun': [xopt[1]], 'mdisk_f': [xopt[2]], 'disk_hz': [xopt[3]], } at.Table(xopt).write(tmp_filename, overwrite=True) return tmp_filename def combine_output(all_filename, this_cache_path, elem_name): import glob cache_glob_pattr = str(this_cache_path / f'tmp-*{elem_name}*.csv') if os.path.exists(all_filename): prev_table = at.Table.read(all_filename) else: prev_table = None # combine the individual worker cache files all_tables = [] remove_filenames = [] for filename in glob.glob(cache_glob_pattr): all_tables.append(at.Table.read(filename)) remove_filenames.append(filename) if all_tables: all_table = at.vstack(all_tables) else: return if prev_table: all_table = at.vstack((prev_table, all_table)) all_table.write(all_filename, overwrite=True) for filename in remove_filenames: os.unlink(filename) def main(pool, overwrite=False): tree_K = 32 # MAGIC NUMBER: set heuristically in Objective-function.ipynb bootstrap_K = 128 # MAGIC NUMBER for data_name, d in datasets.items(): # TODO: make seed configurable? rnd = np.random.default_rng(seed=42) # loop over all elements tasks = [] cache_paths = [] cache_filenames = [] for elem_name in elem_names[data_name]: print(f"Running element: {elem_name}") # TODO: if galah in data_name, filter on flag?? this_cache_path = cache_path / data_name this_cache_filename = (this_cache_path / f'optimize-results-{elem_name}.csv') if this_cache_filename.exists() and not overwrite: print(f"Cache file exists for {elem_name}: " f"{this_cache_filename}") continue atexit.register(combine_output, this_cache_filename, this_cache_path, elem_name) cache_paths.append(this_cache_path) cache_filenames.append(this_cache_filename) # print("Optimizing with full sample to initialize bootstraps...") # obj = TorusImagingObjective(d.t, d.c, elem_name, tree_K=tree_K) # full_sample_res = obj.minimize(method="nelder-mead", # options=dict(maxiter=1024)) # if not full_sample_res.success: # print(f"FAILED TO CONVERGE: optimize for full sample failed " # f"for {elem_name}") # continue # print(f"Finished optimizing full sample: {full_sample_res.x}") # x0 = full_sample_res.x x0 = np.array([20.8, 7.78, 1.1, 0.28]) # HACK: init from fiducial for k in range(bootstrap_K): idx = rnd.choice(len(d), len(d), replace=True) obj = TorusImagingObjective(d[idx], elem_name, tree_K=tree_K) tmp_filename = (this_cache_path / f'tmp-optimize-results-{elem_name}-{k}.csv') tasks.append((k, obj, x0, tmp_filename)) print("Done setting up bootstrap samples - running pool.map() on " f"{len(tasks)} tasks") for _ in pool.map(worker, tasks): pass for this_cache_filename, this_cache_path, elem_name in zip( cache_filenames, cache_paths, elem_names[data_name]): combine_output(this_cache_filename, this_cache_path, elem_name) sys.exit(0) if __name__ == '__main__': from argparse import ArgumentParser # Define parser object parser = ArgumentParser() parser.add_argument("-o", "--overwrite", dest="overwrite", action="store_true") # vq_group = parser.add_mutually_exclusive_group() # vq_group.add_argument('-v', '--verbose', action='count', default=0, # dest='verbosity') # vq_group.add_argument('-q', '--quiet', action='count', default=0, # dest='quietness') group = parser.add_mutually_exclusive_group() group.add_argument("--procs", dest="n_procs", default=1, type=int, help="Number of processes.") group.add_argument("--mpi", dest="mpi", default=False, action="store_true", help="Run with MPI.") parsed = parser.parse_args() # deal with multiproc: if parsed.mpi: from schwimmbad.mpi import MPIPool Pool = MPIPool kw = dict() elif parsed.n_procs > 1: from schwimmbad import MultiPool Pool = MultiPool kw = dict(processes=parsed.n_procs) else: from schwimmbad import SerialPool Pool = SerialPool kw = dict() Pool = Pool Pool_kwargs = kw with Pool(**Pool_kwargs) as pool: main(pool=pool, overwrite=parsed.overwrite) sys.exit(0)
{"/thriftshop/actions.py": ["/thriftshop/galpy_helpers.py"], "/scripts/bootstrap_optimize.py": ["/totoro/config.py", "/totoro/data.py", "/totoro/objective.py"], "/totoro/tests/test_potentials.py": ["/totoro/config.py", "/totoro/potentials.py"], "/totoro/potentials.py": ["/totoro/config.py"], "/totoro/objective.py": ["/totoro/data.py", "/totoro/config.py", "/totoro/potentials.py", "/totoro/actions_staeckel.py", "/totoro/atm.py"], "/scripts/compute_actions.py": ["/totoro/config.py", "/totoro/data.py", "/totoro/potentials.py", "/totoro/actions_staeckel.py"], "/totoro/data.py": ["/totoro/config.py"], "/totoro/action_helpers.py": ["/totoro/potentials.py", "/totoro/config.py", "/totoro/actions_o2gf.py", "/totoro/actions_staeckel.py"], "/totoro/actions_staeckel.py": ["/totoro/config.py", "/totoro/galpy_helpers.py"], "/totoro/galpy_helpers.py": ["/totoro/config.py"]}
17,993,269
katiechambe/chemical-torus-imaging
refs/heads/main
/totoro/tests/test_potentials.py
import astropy.units as u import numpy as np from ..config import rsun, vcirc from ..potentials import potentials, galpy_potentials def test_vcirc(): for k, p in potentials.items(): assert u.isclose( p.circular_velocity([-rsun.to_value(u.kpc), 0, 0]*u.kpc)[0], vcirc, rtol=1e-5) def galpy_test_helper(gala_pot, galpy_pot): from galpy.potential import (evaluateDensities, evaluatePotentials, evaluatezforces) ntest = 16 Rs = np.random.uniform(1, 15, size=ntest) * u.kpc zs = np.random.uniform(1, 15, size=ntest) * u.kpc xyz = np.zeros((3, Rs.size)) * u.kpc xyz[0] = Rs xyz[2] = zs assert np.allclose( gala_pot.density(xyz).to_value(u.Msun/u.pc**3), evaluateDensities(galpy_pot, R=Rs.to_value(rsun), z=zs.to_value(rsun))) assert np.allclose( gala_pot.energy(xyz).to_value((u.km / u.s)**2), evaluatePotentials(galpy_pot, R=Rs.to_value(rsun), z=zs.to_value(rsun))) assert np.allclose( gala_pot.gradient(xyz).to_value((u.km/u.s) * u.pc/u.Myr / u.pc)[2], -evaluatezforces(galpy_pot, R=Rs.to_value(rsun), z=zs.to_value(rsun))) def test_against_galpy(): for k in potentials: galpy_test_helper(potentials[k], galpy_potentials[k])
{"/thriftshop/actions.py": ["/thriftshop/galpy_helpers.py"], "/scripts/bootstrap_optimize.py": ["/totoro/config.py", "/totoro/data.py", "/totoro/objective.py"], "/totoro/tests/test_potentials.py": ["/totoro/config.py", "/totoro/potentials.py"], "/totoro/potentials.py": ["/totoro/config.py"], "/totoro/objective.py": ["/totoro/data.py", "/totoro/config.py", "/totoro/potentials.py", "/totoro/actions_staeckel.py", "/totoro/atm.py"], "/scripts/compute_actions.py": ["/totoro/config.py", "/totoro/data.py", "/totoro/potentials.py", "/totoro/actions_staeckel.py"], "/totoro/data.py": ["/totoro/config.py"], "/totoro/action_helpers.py": ["/totoro/potentials.py", "/totoro/config.py", "/totoro/actions_o2gf.py", "/totoro/actions_staeckel.py"], "/totoro/actions_staeckel.py": ["/totoro/config.py", "/totoro/galpy_helpers.py"], "/totoro/galpy_helpers.py": ["/totoro/config.py"]}
17,993,270
katiechambe/chemical-torus-imaging
refs/heads/main
/setup.py
import os from setuptools import find_packages, setup setup( name="totoro", use_scm_version={ "write_to": os.path.join("totoro", "version.py"), "write_to_template": '__version__ = "{version}"\n', }, description="Orbital Torus Imaging", author="adrn", author_email="adrianmpw@gmail.com", url="https://github.com/adrn/chemical-torus-imaging", license="MIT", packages=find_packages(), python_requires=">=3.6", # package_data={"totoro": ["data/filename"]}, # include_package_data=True, zip_safe=False, install_requires=[ "numpy", "scipy", "astropy", "matplotlib", "astro-gala", "galpy", "pyia" ] )
{"/thriftshop/actions.py": ["/thriftshop/galpy_helpers.py"], "/scripts/bootstrap_optimize.py": ["/totoro/config.py", "/totoro/data.py", "/totoro/objective.py"], "/totoro/tests/test_potentials.py": ["/totoro/config.py", "/totoro/potentials.py"], "/totoro/potentials.py": ["/totoro/config.py"], "/totoro/objective.py": ["/totoro/data.py", "/totoro/config.py", "/totoro/potentials.py", "/totoro/actions_staeckel.py", "/totoro/atm.py"], "/scripts/compute_actions.py": ["/totoro/config.py", "/totoro/data.py", "/totoro/potentials.py", "/totoro/actions_staeckel.py"], "/totoro/data.py": ["/totoro/config.py"], "/totoro/action_helpers.py": ["/totoro/potentials.py", "/totoro/config.py", "/totoro/actions_o2gf.py", "/totoro/actions_staeckel.py"], "/totoro/actions_staeckel.py": ["/totoro/config.py", "/totoro/galpy_helpers.py"], "/totoro/galpy_helpers.py": ["/totoro/config.py"]}
17,993,271
katiechambe/chemical-torus-imaging
refs/heads/main
/totoro/abundance_helpers.py
def elem_to_label(elem, dollar=True): num, den = elem.split('_') if num.lower() == 'alpha': if den.lower() == 'm': label = r'[\alpha / {\rm M}]' elif den.lower() == 'fe': label = r'[\alpha / {\rm Fe}]' else: label = rf"[{{\rm {num.title()} }} / {{\rm {den.title()} }}]" if dollar: return '$' + label + '$' else: return label
{"/thriftshop/actions.py": ["/thriftshop/galpy_helpers.py"], "/scripts/bootstrap_optimize.py": ["/totoro/config.py", "/totoro/data.py", "/totoro/objective.py"], "/totoro/tests/test_potentials.py": ["/totoro/config.py", "/totoro/potentials.py"], "/totoro/potentials.py": ["/totoro/config.py"], "/totoro/objective.py": ["/totoro/data.py", "/totoro/config.py", "/totoro/potentials.py", "/totoro/actions_staeckel.py", "/totoro/atm.py"], "/scripts/compute_actions.py": ["/totoro/config.py", "/totoro/data.py", "/totoro/potentials.py", "/totoro/actions_staeckel.py"], "/totoro/data.py": ["/totoro/config.py"], "/totoro/action_helpers.py": ["/totoro/potentials.py", "/totoro/config.py", "/totoro/actions_o2gf.py", "/totoro/actions_staeckel.py"], "/totoro/actions_staeckel.py": ["/totoro/config.py", "/totoro/galpy_helpers.py"], "/totoro/galpy_helpers.py": ["/totoro/config.py"]}
17,993,272
katiechambe/chemical-torus-imaging
refs/heads/main
/totoro/potentials.py
from astropy.constants import G import astropy.units as u import numpy as np from scipy.optimize import minimize import gala.potential as gp from .config import fiducial_mdisk, rsun, vcirc def get_mw_potential(mdisk): """ Retrieve a MW potential model with fixed vcirc=229 """ def objfunc(ln_mhalo): mhalo = np.exp(ln_mhalo) tmp_mw = gp.MilkyWayPotential(disk=dict(m=mdisk), halo=dict(m=mhalo)) test_v = tmp_mw.circular_velocity( [-rsun.to_value(u.kpc), 0, 0] * u.kpc).to_value(u.km/u.s)[0] return (vcirc.to_value(u.km/u.s) - test_v) ** 2 minit = potentials['1.0']['halo'].parameters['m'].to_value(u.Msun) res = minimize(objfunc, x0=np.log(minit), method='powell') if not res.success: return np.nan mhalo = np.exp(res.x) return gp.MilkyWayPotential(disk=dict(m=mdisk), halo=dict(m=mhalo)) def get_equivalent_galpy(potential): from galpy.potential import ( MiyamotoNagaiPotential as BovyMiyamotoNagaiPotential, HernquistPotential as BovyHernquistPotential, NFWPotential as BovyNFWPotential) ro = rsun vo = vcirc bovy_pot = {} amp = (G * potential['disk'].parameters['m']).to_value(vo**2 * ro) a = potential['disk'].parameters['a'].to_value(ro) b = potential['disk'].parameters['b'].to_value(ro) bovy_pot['disk'] = BovyMiyamotoNagaiPotential(amp=amp, a=a, b=b, ro=ro, vo=vo) amp = (G * potential['bulge'].parameters['m']).to_value(vo**2 * ro) * 2 c = potential['bulge'].parameters['c'].to_value(ro) bovy_pot['bulge'] = BovyHernquistPotential(amp=amp, a=c, ro=ro, vo=vo) amp = (G * potential['nucleus'].parameters['m']).to_value(vo**2 * ro) * 2 c = potential['nucleus'].parameters['c'].to_value(ro) bovy_pot['nucleus'] = BovyHernquistPotential(amp=amp, a=c, ro=ro, vo=vo) _m = potential['halo'].parameters['m'] amp = (G * _m).to_value(vo**2 * ro) rs = potential['halo'].parameters['r_s'].to_value(ro) bovy_pot['halo'] = BovyNFWPotential(amp=amp, a=rs, ro=ro, vo=vo) return list(bovy_pot.values()) # Set up Milky Way models potentials = dict() potentials['1.0'] = gp.MilkyWayPotential(disk=dict(m=fiducial_mdisk)) facs = np.arange(0.4, 1.8+1e-3, 0.1) # limit 1.8 to get vcirc=229 for fac in facs: name = f'{fac:.1f}' if name in potentials: continue potentials[name] = get_mw_potential(fac * fiducial_mdisk) # Define equivalent galpy potentials: galpy_potentials = dict() for k, p in potentials.items(): galpy_potentials[k] = get_equivalent_galpy(p)
{"/thriftshop/actions.py": ["/thriftshop/galpy_helpers.py"], "/scripts/bootstrap_optimize.py": ["/totoro/config.py", "/totoro/data.py", "/totoro/objective.py"], "/totoro/tests/test_potentials.py": ["/totoro/config.py", "/totoro/potentials.py"], "/totoro/potentials.py": ["/totoro/config.py"], "/totoro/objective.py": ["/totoro/data.py", "/totoro/config.py", "/totoro/potentials.py", "/totoro/actions_staeckel.py", "/totoro/atm.py"], "/scripts/compute_actions.py": ["/totoro/config.py", "/totoro/data.py", "/totoro/potentials.py", "/totoro/actions_staeckel.py"], "/totoro/data.py": ["/totoro/config.py"], "/totoro/action_helpers.py": ["/totoro/potentials.py", "/totoro/config.py", "/totoro/actions_o2gf.py", "/totoro/actions_staeckel.py"], "/totoro/actions_staeckel.py": ["/totoro/config.py", "/totoro/galpy_helpers.py"], "/totoro/galpy_helpers.py": ["/totoro/config.py"]}
17,993,273
katiechambe/chemical-torus-imaging
refs/heads/main
/totoro/objective.py
import pickle import astropy.coordinates as coord import astropy.table as at import astropy.units as u import gala.dynamics as gd import gala.potential as gp import numpy as np from scipy.interpolate import interp1d from scipy.optimize import minimize from tqdm import tqdm from .data import APOGEEDataset from .config import galcen_frame, cache_path from .potentials import fiducial_mdisk, get_mw_potential, get_equivalent_galpy from .actions_staeckel import get_staeckel_aaf from .atm import AbundanceTorusMaschine class TorusImagingObjective: def __init__(self, dataset, elem_name, tree_K=64): self.c = dataset.c # Select out the bare minimum columns: # err_name = dataset._elem_err_fmt.format(elem_name=elem_name) # HACK: all datasets have elem names and errors like APOGEE err_name = APOGEEDataset._elem_err_fmt.format(elem_name=elem_name) self.t = dataset.t[dataset._id_column, elem_name, err_name] mask = np.isfinite(self.t[elem_name]) self.t = self.t[mask] self.c = self.c[mask] self.elem_name = elem_name self._vsun = galcen_frame.galcen_v_sun.d_xyz self._init_potential() self.tree_K = int(tree_K) def _init_potential(self): path = cache_path / 'potential-mhalo-interp.pkl' if not path.exists(): print("Computing potential mhalo grid...") pot_grid = np.arange(0.35, 1.79+1e-3, 0.04) mhalos = [] for mdisk_f in tqdm(pot_grid): pot = get_mw_potential(mdisk_f * fiducial_mdisk) mhalos.append(pot['halo'].parameters['m'] / fiducial_mdisk) mhalos = np.squeeze(mhalos) with open(path, 'wb') as f: pickle.dump((pot_grid, mhalos), f) else: with open(path, 'rb') as f: pot_grid, mhalos = pickle.load(f) self._mhalo_interp = interp1d(pot_grid, mhalos, kind='cubic', bounds_error=False, fill_value='extrapolate') def get_mw_potential(self, mdisk_f, disk_hz): mhalo = self._mhalo_interp(mdisk_f) * fiducial_mdisk mdisk = mdisk_f * fiducial_mdisk return gp.MilkyWayPotential(disk=dict(m=mdisk, b=disk_hz), halo=dict(m=mhalo)) def get_atm_w0(self, zsun, vzsun, mdisk_f, disk_hz): # get galcen frame for zsun, vzsun vsun = self._vsun.copy() vsun[2] = vzsun * u.km/u.s galcen_frame = coord.Galactocentric(z_sun=zsun*u.pc, galcen_v_sun=vsun) galcen = self.c.transform_to(galcen_frame) w0 = gd.PhaseSpacePosition(galcen.data) # get galpy potential for this mdisk_f pot = self.get_mw_potential(mdisk_f, disk_hz) galpy_pot = get_equivalent_galpy(pot) aaf = get_staeckel_aaf(galpy_pot, w=w0, gala_potential=pot) aaf = at.QTable(at.hstack((aaf, self.t))) atm = AbundanceTorusMaschine(aaf, tree_K=self.tree_K) return atm, w0, pot def get_coeffs(self, zsun, vzsun, mdisk_f, disk_hz): atm, *_ = self.get_atm_w0(zsun, vzsun, mdisk_f, disk_hz) coeff, coeff_cov = atm.get_coeffs_for_elem(self.elem_name) return coeff def __call__(self, p): zsun, vzsun, mdisk_f, disk_hz = p if not 0.4 < mdisk_f < 1.8: return np.inf if not 0 < disk_hz < 2.: return np.inf coeff = self.get_coeffs(zsun, vzsun, mdisk_f, disk_hz) val = coeff[1]**2 + coeff[2]**2 + coeff[3]**2 return val def minimize(self, x0=None, **kwargs): kwargs.setdefault('method', 'nelder-mead') if x0 is None: x0 = [20.8, 7.78, 1.0, 0.28] # Fiducial values res = minimize(self, x0=x0, **kwargs) return res
{"/thriftshop/actions.py": ["/thriftshop/galpy_helpers.py"], "/scripts/bootstrap_optimize.py": ["/totoro/config.py", "/totoro/data.py", "/totoro/objective.py"], "/totoro/tests/test_potentials.py": ["/totoro/config.py", "/totoro/potentials.py"], "/totoro/potentials.py": ["/totoro/config.py"], "/totoro/objective.py": ["/totoro/data.py", "/totoro/config.py", "/totoro/potentials.py", "/totoro/actions_staeckel.py", "/totoro/atm.py"], "/scripts/compute_actions.py": ["/totoro/config.py", "/totoro/data.py", "/totoro/potentials.py", "/totoro/actions_staeckel.py"], "/totoro/data.py": ["/totoro/config.py"], "/totoro/action_helpers.py": ["/totoro/potentials.py", "/totoro/config.py", "/totoro/actions_o2gf.py", "/totoro/actions_staeckel.py"], "/totoro/actions_staeckel.py": ["/totoro/config.py", "/totoro/galpy_helpers.py"], "/totoro/galpy_helpers.py": ["/totoro/config.py"]}
17,993,274
katiechambe/chemical-torus-imaging
refs/heads/main
/scripts/compute_actions.py
# Third-party from astropy.utils import iers iers.conf.auto_download = False import gala.dynamics as gd # This project from totoro.config import cache_path, galcen_frame from totoro.data import datasets from totoro.potentials import potentials, galpy_potentials from totoro.actions_staeckel import get_staeckel_aaf def worker(task): data_name, potential_name, aaf_filename = task # Read APOGEE sample and do parallax & plx s/n cut: d = datasets[data_name] galcen = d.c.transform_to(galcen_frame) w0 = gd.PhaseSpacePosition(galcen.data) aaf = get_staeckel_aaf(galpy_potentials[potential_name], w=w0, gala_potential=potentials[potential_name]) aaf[d._id_column] = d.t[d._id_column] aaf.write(aaf_filename, overwrite=True) def main(pool, overwrite=False): tasks = [] for data_name in datasets.keys(): for potential_name in potentials: filename = cache_path / data_name / f'aaf-{potential_name}.fits' if filename.exists() and not overwrite: continue tasks.append(( data_name, potential_name, filename )) for _ in pool.map(worker, tasks): pass if __name__ == '__main__': import sys from argparse import ArgumentParser # Define parser object parser = ArgumentParser() parser.add_argument("-o", "--overwrite", dest="overwrite", default=False, action="store_true") group = parser.add_mutually_exclusive_group() group.add_argument("--procs", dest="n_procs", default=1, type=int, help="Number of processes.") group.add_argument("--mpi", dest="mpi", default=False, action="store_true", help="Run with MPI.") parsed = parser.parse_args() # deal with multiproc: if parsed.mpi: from schwimmbad.mpi import MPIPool Pool = MPIPool kw = dict() elif parsed.n_procs > 1: from schwimmbad import MultiPool Pool = MultiPool kw = dict(processes=parsed.n_procs) else: from schwimmbad import SerialPool Pool = SerialPool kw = dict() Pool = Pool Pool_kwargs = kw with Pool(**Pool_kwargs) as pool: main(pool=pool, overwrite=parsed.overwrite) sys.exit(0)
{"/thriftshop/actions.py": ["/thriftshop/galpy_helpers.py"], "/scripts/bootstrap_optimize.py": ["/totoro/config.py", "/totoro/data.py", "/totoro/objective.py"], "/totoro/tests/test_potentials.py": ["/totoro/config.py", "/totoro/potentials.py"], "/totoro/potentials.py": ["/totoro/config.py"], "/totoro/objective.py": ["/totoro/data.py", "/totoro/config.py", "/totoro/potentials.py", "/totoro/actions_staeckel.py", "/totoro/atm.py"], "/scripts/compute_actions.py": ["/totoro/config.py", "/totoro/data.py", "/totoro/potentials.py", "/totoro/actions_staeckel.py"], "/totoro/data.py": ["/totoro/config.py"], "/totoro/action_helpers.py": ["/totoro/potentials.py", "/totoro/config.py", "/totoro/actions_o2gf.py", "/totoro/actions_staeckel.py"], "/totoro/actions_staeckel.py": ["/totoro/config.py", "/totoro/galpy_helpers.py"], "/totoro/galpy_helpers.py": ["/totoro/config.py"]}
17,993,275
katiechambe/chemical-torus-imaging
refs/heads/main
/totoro/atm.py
from collections import defaultdict import pickle import astropy.coordinates as coord import astropy.units as u import numpy as np from scipy.interpolate import interp1d from scipy.spatial import cKDTree from scipy.stats import binned_statistic __all__ = ['AbundanceTorusMaschine', 'run_bootstrap_coeffs', 'get_cos2th_zerocross'] class AbundanceTorusMaschine: def __init__(self, aaf, tree_K=64, sinusoid_K=2): """ Parameters ---------- aaf : `astropy.table.Table` Table of actions, angles, and abundances. tree_K : int (optional) The number of neighbors used to estimate the action-local mean abundances. sinusoid_K : int (optional) The number of cos/sin terms in the sinusoid fit to the abundance anomaly variations with angle. """ self.aaf = aaf # config self.tree_K = int(tree_K) self.sinusoid_K = int(sinusoid_K) # def get_theta_z_anomaly(self, elem_name, action_unit=30*u.km/u.s*u.kpc): # action_unit = u.Quantity(action_unit) # # Actions without units: # X = self.aaf['actions'].to_value(action_unit) # angz = coord.Angle(self.aaf['angles'][:, 2]).wrap_at(360*u.deg).radian # # element abundance # elem = self.aaf[elem_name] # elem_errs = self.aaf[f"{elem_name}_ERR"] # ivar = 1 / elem_errs**2 # tree = cKDTree(X) # dists, idx = tree.query(X, k=self.tree_K+1) # # compute action-local abundance anomaly # errs = np.sqrt(1 / np.sum(ivar[idx[:, 1:]], axis=1)) # means = np.sum(elem[idx[:, 1:]] * ivar[idx[:, 1:]], axis=1) * errs**2 # d_elem = elem - means # d_elem_errs = np.sqrt(elem_errs**2 + errs**2) # # d_elem_errs = np.full_like(d_elem, 0.04) # MAGIC NUMBER # return angz, d_elem, d_elem_errs def get_theta_z_anomaly(self, elem_name, action_unit=30*u.km/u.s*u.kpc): action_unit = u.Quantity(action_unit) # Actions without units: X = self.aaf['actions'].to_value(action_unit) angz = coord.Angle(self.aaf['angles'][:, 2]).wrap_at(360*u.deg).radian # element abundance elem = self.aaf[elem_name] elem_errs = self.aaf[f"{elem_name}_ERR"] tree = cKDTree(X) dists, idx = tree.query(X, k=self.tree_K+1) xhat = np.mean(X[idx[:, 1:]], axis=1) - X dx = X[idx[:, 1:]] - X[:, None] x = np.einsum('nij,nj->ni', dx, xhat) y = elem[idx[:, 1:]] w = np.sum(x**2, axis=1)[:, None] - x * np.sum(x, axis=1)[:, None] means = np.sum(y * w, axis=1) / np.sum(w, axis=1) d_elem = np.array(elem - means) d_elem_errs = np.array(elem_errs) return angz, d_elem, d_elem_errs def get_M(self, x): M = np.full((len(x), 1 + 2*self.sinusoid_K), np.nan) M[:, 0] = 1. for n in range(self.sinusoid_K): M[:, 1 + 2*n] = np.cos((n+1) * x) M[:, 2 + 2*n] = np.sin((n+1) * x) return M def get_coeffs(self, M, y, yerr): Cinv_diag = 1 / yerr**2 MT_Cinv = M.T * Cinv_diag[None] MT_Cinv_M = MT_Cinv @ M coeffs = np.linalg.solve(MT_Cinv_M, MT_Cinv @ y) coeffs_cov = np.linalg.inv(MT_Cinv_M) return coeffs, coeffs_cov def get_coeffs_for_elem(self, elem_name): tz, d_elem, d_elem_errs = self.get_theta_z_anomaly(elem_name) M = self.get_M(tz) return self.get_coeffs(M, d_elem, d_elem_errs) def get_binned_anomaly(self, elem_name, theta_z_step=5*u.deg): """ theta_z_step : `astropy.units.Quantity` [angle] (optional) The bin step size for the vertical angle bins. This is only used in methods if `statistic != 'mean'`. """ theta_z_step = coord.Angle(theta_z_step) angz_bins = np.arange(0, 2*np.pi+1e-4, theta_z_step.to_value(u.rad)) theta_z, d_elem, d_elem_errs = self.get_theta_z_anomaly(elem_name) d_elem_ivar = 1 / d_elem_errs**2 # d_elem_ivar = np.full_like(d_elem, 1 / 0.04**2) # MAGIC NUMBER stat1 = binned_statistic(theta_z, d_elem * d_elem_ivar, bins=angz_bins, statistic='sum') stat2 = binned_statistic(theta_z, d_elem_ivar, bins=angz_bins, statistic='sum') binx = 0.5 * (angz_bins[:-1] + angz_bins[1:]) means = stat1.statistic / stat2.statistic errs = np.sqrt(1 / stat2.statistic) return binx, means, errs def run_bootstrap_coeffs(aafs, elem_name, bootstrap_K=128, seed=42, overwrite=False, cache_path=None): if cache_path is not None: cache_filename = f'coeffs-bootstrap{bootstrap_K}-{elem_name}.pkl' coeffs_cache = cache_path / cache_filename if coeffs_cache.exists() and not overwrite: with open(coeffs_cache, 'rb') as f: all_bs_coeffs = pickle.load(f) return all_bs_coeffs all_bs_coeffs = {} for name in aafs: aaf = aafs[name] if seed is not None: np.random.seed(seed) bs_coeffs = [] for k in range(bootstrap_K): bootstrap_idx = np.random.choice(len(aaf), size=len(aaf)) atm = AbundanceTorusMaschine(aaf[bootstrap_idx]) coeffs, _ = atm.get_coeffs_for_elem(elem_name) bs_coeffs.append(coeffs) all_bs_coeffs[name] = np.array(bs_coeffs) if cache_path is not None: with open(coeffs_cache, 'wb') as f: pickle.dump(all_bs_coeffs, f) return all_bs_coeffs def get_cos2th_zerocross(coeffs): summary = defaultdict(lambda *args: defaultdict(list)) for i in range(5): for k in coeffs: summary[i]['mdisk'].append(float(k)) summary[i]['y'].append(np.mean(coeffs[k][:, i])) summary[i]['y_err'].append(np.std(coeffs[k][:, i])) summary[i]['mdisk'] = np.array(summary[i]['mdisk']) summary[i]['y'] = np.array(summary[i]['y']) summary[i]['y_err'] = np.array(summary[i]['y_err']) idx = summary[i]['mdisk'].argsort() for key in summary[i].keys(): summary[i][key] = summary[i][key][idx] # cos2theta term: s = summary[3] zero_cross = interp1d(s['y'], s['mdisk'], fill_value="extrapolate")(0.) zero_cross1 = interp1d(np.array(s['y']) - np.array(s['y_err']), s['mdisk'], fill_value="extrapolate")(0.) zero_cross2 = interp1d(np.array(s['y']) + np.array(s['y_err']), s['mdisk'], fill_value="extrapolate")(0.) zero_cross_err = (np.abs(zero_cross2 - zero_cross), np.abs(zero_cross1 - zero_cross)) return summary, zero_cross, zero_cross_err class ZeroCrossWorker: def __init__(self, aafs, cache_path=None, bootstrap_K=128): self.aafs = aafs self.cache_path = cache_path self.bootstrap_K = int(bootstrap_K) def __call__(self, elem_name): clean_aafs = {} for k in self.aafs: clean_aafs[k] = self.aafs[k][self.aafs[k][elem_name] > -3] bs_coeffs = run_bootstrap_coeffs(clean_aafs, elem_name, bootstrap_K=self.bootstrap_K, cache_path=self.cache_path) s, zc, zc_err = get_cos2th_zerocross(bs_coeffs) return elem_name, [zc, zc_err]
{"/thriftshop/actions.py": ["/thriftshop/galpy_helpers.py"], "/scripts/bootstrap_optimize.py": ["/totoro/config.py", "/totoro/data.py", "/totoro/objective.py"], "/totoro/tests/test_potentials.py": ["/totoro/config.py", "/totoro/potentials.py"], "/totoro/potentials.py": ["/totoro/config.py"], "/totoro/objective.py": ["/totoro/data.py", "/totoro/config.py", "/totoro/potentials.py", "/totoro/actions_staeckel.py", "/totoro/atm.py"], "/scripts/compute_actions.py": ["/totoro/config.py", "/totoro/data.py", "/totoro/potentials.py", "/totoro/actions_staeckel.py"], "/totoro/data.py": ["/totoro/config.py"], "/totoro/action_helpers.py": ["/totoro/potentials.py", "/totoro/config.py", "/totoro/actions_o2gf.py", "/totoro/actions_staeckel.py"], "/totoro/actions_staeckel.py": ["/totoro/config.py", "/totoro/galpy_helpers.py"], "/totoro/galpy_helpers.py": ["/totoro/config.py"]}
17,993,276
katiechambe/chemical-torus-imaging
refs/heads/main
/totoro/data.py
import pathlib import astropy.table as at import astropy.units as u from matplotlib.path import Path import numpy as np from pyia import GaiaData from .config import (apogee_parent_filename, galah_parent_filename, cache_path, plot_path) class Dataset: _id_column = None _radial_velocity_name = None _elem_err_fmt = None def __init_subclass__(cls, **kwargs): if not hasattr(cls, '_radial_velocity_name'): cls._radial_velocity_name = 'radial_velocity' for name in ['_id_column', '_elem_err_fmt']: if getattr(cls, name) is None: raise ValueError(f'You must specify class param: {name}') super().__init_subclass__(**kwargs) def __init__(self, filename_or_tbl): if (isinstance(filename_or_tbl, str) or isinstance(filename_or_tbl, pathlib.Path)): self.t = at.QTable.read(filename_or_tbl) else: self.t = at.QTable(filename_or_tbl) self.t = self._init_mask() # Abundance ratios should be all caps: for col in self.t.colnames: if ((col.upper().endswith('_FE') or col.upper().startswith('FE_') or col.upper().endswith('_H')) and not col.upper().startswith('FLAG')): self.t.rename_column(col, col.upper()) # Abundance error columns should be _ERR like APOGEE: for elem in self.elem_ratios: col1 = self._elem_err_fmt.format(elem_name=elem) col2 = APOGEEDataset._elem_err_fmt.format(elem_name=elem) if col1 in self.t.colnames: self.t.rename_column(col1, col2) self.g = GaiaData(self.t) # Use Gaia RV if not defined at dataset subclass level rv_name = self._radial_velocity_name rv = u.Quantity(self.t[rv_name]) if rv.unit.is_equivalent(u.one): rv = rv * u.km/u.s self.c = self.g.get_skycoord(radial_velocity=rv) def _init_mask(self): # TODO: implement on subclasses return self.t def __len__(self): return len(self.t) @property def elem_ratios(self): if not hasattr(self, '_elem_ratios'): self._elem_ratios = ['FE_H'] + sorted([x for x in self.t.colnames if x.endswith('_FE') and not x.startswith('E_') and not x.startswith('FLAG_') and not x.startswith('CHI_') and not x.startswith('FLUX_') and not x.startswith('NR_')]) return self._elem_ratios @property def elem_names(self): if not hasattr(self, '_elem_names'): elem_list = ([x.split('_')[0] for x in self.elem_ratios] + [x.split('_')[1] for x in self.elem_ratios]) elem_list.pop(elem_list.index('H')) self._elem_names = set(elem_list) return self._elem_names def get_elem_ratio(self, elem1, elem2=None): # Passed in an elem ratio provided by the table, e.g., FE_H if elem2 is None and elem1 in self.t.colnames: return self.t[elem1] if elem2 is None: try: elem1, elem2 = elem1.split('_') except Exception: raise RuntimeError("If passing a single elem ratio string, " "it must have the form ELEM_ELEM, not " f"{elem1}") elem1 = str(elem1).upper() elem2 = str(elem2).upper() if elem2 == 'H': i1 = self.elem_ratios.index(elem1 + '_FE') i2 = self.elem_ratios.index('FE_H') return (self.t[self.elem_ratios[i1]] - self.t[self.elem_ratios[i2]]) else: i1 = self.elem_ratios.index(elem1 + '_FE') i2 = self.elem_ratios.index(elem2 + '_FE') return (self.t[self.elem_ratios[i1]] - self.t[self.elem_ratios[i2]]) def get_mh_am_mask(self): # TODO: implement on subclasses return np.ones(len(self.t), dtype=bool) def filter(self, filters, low_alpha=True): mask = np.ones(len(self.t), dtype=bool) for k, (x1, x2) in filters.items(): if x1 is None and x2 is None: raise ValueError("Doh") arr = u.Quantity(self.t[k]).value if x1 is None: mask &= arr < x2 elif x2 is None: mask &= arr >= x1 else: mask &= (arr >= x1) & (arr < x2) if low_alpha is not None: alpha_mask = self.get_mh_am_mask(low_alpha) else: alpha_mask = np.ones(len(self.t), dtype=bool) return self[mask & alpha_mask] def __getitem__(self, slc): if isinstance(slc, int): slc = slice(slc, slc+1) return self.__class__(self.t[slc]) class APOGEEDataset(Dataset): _id_column = 'APOGEE_ID' _radial_velocity_name = 'VHELIO_AVG' _elem_err_fmt = '{elem_name}_ERR' # See: 2-High-alpha-Low-alpha.ipynb _mh_alpham_nodes = np.array([ [0.6, -0.05], [0.6, 0.04], [0.15, 0.04], [-0.5, 0.13], [-0.9, 0.13], [-1., 0.07], [-0.2, -0.1], [0.2, -0.1], [0.6, -0.05]] ) def _init_mask(self): aspcap_bitmask = np.sum(2 ** np.array([ 7, # STAR_WARN 23 # STAR_BAD ])) quality_mask = ( (self.t['SNR'] > 20) & ((self.t['ASPCAPFLAG'] & aspcap_bitmask) == 0) ) # Remove stars targeted in known clusters or dwarf galaxies: mask_bits = { 'APOGEE_TARGET1': np.array([9, 18, 24, 26]), 'APOGEE_TARGET2': np.array([10, 18]), 'APOGEE2_TARGET1': np.array([9, 18, 20, 21, 22, 23, 24, 26]), 'APOGEE2_TARGET2': np.array([10]), 'APOGEE2_TARGET3': np.array([5, 14, 15]) } target_mask = np.ones(len(self.t), dtype=bool) for name, bits in mask_bits.items(): target_mask &= (self.t[name] & np.sum(2**bits)) == 0 return self.t[quality_mask & target_mask] def get_mh_am_mask(self, low_alpha=True): mh_alpham_path = Path(self._mh_alpham_nodes[:-1]) low_alpha_mask = mh_alpham_path.contains_points( np.stack((self.t['M_H'], self.t['ALPHA_M'])).T) if low_alpha: return low_alpha_mask else: return ((~low_alpha_mask) & (self.t['M_H'] > -1) & (self.t['ALPHA_M'] > 0)) class GALAHDataset(Dataset): _id_column = 'star_id' _radial_velocity_name = 'rv_galah' _elem_err_fmt = 'E_{elem_name}' # See: 2-High-alpha-Low-alpha.ipynb _mh_alpham_nodes = np.array([ [0.6, -0.01], [0.6, 0.08], [0.15, 0.08], [-0.5, 0.17], [-0.9, 0.17], [-1., 0.11], [-0.2, -0.11], [0.2, -0.11], [0.6, -0.03]]) def _init_mask(self): quality_mask = ( (self.t['flag_sp'] == 0) & (self.t['flag_fe_h'] == 0) ) # Remove stars targeted in known clusters or dwarf galaxies: # TODO: how to do this for GALAH?? return self.t[quality_mask] def get_mh_am_mask(self, low_alpha=True): mh_alpham_path = Path(self._mh_alpham_nodes) low_alpha_mask = mh_alpham_path.contains_points( np.stack((np.array(self.t['FE_H']), np.array(self.t['ALPHA_FE']))).T) if low_alpha: return low_alpha_mask else: return (~low_alpha) & (self.t['FE_H'] > -1) apogee = APOGEEDataset(apogee_parent_filename) galah = GALAHDataset(galah_parent_filename) teff_ref = -382.5 * apogee.t['FE_H'] + 4607 rc_logg_max = 0.0018 * (apogee.t['TEFF'] - teff_ref) + 2.4 datasets = { 'apogee-rgb-loalpha': apogee.filter({'LOGG': (1, 3.4), 'TEFF': (3500, 6500), 'FE_H': (-3, 1)}, low_alpha=True), 'apogee-rc-loalpha': apogee.filter({'LOGG': (1.9, rc_logg_max), 'TEFF': (4200, 5400), 'FE_H': (-3, 1)}, low_alpha=True), 'apogee-rgb-hialpha': apogee.filter({'LOGG': (1, 3.4), 'TEFF': (3500, 6500), 'FE_H': (-3, 1)}, low_alpha=False), 'apogee-ms-loalpha': apogee.filter({'LOGG': (3.75, 5), 'TEFF': (5000, 6000), 'FE_H': (-3, 1)}, low_alpha=True), 'galah-rgb-loalpha': galah.filter({'logg': (1, 3.5), 'teff': (3500, 5500), 'FE_H': (-3, 1)}, low_alpha=True), 'galah-ms-loalpha': galah.filter({'logg': (3.5, 5), 'teff': (5000, 6000), 'FE_H': (-3, 1)}, low_alpha=True) } # From visual inspection of the z-vz grid plots! elem_names = { 'apogee-rgb-loalpha': ['FE_H', 'AL_FE', 'C_FE', 'MG_FE', 'MN_FE', 'NI_FE', 'N_FE', 'O_FE', 'P_FE', 'SI_FE'], 'apogee-ms-loalpha': ['FE_H', 'AL_FE', 'C_FE', 'MG_FE', 'MN_FE', 'NI_FE', 'N_FE', 'O_FE', 'P_FE', 'SI_FE', 'TI_FE'], 'galah-rgb-loalpha': ['FE_H', 'AL_FE', 'BA_FE', 'CA_FE', 'CO_FE', 'CU_FE', 'MG_FE', 'MN_FE', 'NA_FE', 'O_FE', 'SC_FE', 'Y_FE', 'ZN_FE'], 'galah-ms-loalpha': ['FE_H', 'AL_FE', 'CA_FE', 'K_FE', 'MG_FE', 'MN_FE', 'NA_FE', 'SC_FE', 'TI_FE', 'Y_FE'] } elem_names['apogee-rgb-hialpha'] = elem_names['apogee-rgb-loalpha'] elem_names['apogee-rc-loalpha'] = elem_names['apogee-rgb-loalpha'] for name in datasets: for path in [plot_path, cache_path]: this_path = path / name this_path.mkdir(exist_ok=True)
{"/thriftshop/actions.py": ["/thriftshop/galpy_helpers.py"], "/scripts/bootstrap_optimize.py": ["/totoro/config.py", "/totoro/data.py", "/totoro/objective.py"], "/totoro/tests/test_potentials.py": ["/totoro/config.py", "/totoro/potentials.py"], "/totoro/potentials.py": ["/totoro/config.py"], "/totoro/objective.py": ["/totoro/data.py", "/totoro/config.py", "/totoro/potentials.py", "/totoro/actions_staeckel.py", "/totoro/atm.py"], "/scripts/compute_actions.py": ["/totoro/config.py", "/totoro/data.py", "/totoro/potentials.py", "/totoro/actions_staeckel.py"], "/totoro/data.py": ["/totoro/config.py"], "/totoro/action_helpers.py": ["/totoro/potentials.py", "/totoro/config.py", "/totoro/actions_o2gf.py", "/totoro/actions_staeckel.py"], "/totoro/actions_staeckel.py": ["/totoro/config.py", "/totoro/galpy_helpers.py"], "/totoro/galpy_helpers.py": ["/totoro/config.py"]}
17,993,277
katiechambe/chemical-torus-imaging
refs/heads/main
/totoro/action_helpers.py
import astropy.units as u import numpy as np from scipy.optimize import minimize import gala.integrate as gi import gala.dynamics as gd from .potentials import potentials, galpy_potentials from .config import vcirc from .actions_o2gf import get_o2gf_aaf from .actions_staeckel import get_staeckel_aaf def _same_actions_objfunc_staeckel(p, pos, vy, potential_name, match_actions): vx, vz = p w0 = gd.PhaseSpacePosition(pos=pos, vel=[vx, vy, vz] * u.km/u.s) o = potentials[potential_name].integrate_orbit( w0, dt=1.*u.Myr, t1=0, t2=1 * u.Gyr, Integrator=gi.DOPRI853Integrator) aaf = get_staeckel_aaf(o[::2], galpy_potentials[potential_name]) actions = aaf['actions'].mean(axis=-1) _unit = (u.km/u.s * u.kpc)**2 val = ((actions[0] - match_actions[0])**2 + (actions[2] - match_actions[2])**2).to_value(_unit) return val def _same_actions_objfunc_sanders(p, pos, vy, potential_name, match_actions): vx, vz = p w0 = gd.PhaseSpacePosition(pos=pos, vel=[vx, vy, vz] * u.km/u.s) aaf = get_o2gf_aaf(potentials[potential_name], w0, N_max=8) actions = aaf['actions'] _unit = (u.km/u.s * u.kpc)**2 val = ((actions[0] - match_actions[0])**2 + (actions[2] - match_actions[2])**2).to_value(_unit) return val def get_w0s_with_same_actions(fiducial_w0, vy=None, staeckel=False): if staeckel: _same_actions_objfunc = _same_actions_objfunc_staeckel else: _same_actions_objfunc = _same_actions_objfunc_sanders if vy is None: # Default: set to circular velocity vy = vcirc # First, determine actions for the input orbit in the # fiducial potential model. These will be the target action values fiducial_actions = [] for n in range(fiducial_w0.shape[0]): if staeckel: o = potentials['1.0'].integrate_orbit( fiducial_w0[n], dt=0.5, t1=0, t2=2*u.Gyr) # MAGIC NUMBERS fiducial_actions.append( get_staeckel_aaf(o, galpy_potentials['1.0'])['actions']) else: fiducial_actions.append( get_o2gf_aaf(potentials['1.0'], fiducial_w0[n], N_max=8)['actions']) fiducial_actions = u.Quantity(fiducial_actions).to(u.km/u.s * u.kpc) if staeckel: fiducial_actions = np.mean(fiducial_actions, axis=-1) w0s = {} for name in potentials: if name == '1.0': w0s[name] = fiducial_w0 continue w0s[name] = [] for n in range(fiducial_w0.shape[0]): res = minimize(_same_actions_objfunc, x0=fiducial_w0.v_xyz.value[[0, 2], n], args=(fiducial_w0.pos[n], vy.to_value(u.km/u.s), name, fiducial_actions[n]), method='nelder-mead', options=dict(maxfev=64)) if res.fun > 1e-3: print(f"{name}, {n}: func val = {res.fun} -- " "Failed to converge") w0s[name].append(gd.PhaseSpacePosition( pos=fiducial_w0.pos[n], vel=[res.x[0], vy.to_value(u.km/u.s), res.x[1]] * u.km/u.s)) w0s[name] = gd.combine(w0s[name]) return w0s
{"/thriftshop/actions.py": ["/thriftshop/galpy_helpers.py"], "/scripts/bootstrap_optimize.py": ["/totoro/config.py", "/totoro/data.py", "/totoro/objective.py"], "/totoro/tests/test_potentials.py": ["/totoro/config.py", "/totoro/potentials.py"], "/totoro/potentials.py": ["/totoro/config.py"], "/totoro/objective.py": ["/totoro/data.py", "/totoro/config.py", "/totoro/potentials.py", "/totoro/actions_staeckel.py", "/totoro/atm.py"], "/scripts/compute_actions.py": ["/totoro/config.py", "/totoro/data.py", "/totoro/potentials.py", "/totoro/actions_staeckel.py"], "/totoro/data.py": ["/totoro/config.py"], "/totoro/action_helpers.py": ["/totoro/potentials.py", "/totoro/config.py", "/totoro/actions_o2gf.py", "/totoro/actions_staeckel.py"], "/totoro/actions_staeckel.py": ["/totoro/config.py", "/totoro/galpy_helpers.py"], "/totoro/galpy_helpers.py": ["/totoro/config.py"]}
17,993,278
katiechambe/chemical-torus-imaging
refs/heads/main
/totoro/actions_staeckel.py
""" Helper functions for computing actions using the axisymmetric Stäckel Fudge method introduced in Binney 20XX, implemented in Galpy. """ # Third-party import astropy.coordinates as coord import astropy.table as at import astropy.units as u import numpy as np import gala.dynamics as gd # This project from .config import rsun as ro, vcirc as vo from .galpy_helpers import gala_to_galpy_orbit def get_staeckel_aaf(galpy_potential, w, delta=None, gala_potential=None): from galpy.actionAngle import actionAngleStaeckel if delta is None: if gala_potential is None: raise ValueError("If deltas not specified, you must specify " "gala_potential.") delta = gd.get_staeckel_fudge_delta(gala_potential, w) o = gala_to_galpy_orbit(w) aAS = actionAngleStaeckel(pot=galpy_potential, delta=delta) aaf = aAS.actionsFreqsAngles(o) aaf = {'actions': np.squeeze(aaf[:3]) * ro * vo, 'freqs': np.squeeze(aaf[3:6]) * vo / ro, 'angles': coord.Angle(np.squeeze(aaf[6:]) * u.rad)} aaf = at.Table({k: v.T for k, v in aaf.items()}) return aaf
{"/thriftshop/actions.py": ["/thriftshop/galpy_helpers.py"], "/scripts/bootstrap_optimize.py": ["/totoro/config.py", "/totoro/data.py", "/totoro/objective.py"], "/totoro/tests/test_potentials.py": ["/totoro/config.py", "/totoro/potentials.py"], "/totoro/potentials.py": ["/totoro/config.py"], "/totoro/objective.py": ["/totoro/data.py", "/totoro/config.py", "/totoro/potentials.py", "/totoro/actions_staeckel.py", "/totoro/atm.py"], "/scripts/compute_actions.py": ["/totoro/config.py", "/totoro/data.py", "/totoro/potentials.py", "/totoro/actions_staeckel.py"], "/totoro/data.py": ["/totoro/config.py"], "/totoro/action_helpers.py": ["/totoro/potentials.py", "/totoro/config.py", "/totoro/actions_o2gf.py", "/totoro/actions_staeckel.py"], "/totoro/actions_staeckel.py": ["/totoro/config.py", "/totoro/galpy_helpers.py"], "/totoro/galpy_helpers.py": ["/totoro/config.py"]}
17,993,279
katiechambe/chemical-torus-imaging
refs/heads/main
/totoro/galpy_helpers.py
""" Helper functions for interfacing Gala and Galpy """ # Third-party import astropy.units as u import numpy as np # This project from .config import rsun, vcirc def gala_to_galpy_orbit(w, ro=None, vo=None): from galpy.orbit import Orbit if ro is None: ro = rsun if vo is None: vo = vcirc # PhaseSpacePosition or Orbit: cyl = w.cylindrical R = cyl.rho.to_value(ro).T phi = cyl.phi.to_value(u.rad).T z = cyl.z.to_value(ro).T vR = cyl.v_rho.to_value(vo).T vT = (cyl.rho * cyl.pm_phi).to_value(vo, u.dimensionless_angles()).T vz = cyl.v_z.to_value(vo).T o = Orbit(np.array([R, vR, vT, z, vz, phi]).T, ro=ro, vo=vo) if hasattr(w, 't'): o.t = w.t.to_value(u.Myr) return o
{"/thriftshop/actions.py": ["/thriftshop/galpy_helpers.py"], "/scripts/bootstrap_optimize.py": ["/totoro/config.py", "/totoro/data.py", "/totoro/objective.py"], "/totoro/tests/test_potentials.py": ["/totoro/config.py", "/totoro/potentials.py"], "/totoro/potentials.py": ["/totoro/config.py"], "/totoro/objective.py": ["/totoro/data.py", "/totoro/config.py", "/totoro/potentials.py", "/totoro/actions_staeckel.py", "/totoro/atm.py"], "/scripts/compute_actions.py": ["/totoro/config.py", "/totoro/data.py", "/totoro/potentials.py", "/totoro/actions_staeckel.py"], "/totoro/data.py": ["/totoro/config.py"], "/totoro/action_helpers.py": ["/totoro/potentials.py", "/totoro/config.py", "/totoro/actions_o2gf.py", "/totoro/actions_staeckel.py"], "/totoro/actions_staeckel.py": ["/totoro/config.py", "/totoro/galpy_helpers.py"], "/totoro/galpy_helpers.py": ["/totoro/config.py"]}
17,993,280
katiechambe/chemical-torus-imaging
refs/heads/main
/totoro/config.py
import pathlib import astropy.coordinates as coord import astropy.units as u import numpy as np # Eilers et al. 2019: vcirc = 229. * u.km/u.s rsun = 8.122 * u.kpc fiducial_mdisk = 6.52551e10 * u.Msun # Assumes that the package isn't actually installed, but built in place pkg_path = pathlib.Path(__file__).resolve().parent.parent cache_path = pkg_path / 'cache' plot_path = pkg_path / 'plots' data_path = pkg_path / 'data' fig_path = pkg_path / 'tex/figures' for p in [plot_path, fig_path, cache_path, data_path]: p.mkdir(exist_ok=True) # Parent data samples: apogee_parent_filename = data_path / 'apogee-parent.fits' galah_parent_filename = data_path / 'galah-parent.fits' # Plotting config stuff (limits, units, etc.) zlim = 1.5 # kpc vlim = 80. # km/s Rlim = (7, 9.5) # kpc plot_config = { "zunit": u.kpc, "vunit": u.km/u.s, "Junit": u.kpc * u.km/u.s, "zlim": zlim, "vlim": vlim, "vticks": np.arange(-vlim, vlim+1e-3, vlim//2), "zticks": np.round(np.arange(-zlim, zlim+1e-3, zlim/3), 2), "vminorticks": np.arange(-vlim, vlim+1e-3, vlim//4), "zminorticks": np.round(np.arange(-zlim, zlim+1e-3, zlim/6), 2), "Rlim": Rlim, "Rticks": np.arange(*Rlim, 1), "Rminorticks": np.arange(*Rlim, 0.5) } # Subset of elements we plot in panels elem_names = ['FE_H', 'C_FE', 'N_FE', 'O_FE', 'MG_FE', 'SI_FE', 'MN_FE', 'NI_FE'] # TODO: drop SI_FE and replace with C/N. For Galah, li_fe? # Galactocentric frame coord.galactocentric_frame_defaults.set('v4.0') galcen_frame = coord.Galactocentric()
{"/thriftshop/actions.py": ["/thriftshop/galpy_helpers.py"], "/scripts/bootstrap_optimize.py": ["/totoro/config.py", "/totoro/data.py", "/totoro/objective.py"], "/totoro/tests/test_potentials.py": ["/totoro/config.py", "/totoro/potentials.py"], "/totoro/potentials.py": ["/totoro/config.py"], "/totoro/objective.py": ["/totoro/data.py", "/totoro/config.py", "/totoro/potentials.py", "/totoro/actions_staeckel.py", "/totoro/atm.py"], "/scripts/compute_actions.py": ["/totoro/config.py", "/totoro/data.py", "/totoro/potentials.py", "/totoro/actions_staeckel.py"], "/totoro/data.py": ["/totoro/config.py"], "/totoro/action_helpers.py": ["/totoro/potentials.py", "/totoro/config.py", "/totoro/actions_o2gf.py", "/totoro/actions_staeckel.py"], "/totoro/actions_staeckel.py": ["/totoro/config.py", "/totoro/galpy_helpers.py"], "/totoro/galpy_helpers.py": ["/totoro/config.py"]}
17,993,281
katiechambe/chemical-torus-imaging
refs/heads/main
/totoro/actions_o2gf.py
""" Helper functions for computing actions using the O2GF method introduced in Sanders & Binney 2014. """ # Third-party import astropy.units as u import numpy as np import gala.integrate as gi import gala.dynamics as gd def get_o2gf_aaf(potential, w0, N_max=10, dt=1*u.Myr, n_periods=128): """Wrapper around the O2GF action solver in Gala that fails more gracefully This returns actions, angles, and frequencies for the input phase-space position estimated for the specified potential. """ aaf_units = {'actions': u.km/u.s*u.kpc, 'angles': u.degree, 'freqs': 1/u.Gyr} # First integrate a little bit of the orbit with Leapfrog to estimate # the orbital period test_orbit = potential.integrate_orbit(w0, dt=2*u.Myr, t1=0, t2=1*u.Gyr) P_guess = test_orbit.estimate_period() if np.isnan(P_guess): return {k: np.full(3, np.nan) * aaf_units[k] for k in aaf_units} # Integrate the orbit with a high-order integrator for many periods orbit = potential.integrate_orbit( w0, dt=dt, t1=0, t2=n_periods * P_guess, Integrator=gi.DOPRI853Integrator) # Use the Sanders & Binney action solver: try: aaf = gd.find_actions(orbit, N_max=N_max) except Exception: aaf = {k: np.full(3, np.nan) * aaf_units[k] for k in aaf_units} aaf = {k: aaf[k].to(aaf_units[k]) for k in aaf_units.keys()} return aaf
{"/thriftshop/actions.py": ["/thriftshop/galpy_helpers.py"], "/scripts/bootstrap_optimize.py": ["/totoro/config.py", "/totoro/data.py", "/totoro/objective.py"], "/totoro/tests/test_potentials.py": ["/totoro/config.py", "/totoro/potentials.py"], "/totoro/potentials.py": ["/totoro/config.py"], "/totoro/objective.py": ["/totoro/data.py", "/totoro/config.py", "/totoro/potentials.py", "/totoro/actions_staeckel.py", "/totoro/atm.py"], "/scripts/compute_actions.py": ["/totoro/config.py", "/totoro/data.py", "/totoro/potentials.py", "/totoro/actions_staeckel.py"], "/totoro/data.py": ["/totoro/config.py"], "/totoro/action_helpers.py": ["/totoro/potentials.py", "/totoro/config.py", "/totoro/actions_o2gf.py", "/totoro/actions_staeckel.py"], "/totoro/actions_staeckel.py": ["/totoro/config.py", "/totoro/galpy_helpers.py"], "/totoro/galpy_helpers.py": ["/totoro/config.py"]}
18,026,816
PSU-OIT-ARC/django-psu-base-template
refs/heads/master
/project_name/urls.py
from django.contrib import admin from django.conf import settings from django.views.generic import RedirectView from django.urls import path, include, re_path import {{ project_name }}.views as views app_patterns = [ re_path("^admin/", admin.site.urls), re_path("^psu/", include(("psu_base.urls", "psu_base"), namespace="psu")), re_path("^accounts/", include(("psu_base.urls", "psu_base"), namespace="cas")), # Other PSU plugins would have their views included here... # LANDING PAGE path("", views.sample_view, name="sample"), ] # On-prem apps will have additional URL context if settings.URL_CONTEXT: urlpatterns = [ path("", RedirectView.as_view(url="/" + settings.URL_CONTEXT)), url(settings.URL_CONTEXT + "/", include(app_patterns)), ] # AWS apps will NOT have additional URL context else: urlpatterns = app_patterns
{"/project_name/settings.py": ["/project_name/sass_variables.py", "/project_name/local_settings.py"], "/project_name/views/__init__.py": ["/project_name/views/sample_views.py"]}
18,027,981
belinabelortaja/python_fundamentals
refs/heads/master
/_python/OOP/1st_Assignment_User/user.py
class User: # here's what we have so far def __init__(self, name, email): self.name = name self.email = email self.account_balance = 0 # adding the deposit method def make_deposit(self, amount): # takes an argument that is the amount of the deposit self.account_balance += amount # the specific user's account increases by the amount of the value received def make_withdrawl(self,amount): self.account_balance-=amount def make_transfer(self,another_user,amount): self.account_balance -= amount another_user.account_balance += amount user1 = User("User1", "user1@gmail.com") user2 = User("User2", "user2@gmail.com") user3 = User("User3", "user3@gmail.com") user1.make_deposit(1) user1.make_deposit(4) user1.make_withdrawl(3) print(user1.account_balance) user2.make_deposit(10) user2.make_deposit(5) user2.make_withdrawl(4) user2.make_withdrawl(4) print(user2.account_balance) user3.make_deposit(100) user3.make_withdrawl(50) user3.make_withdrawl(30) user3.make_withdrawl(10) print(user3.account_balance) user3.make_transfer(user1,3) print(user1.account_balance,user3.account_balance)
{"/django/django_orm/users_with_templates/users_with_temp/users_app/views.py": ["/django/django_orm/users_with_templates/users_with_temp/users_app/models.py"]}
18,027,982
belinabelortaja/python_fundamentals
refs/heads/master
/django/django_orm/Books_Authors_with_Template/books_authors_proj/books_author_app/urls.py
from django.urls import path from . import views urlpatterns = [ path('', views.index), path('authors',views.authors), path('book/<id>',views.book), path('author/<id>',views.author2), ]
{"/django/django_orm/users_with_templates/users_with_temp/users_app/views.py": ["/django/django_orm/users_with_templates/users_with_temp/users_app/models.py"]}
18,027,983
belinabelortaja/python_fundamentals
refs/heads/master
/_python/python_fundamentals/9th Assignment Functions Intermediate I/functions_intermediate_I.py
import random def randInt(min=0, max=100): print(int(random.random()*100)) print(int(random.random()*50)) print(int(random.random()*50+50)) print(int(random.random()*450+50)) randInt(min=0, max=100)
{"/django/django_orm/users_with_templates/users_with_temp/users_app/views.py": ["/django/django_orm/users_with_templates/users_with_temp/users_app/models.py"]}
18,027,984
belinabelortaja/python_fundamentals
refs/heads/master
/django/django_fullstack/The_Wall/login_registration/login_registration_app/urls.py
from django.urls import path from . import views urlpatterns = [ path('', views.index), path('register', views.registration), path('wall', views.wall), path('login', views.login), path('logout', views.logout), path('post-message', views.post_message), path('post-comment/<int:id>', views.post_comment), path('delete/<int:id>', views.destroy), ]
{"/django/django_orm/users_with_templates/users_with_temp/users_app/views.py": ["/django/django_orm/users_with_templates/users_with_temp/users_app/models.py"]}
18,027,985
belinabelortaja/python_fundamentals
refs/heads/master
/django/django_fullstack/courses/courses_proj/courses_app/urls.py
from django.urls import path from . import views urlpatterns = [ path('courses', views.index), path('courses/new', views.new), path('courses/create', views.create), path('courses/<int:id>', views.show), path('courses/<int:id>/destroy', views.destroy), path('courses/<int:id>/delete', views.delete), path('courses/<int:id>/comment', views.add_comment), path('courses/<int:id>/view-comment', views.view_comment), ]
{"/django/django_orm/users_with_templates/users_with_temp/users_app/views.py": ["/django/django_orm/users_with_templates/users_with_temp/users_app/models.py"]}
18,027,986
belinabelortaja/python_fundamentals
refs/heads/master
/django/django_fullstack/Test_Travel_Plans/login_registration/test_app/urls.py
from django.urls import path from . import views urlpatterns = [ path('travels', views.travel_index), path('travels/create', views.create_travel), path('travels/new', views.new_travel), path('travels/<int:travel_id>/join_travel', views.join_travel), path('travels/destination/<int:travel_id>', views.show_travel) ]
{"/django/django_orm/users_with_templates/users_with_temp/users_app/views.py": ["/django/django_orm/users_with_templates/users_with_temp/users_app/models.py"]}
18,027,987
belinabelortaja/python_fundamentals
refs/heads/master
/django/django_orm/Books_Authors_with_Template/books_authors_proj/books_author_app/views.py
from django.shortcuts import render, redirect, HttpResponse from books_author_app.models import * def index(request): if request.method == "POST": book = Book.objects.create(title=request.POST['title'], description=request.POST['description']) return redirect("/") context={ "books":Book.objects.all(), } return render(request, "index.html", context) def authors(request): if request.method == "POST": authors = Author.objects.create(firstname=request.POST['firstname'], lastname=request.POST['lastname'], notes=request.POST['notes']) return redirect("/authors") context={ "authors":Author.objects.all(), } return render(request, "authors.html", context) def book(request, id): book = Book.objects.get(id=id) if request.method == 'POST': author = Author.objects.get(id=request.POST['author_id']) book.authors.add(author) return redirect('/book/' + str(book.id)) context={ "book": book, "authors": Author.objects.all(), } print(Author.objects.all()) return render(request, "book.html", context) def author2(request, id): author2 = Author.objects.get(id=id) if request.method == 'POST': book2 = Book.objects.get(id=request.POST['book_id']) author2.books.add(book2) return redirect('/author/' + str(author2.id)) context={ "author2": author2, "books": Book.objects.all(), } print(Book.objects.all()) return render(request, "author_2.html", context)
{"/django/django_orm/users_with_templates/users_with_temp/users_app/views.py": ["/django/django_orm/users_with_templates/users_with_temp/users_app/models.py"]}
18,027,988
belinabelortaja/python_fundamentals
refs/heads/master
/django/django_fullstack/Favorite_books/login_registration/favorite_book_app/migrations/0002_book_favorite_book.py
# Generated by Django 2.2 on 2021-05-05 18:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('login_registration_app', '__first__'), ('favorite_book_app', '0001_initial'), ] operations = [ migrations.AddField( model_name='book', name='favorite_book', field=models.ManyToManyField(related_name='fav_books', to='login_registration_app.User'), ), ]
{"/django/django_orm/users_with_templates/users_with_temp/users_app/views.py": ["/django/django_orm/users_with_templates/users_with_temp/users_app/models.py"]}
18,027,989
belinabelortaja/python_fundamentals
refs/heads/master
/django/django_orm/users_with_templates/users_with_temp/users_app/migrations/0002_auto_20210415_1306.py
# Generated by Django 2.2 on 2021-04-15 11:06 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users_app', '0001_initial'), ] operations = [ migrations.RenameField( model_name='users', old_name='name', new_name='firstname', ), migrations.AddField( model_name='users', name='lasttname', field=models.CharField(default=2, max_length=45), preserve_default=False, ), ]
{"/django/django_orm/users_with_templates/users_with_temp/users_app/views.py": ["/django/django_orm/users_with_templates/users_with_temp/users_app/models.py"]}
18,027,990
belinabelortaja/python_fundamentals
refs/heads/master
/_python/Flask/first_assignment.py
@app.route('/') def HelloWorld(): return "Hello World" @app.route('/dashboard') def dashboard(): return "This is a dashboard" @app.route('/dashboard/<name>/<int:year>/<int:id>') def dashboardItem (name, year, id) return name + "" + str(year) + " " str(id)
{"/django/django_orm/users_with_templates/users_with_temp/users_app/views.py": ["/django/django_orm/users_with_templates/users_with_temp/users_app/models.py"]}
18,027,991
belinabelortaja/python_fundamentals
refs/heads/master
/_python/python_fundamentals/11th_Assignment_Selection_sort_optional/selection_sort.py
def selectionSort( myList ): for i in range( len(myList) - 1 ): minValueIndex = i for j in range( i + 1, len(myList) ): if myList[j] < myList[minValueIndex] : minValueIndex = j if minValueIndex != i : temp = myList[i] myList[i] = myList[minValueIndex] myList[minValueIndex] = temp return myList newList = [21,6,9,33,3] print(selectionSort(newList))
{"/django/django_orm/users_with_templates/users_with_temp/users_app/views.py": ["/django/django_orm/users_with_templates/users_with_temp/users_app/models.py"]}
18,027,992
belinabelortaja/python_fundamentals
refs/heads/master
/django/django_fullstack/Favorite_books/login_registration/favorite_book_app/models.py
from django.db import models import re import bcrypt from dateutil.relativedelta import relativedelta from datetime import datetime import dateutil.parser from login_registration_app.models import * class BookManager(models.Manager): def basic_validator(self, postData): errors = {} if len(postData['title']) < 0: errors["title"] = "Book must have a title" if len(postData['description']) <= 5: errors["description"] = "Book description should be at least 10 characters" return errors class Book(models.Model): title= models.CharField(max_length=255) description= models.CharField(max_length=255) user = models.ForeignKey(User, related_name="books", on_delete =models.CASCADE) favorite_book = models.ManyToManyField(User, related_name="fav_books") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects= BookManager()
{"/django/django_orm/users_with_templates/users_with_temp/users_app/views.py": ["/django/django_orm/users_with_templates/users_with_temp/users_app/models.py"]}
18,027,993
belinabelortaja/python_fundamentals
refs/heads/master
/django/django_fullstack/Amadon/poorly_coded_store/urls.py
from django.urls import path from . import views urlpatterns = [ path('', views.index), path('checkout/<int:id>', views.checkout), path('reload', views.reload) ]
{"/django/django_orm/users_with_templates/users_with_temp/users_app/views.py": ["/django/django_orm/users_with_templates/users_with_temp/users_app/models.py"]}
18,027,994
belinabelortaja/python_fundamentals
refs/heads/master
/flask/1st_Assignment_Understanding_flask/understanding_route.py
from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello World!' @app.route('/dojo') def dojo(): return 'Dojo' @app.route('/say/<name>') def say(name): return 'Hi '+ name.capitalize() +'!' @app.route('/repeat/<numb>/<name>') def num(numb,name): n=int(numb) newName=name*n return newName if __name__=="__main__": app.run(debug=True)
{"/django/django_orm/users_with_templates/users_with_temp/users_app/views.py": ["/django/django_orm/users_with_templates/users_with_temp/users_app/models.py"]}
18,027,995
belinabelortaja/python_fundamentals
refs/heads/master
/_python/python_fundamentals/6th Assignment Functions Basic 1/test.py
#14 def a(): print(1) b() print(2) def b(): print(3) a()
{"/django/django_orm/users_with_templates/users_with_temp/users_app/views.py": ["/django/django_orm/users_with_templates/users_with_temp/users_app/models.py"]}