index
int64 | repo_name
string | branch_name
string | path
string | content
string | import_graph
string |
|---|---|---|---|---|---|
14,867,799
|
sub7ata/Django_HMS
|
refs/heads/master
|
/hotel/views.py
|
from django.shortcuts import render, HttpResponse
from django.views.generic import ListView, FormView, View, DeleteView
from django.urls import reverse, reverse_lazy
from .models import Room, Booking
from .forms import AvailabilityForm
from hotel.booking_functions.availability import check_availability
import os
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
import environ
import stripe
stripe.api_key = 'sk_test_51Hu0AzH60lA1oSoomphzz4KWIOkf3fyNb6xKnMTLtZuqrYsafvJvMOQXhqxqOV0vy7EkWSuJxV3GxH5q899R8M8l00MDvjRsHl'
from django.http import JsonResponse
env = environ.Env(
# set casting, default value
DEBUG=(bool, False)
)
environ.Env.read_env()
# Create your views here.
def RoomListView(request):
room = Room.objects.all()[0]
room_categories = dict(room.ROOM_CATEGORIES)
room_values = room_categories.values()
room_list = []
for room_category in room_categories:
room = room_categories.get(room_category)
room_url = reverse('hotel:RoomDetailView', kwargs={
'category': room_category})
room_list.append((room, room_url))
context = {
"room_list": room_list,
}
return render(request, 'room_list_view.html', context)
class BookingListView(ListView):
model = Booking
template_name = "booking_list_view.html"
def get_queryset(self, *args, **kwargs):
if self.request.user.is_staff:
booking_list = Booking.objects.all()
return booking_list
else:
booking_list = Booking.objects.filter(user=self.request.user)
return booking_list
# def get_context_data(self, **kwargs):
# room = Room.objects.all()[0]
# room_categories = dict(room.ROOM_CATEGORIES)
# context = super().get_context_data(**kwargs)
# context
class RoomDetailView(View):
def get(self, request, *args, **kwargs):
print(self.request.user)
category = self.kwargs.get('category', None)
form = AvailabilityForm()
room_list = Room.objects.filter(category=category)
if len(room_list) > 0:
room = room_list[0]
room_category = dict(room.ROOM_CATEGORIES).get(room.category, None)
context = {
'room_category': room_category,
'form': form,
}
return render(request, 'room_detail_view.html', context)
else:
return HttpResponse('Category does not exist')
def post(self, request, *args, **kwargs):
category = self.kwargs.get('category', None)
room_list = Room.objects.filter(category=category)
form = AvailabilityForm(request.POST)
if form.is_valid():
data = form.cleaned_data
available_rooms = []
for room in room_list:
if check_availability(room, data['check_in'], data['check_out']):
available_rooms.append(room)
if len(available_rooms) > 0:
room = available_rooms[0]
booking = Booking.objects.create(
user=self.request.user,
room=room,
check_in=data['check_in'],
check_out=data['check_out']
)
booking.save()
message = Mail(
from_email='dhabaledarshan@gmail.com',
to_emails='dhabalekalpana@gmail.com',
subject='Sending from hotelina',
html_content='<strong>Sending from hotelina</strong>')
try:
sg = SendGridAPIClient(env.str('SG_KEY'))
response = sg.send(message)
print(response.status_code)
print(response.body)
print(response.headers)
print('SENT!!!')
except Exception as e:
print(e)
return HttpResponse(booking)
else:
return HttpResponse('All of this category of rooms are booked!! Try another one')
class CancelBookingView(DeleteView):
model = Booking
template_name = 'booking_cancel_view.html'
success_url = reverse_lazy('hotel:BookingListView')
def checkout_view(request, amount, product_name, product_image):
try:
stripe.api_key = 'sk_test_51Hu0AzH60lA1oSoomphzz4KWIOkf3fyNb6xKnMTLtZuqrYsafvJvMOQXhqxqOV0vy7EkWSuJxV3GxH5q899R8M8l00MDvjRsHl'
checkout_session = stripe.checkout.Session.create(
success_url="http://127.0.0.1:8000/success",
cancel_url="http://127.0.0.1:8000/cancel",
payment_method_types=["card"],
line_items=[
{
'price_data': {
'currency': 'inr',
'unit_amount': amount,
'product_data': {
'name': str(product_name),
'images': [str(product_image)],
},
},
},
],
mode="payment",
)
return render(request, 'checkout.html', {'checkout_id': checkout_session.id})
except Exception as e:
return render(request, 'failure.html', {'error': e})
def success_view(request):
return render(request, 'success.html')
def cancel_view(request):
return render(request, 'cancel.html')
|
{"/hotel/urls.py": ["/hotel/views.py"], "/hotel/views.py": ["/hotel/forms.py"]}
|
14,933,693
|
albertopuentes/python-exercises
|
refs/heads/main
|
/python_data_structure_manipulation_exercises.py
|
students = [
{
"id": "100001",
"student": "Ada Lovelace",
"coffee_preference": "light",
"course": "web development",
"grades": [70, 91, 82, 71],
"pets": [{"species": "horse", "age": 8}],
},
{
"id": "100002",
"student": "Thomas Bayes",
"coffee_preference": "medium",
"course": "data science",
"grades": [75, 73, 86, 100],
"pets": [],
},
{
"id": "100003",
"student": "Marie Curie",
"coffee_preference": "light",
"course": "web development",
"grades": [70, 89, 69, 65],
"pets": [{"species": "cat", "age": 0}],
},
{
"id": "100004",
"student": "Grace Hopper",
"coffee_preference": "dark",
"course": "data science",
"grades": [73, 66, 83, 92],
"pets": [{"species": "dog", "age": 4}, {"species": "cat", "age": 4}],
},
{
"id": "100005",
"student": "Alan Turing",
"coffee_preference": "dark",
"course": "web development",
"grades": [78, 98, 85, 65],
"pets": [
{"species": "horse", "age": 6},
{"species": "horse", "age": 7},
{"species": "dog", "age": 5},
],
},
{
"id": "100006",
"student": "Rosalind Franklin",
"coffee_preference": "dark",
"course": "data science",
"grades": [76, 70, 96, 81],
"pets": [],
},
{
"id": "100007",
"student": "Elizabeth Blackwell",
"coffee_preference": "dark",
"course": "web development",
"grades": [69, 94, 89, 86],
"pets": [{"species": "cat", "age": 10}],
},
{
"id": "100008",
"student": "Rene Descartes",
"coffee_preference": "medium",
"course": "data science",
"grades": [87, 79, 90, 99],
"pets": [{"species": "cat", "age": 10}, {"species": "cat", "age": 8}],
},
{
"id": "100009",
"student": "Ahmed Zewail",
"coffee_preference": "medium",
"course": "data science",
"grades": [74, 99, 93, 89],
"pets": [{"species": "cat", "age": 0}, {"species": "cat", "age": 0}],
},
{
"id": "100010",
"student": "Chien-Shiung Wu",
"coffee_preference": "medium",
"course": "web development",
"grades": [82, 92, 91, 65],
"pets": [{"species": "cat", "age": 8}],
},
{
"id": "100011",
"student": "William Sanford Nye",
"coffee_preference": "dark",
"course": "data science",
"grades": [70, 92, 65, 99],
"pets": [{"species": "cat", "age": 8}, {"species": "cat", "age": 5}],
},
{
"id": "100012",
"student": "Carl Sagan",
"coffee_preference": "medium",
"course": "data science",
"grades": [100, 86, 91, 87],
"pets": [{"species": "cat", "age": 10}],
},
{
"id": "100013",
"student": "Jane Goodall",
"coffee_preference": "light",
"course": "web development",
"grades": [80, 70, 68, 98],
"pets": [{"species": "horse", "age": 4}],
},
{
"id": "100014",
"student": "Richard Feynman",
"coffee_preference": "medium",
"course": "web development",
"grades": [73, 99, 86, 98],
"pets": [{"species": "dog", "age": 6}],
},
]
# 1) 14 students
print(len(students))
# 2)3 students prefer light roast
# 6 students prefer medium roast
# 5 students prefer dark roast
count_light = 0
count_medium = 0
count_dark = 0
for n in students:
if n["coffee_preference"] == 'light':
count_light += 1
if n["coffee_preference"] == 'medium':
count_medium += 1
if n["coffee_preference"] == 'dark':
count_dark += 1
print(f'{count_light} students prefer light roast')
print(f'{count_medium} students prefer medium roast')
print(f'{count_dark} students prefer dark roast')
#3) 3 dogs, 4 horses & 11 cats
Dog = 0
Horse = 0
Cat = 0
for n in students:
for n in n["pets"]:
if n["species"] == 'dog':
Dog += 1
if n["species"] == 'horse':
Horse += 1
if n["species"] == 'cat':
Cat += 1
print(f'{Dog} dogs')
print(f'{Horse} horses')
print(f'{Cat} cats')
#4) All students received 4 grades [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
num_of_grades = [len(x['grades']) for x in students]
print(num_of_grades)
#5) [78.5, 83.5, 73.25, 78.5, 81.5, 80.75, 84.5, 88.75, 88.75, 82.5, 81.5, 91.0, 79.0, 89.0]
# average grade for each student
grade_sum = [sum(x['grades']) for x in students]
grade_len = [len(x['grades']) for x in students]
grade_avg = [x / y for x, y in zip(grade_sum, grade_len)]
print(grade_avg)
#6) [1, 0, 1, 2, 3, 0, 1, 2, 2, 1, 2, 1, 1, 1] is list of number of pets each student has
student_pets = [len(x['pets']) for x in students]
print(student_pets)
#7) 7 students in the data science course & 7 students in the web development course
ds_count = 0
wd_count = 0
for n in students:
if n["course"] == 'data science':
ds_count += 1
if n["course"] == 'web development':
wd_count += 1
print(f'{ds_count} of students in data science')
print(f'{wd_count} of students in web development')
#8) 1.2857142857142858 is average number of pets for students in web development
web_pets = []
for n in students:
if n["course"] == 'web development':
web_pets.append(len(n['pets']))
x = sum(web_pets)/len(web_pets)
print(x)
#9) 5.444444444444445 is avg pet age for data science students
pet_ages = []
for n in students:
if n["course"] == "data science":
for n in n["pets"]:
pet_ages.append(n["age"])
print(sum(pet_ages)/len(pet_ages))
# 10) the most frequent coffee preference for data science students is medium @ 4
count_light = 0
count_medium = 0
count_dark = 0
for n in students:
if n["course"] == 'data science':
if n["coffee_preference"] == 'light':
count_light += 1
if n["coffee_preference"] == 'medium':
count_medium += 1
if n["coffee_preference"] == 'dark':
count_dark += 1
print(f'{count_light} data science students prefer light roast')
print(f'{count_medium} data science students prefer medium roast')
print(f'{count_dark} data science students prefer dark roast')
# 11) the least frequent coffee preference for web dev students are medium & dark @ 2
count_light = 0
count_medium = 0
count_dark = 0
for n in students:
if n["course"] == 'web development':
if n["coffee_preference"] == 'light':
count_light += 1
if n["coffee_preference"] == 'medium':
count_medium += 1
if n["coffee_preference"] == 'dark':
count_dark += 1
print(f'{count_light} web development students prefer light roast')
print(f'{count_medium} web development students prefer medium roast')
print(f'{count_dark} web development students prefer dark roast')
#12 the avg grade for students w/at least 2 pets is 83.8
grades_2pets = []
for n in students:
if len(n["pets"]) >= 2:
grades_2pets.append((sum(n["grades"]))/(len(n["grades"])))
print(grades_2pets)
print(len(grades_2pets))
print(sum(grades_2pets)/len(grades_2pets))
#13 1 student has 3 pets
count = 0
for n in students:
if len(n["pets"]) == 3:
count += 1
print(count)
#14 The avg grade for students w/0 pets is 82.125
grades_2pets = []
for n in students:
if len(n["pets"]) == 0:
grades_2pets.append((sum(n["grades"]))/(len(n["grades"])))
print(grades_2pets)
print(len(grades_2pets))
print(sum(grades_2pets)/len(grades_2pets))
#15 81.17857142857143 is avg grade for Web Dev students
# 84.67857142857143 is avg grade for Data Science students
grades_wd = []
grades_ds = []
for n in students:
if n["course"] == "data science":
grades_ds.append((sum(n["grades"]))/(len(n["grades"])))
if n["course"] == "web development":
grades_wd.append((sum(n["grades"]))/(len(n["grades"])))
print(f'{sum(grades_wd)/len(grades_wd)} is avg grade for Web Dev students')
print(f'{sum(grades_ds)/len(grades_ds)} is avg grade for Data Science students')
# 16 28.8 is avg grade range for dark coffee drinkers
grade_range = []
for n in students:
if n["coffee_preference"] == "dark":
grade_range.append((max(n["grades"]))-(min(n["grades"])))
print(grade_range)
print(f'{sum(grade_range)/len(grade_range)} is avg grade range for dark coffee drinkers')
# 17 1.1666666666666667 is avg pets for medium coffee drinkers
num_pets = []
for n in students:
if n["coffee_preference"] == "medium":
num_pets.append(len(n["pets"]))
print(num_pets)
print(f'{sum(num_pets)/len(num_pets)} is avg pets for medium coffee drinkers')
# 18 horse is most common pet for web developers @ 4
type_pets = []
for n in students:
if n["course"] == "web development":
for n in n["pets"]:
type_pets.append(n["species"])
print(type_pets)
print(f'{max(type_pets)} is most common pet for web developers')
# 19 13.642857142857142 is avg name length
name_len = [len(n["student"]) for n in students]
print(f'{sum(name_len)/len(name_len)} is avg name length')
# 20 8 is highest pet age for light coffee drinkers
pet_age = []
for n in students:
if n["coffee_preference"] == 'light':
for n in n["pets"]:
pet_age.append(n["age"])
print(f'{max(pet_age)} is highest pet age for light coffee drinkers')
|
{"/import_exercises.py": ["/function_exercises.py"]}
|
14,933,694
|
albertopuentes/python-exercises
|
refs/heads/main
|
/function_exercises.py
|
# 1
def is_two(x):
if x == 2 or x == '2':
return True
else:
return False
print(is_two(4))
# 2
def is_vowel(x):
if x in 'aeiouAEIOU':
return True
else:
return False
print(is_vowel(b))
# 3
def is_vowel(x):
if x not in 'aeiouAEIOU':
return True
else:
return False
# 4
def cap_word(x):
if x[0] not in 'aeiouAEIOU':
x = x.capitalize()
return(x)
cap_word('today')
# 5
def calculate_tip(tip, bill):
return tip*bill
# 6
def apply_discount(price, discount):
return price-(price*discount)
# 7
def handle_commas(n):
n = n.replace(',', '')
return int(n)
# 8
def get_letter_grade(x):
if x > 89:
return 'A'
elif x > 79:
return 'B'
elif x > 74:
return 'C'
elif x > 69:
return 'D'
else:
return 'F'
get_letter_grade(55)
# 9
def remove_vowels(n):
vowel = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]
for x in n:
if x in vowel:
n = n.replace(x, "")
return n
# 10
def normalize_name(x):
x = x.lower()
x = x.strip()
x = x.replace(" ", "_")
for y in x:
if y.isalnum() == False and y != "_":
x = x.replace(y, "")
while x[0].isdigit() and x[0] != "_":
x = x[1:]
return x
# 11
def cumulative_sum(x):
x = [sum(x[:i]) for i in range(1, len(x)+1)]
return x
|
{"/import_exercises.py": ["/function_exercises.py"]}
|
14,933,695
|
albertopuentes/python-exercises
|
refs/heads/main
|
/import_exercises.py
|
import function_exercises
print(function_exercises.is_vowel('a'))
print(function_exercises.apply_discount(100, .25))
print(function_exercises.remove_vowels('testme'))
from function_exercises import calculate_tip
print(calculate_tip(.15, 100))
from itertools import product
# 2.a.
print(len(list(product('abc', '123'))))
# 2.b.
from itertools import combinations
print(len(list(combinations('abcd', 2))))
#2.c.
from itertools import permutations
print(len(list(permutations('abcd', 2))))
# 3
import json
json.load(open('profiles.json'))
profiles.listdir()
|
{"/import_exercises.py": ["/function_exercises.py"]}
|
14,933,696
|
albertopuentes/python-exercises
|
refs/heads/main
|
/control_structures_exercises.py
|
# 1.a.
day_input = input('What day is it?')
if day_input.lower() == 'monday':
print('Monday')
else:
print('Not Monday')
# 1.b.
weekday = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday']
day_input = input('What day is it?')
if day_input.lower() in weekday:
print('Weekday')
else:
print('Weekend')
# 1.c.
hours_worked = 45
hourly_rate = 10
if hours_worked <= 40:
weekly_pay = hours_worked * hourly_rate
else:
weekly_pay = (40 * hourly_rate) + ((hours_worked - 40) * (1.5 * hourly_rate))
print(weekly_pay)
# 2.a.
i = 5
while i <= 15:
print(i)
i += 1
i = 0
while i <= 100:
print(i)
i += 2
i = 100
while i <= -10:
print(i)
i += -5
while i <= -10:
print(i)
i += -5
i = 2
while i <= 1000000:
print(i)
i **= 2
i = 100
while i >= 5:
print(i)
i += -5
# 2.b
num_input = input('Give me a positive number')
for n in range(1, 11):
print(f'{int(num_input)} X {n} = {int(num_input) * n}')
for n in range (1,10):
print(str(n) * n)
# 2.c
for n in range(1,51,2):
num_input = input('Please enter an odd number between 1 and 50')
if n % 2 == 1:
continue
print(f'Here is an odd number: {n}')
num_input = input('Please enter an odd number between 1 and 50')
for num in range(1, 51, 2):
if num == int(num_input):
print(f'Yikes! Skipping number: {num}')
else:
print(f'Here is an odd number: {num}')
num_input = input('Please enter a positive number')
while num_input.isdigit() and int(num_input) > 0:
for n in range (0, (int(num_input)+1)):
if n <= int(num_input):
print(n)
else: break
# 2.d.
num_input = input('Please enter a positive number')
while num_input.isdigit() and int(num_input) > 0:
n = int(num_input)
for n in range(int(num_input), 1)
while n >= 1
n += -1
#2.e.
num_input = input('Please enter a positive number')
if num_input.isdigit() and int(num_input) > 0:
n = int(num_input)
while n >= 1:
print(n)
n += -1
# 3. FizzBuzz
for n in range (1, 101, 1):
if n % 3 == 0:
print("Fizz")
if n % 5 == 0:
print("Buzz")
if n % 5 == 0 and n % 3 == 0:
print("FizzBuzz")
else:
print(n)
# 5
while True:
grade_inp = input("Please enter a grade from 0 to 100")
if int(grade_inp) > 87:
print('A')
elif int(grade_inp) > 79 and int(grade_inp) < 88:
print('B')
elif int(grade_inp) > 66 and int(grade_inp) < 80:
print('C')
elif int(grade_inp) > 59 and int(grade_inp) < 60:
print('D')
else:
print('F')
cont_input = input("Would you like to continue? Enter Y or N")
if cont_input.lower() != "y":
break
# 6
books_read = [
dict(title = "Guns, Germs, and Steel", author = "Jared Diamond", genre = "Historical"),
dict(title = "Thinking Strategically", author = "Avinish Dixit", genre = "Educational"),
dict(title = "A History of God", author = "Alfred Knopf", genre = "Historical")
]
prompt = input('Please select either Historical or Educational genre')
for x in books_read:
if x['genre'] == prompt:
print(x['title'])
|
{"/import_exercises.py": ["/function_exercises.py"]}
|
14,933,697
|
albertopuentes/python-exercises
|
refs/heads/main
|
/list_comprehensions.py
|
# 17 list comprehension problems in python
fruits = ['mango', 'kiwi', 'strawberry', 'guava', 'pineapple', 'mandarin orange']
numbers = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 17, 19, 23, 256, -8, -4, -2, 5, -9]
# Example for loop solution to add 1 to each number in the list
numbers_plus_one = []
for number in numbers:
numbers_plus_one.append(number + 1)
# Example of using a list comprehension to create a list of the numbers plus one.
numbers_plus_one = [number + 1 for number in numbers]
print(numbers_plus_one)
# Example code that creates a list of all of the list of strings in fruits and uppercases every string
output = []
for fruit in fruits:
output.append(fruit.upper())
# Exercise 1 - rewrite the above example code using list comprehension syntax. Make a variable named uppercased_fruits to hold the output of the list comprehension. Output should be ['MANGO', 'KIWI', etc...]
uppercased_fruits = [fruit.upper() for fruit in fruits]
print(uppercased_fruits)
# Exercise 2 - create a variable named capitalized_fruits and use list comprehension syntax to produce output like ['Mango', 'Kiwi', 'Strawberry', etc...]
capitalized_fruits = [fruit.title() for fruit in fruits]
print(capitalized_fruits)
# Exercise 3 - Use a list comprehension to make a variable named fruits_with_more_than_two_vowels. Hint: You'll need a way to check if something is a vowel.
vowel = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
count = 0
fruits_with_more_than_two_vowels = []
for fruit in fruits:
for x in fruit:
if x in vowel:
count += 1
if count > 2:
fruits_with_more_than_two_vowels.append(fruit)
print(fruits_with_more_than_two_vowels)
# Exercise 4 - make a variable named fruits_with_only_two_vowels. The result should be ['mango', 'kiwi', 'strawberry']
vowel = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
count = 0
fruits_with_only_two_vowels = []
for fruit in fruits:
for x in fruit:
if x in vowel:
count += 1
if count == 2:
fruits_with_only_two_vowels.append(fruit)
print(fruits_with_only_two_vowels)
# Exercise 5 - make a list that contains each fruit with more than 5 characters
more_than_5_char = [fruit for fruit in fruits if len(fruit) > 5]
print(more_than_5_char)
# Exercise 6 - make a list that contains each fruit with exactly 5 characters
equal_5_char = [fruit for fruit in fruits if len(fruit) == 5]
print(equal_5_char)
# Exercise 7 - Make a list that contains fruits that have less than 5 characters
lessthan_5_char = [fruit for fruit in fruits if len(fruit) < 5]
print(lessthan_5_char)
# Exercise 8 - Make a list containing the number of characters in each fruit. Output would be [5, 4, 10, etc... ]
number_char = [len(fruit) for fruit in fruits]
print(number_char)
# Exercise 9 - Make a variable named fruits_with_letter_a that contains a list of only the fruits that contain the letter "a"
fruits_with_letter_a = [fruit for fruit in fruits if "a" in fruit]
print(fruits_with_letter_a)
# Exercise 10 - Make a variable named even_numbers that holds only the even numbers
even_numbers = [number for number in numbers if number % 2 == 0]
print(even_numbers)
# Exercise 11 - Make a variable named odd_numbers that holds only the odd numbers
odd_numbers = [number for number in numbers if number % 2 != 0]
print(odd_numbers)
# Exercise 12 - Make a variable named positive_numbers that holds only the positive numbers
positive_numbers = [number for number in numbers if number > 0]
print(positive_numbers)
# Exercise 13 - Make a variable named negative_numbers that holds only the negative numbers
negative_numbers = [number for number in numbers if number < 0]
print(negative_numbers)
# Exercise 14 - use a list comprehension w/ a conditional in order to produce a list of numbers with 2 or more numerals
<<<<<<< HEAD
two_or_more = [x for x in numbers if len(str(x)) >= 2 and x > 0]
=======
two_or_more = [str(x) for x in numbers if len(str(x)) >= 2 and x > 0]
>>>>>>> ea5fd57a4ecbebeb60b399d372cacf63435691ab
print(two_or_more)
# Exercise 15 - Make a variable named numbers_squared that contains the numbers list with each element squared. Output is [4, 9, 16, etc...]
numbers = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 17, 19, 23, 256, -8, -4, -2, 5, -9]
numbers_squared = [(num*num) for num in numbers]
print(numbers_squared)
# Exercise 16 - Make a variable named odd_negative_numbers that contains only the numbers that are both odd and negative.
odd_negative_numbers = [num for num in numbers if num < 0 and num % 2 != 0]
print(odd_negative_numbers)
# Exercise 17 - Make a variable named numbers_plus_5. In it, return a list containing each number plus five.
numbers_plus_5 = [num + 5 for num in numbers]
print(numbers_plus_5)
# BONUS Make a variable named "primes" that is a list containing the prime numbers in the numbers list. *Hint* you may want to make or find a helper function that determines if a given number is prime or not.
import sympy
numbers = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 17, 19, 23, 256, -8, -4, -2, 5, -9]
is_prime = [number for number in numbers if sympy.isprime(number)]
print(is_prime)
|
{"/import_exercises.py": ["/function_exercises.py"]}
|
14,933,698
|
albertopuentes/python-exercises
|
refs/heads/main
|
/warmup.py
|
# 1
input_truck = "toyota tacoma"
input_truck.split()
make = input_truck.split()[0]
model = input_truck.split()[-1]
truck = dict(make = make, model = model)
print(truck)
# 2
input_truck = "toyota tacoma"
input_truck.split()
make = input_truck.split()[0]
model = input_truck.split()[-1]
truck = dict(make = make, model = model)
truck['make'] = truck['make'].capitalize()
truck['model'] = truck['model'].capitalize()
print(truck)
# 3
trucks = [dict(make='toyota', model='tacoma'),
dict(make='ford', model='F150'),
dict(make='land rover', model ='range rover')]
for truck in trucks:
truck['make'] = truck['make'].title()
truck['model'] = truck['model'].title()
print(trucks)
|
{"/import_exercises.py": ["/function_exercises.py"]}
|
14,933,699
|
albertopuentes/python-exercises
|
refs/heads/main
|
/data_types_and_variables.py
|
Data Types, Operators, and Variables Exercises
# movie rental exercise
mermaid_days = 3
hercules_days = 1
bbear_days = 5
price = 3
days_held = mermaid_days + hercules_days + bbear_days
total = days_held * price
print(days_held)
print(total)
# Contractor exercise
Google_Pay = 400
Amazon_Pay = 380
Facebook_Pay = 350
Google_hours_worked = 6
Amazon_hours_worked = 4
Facebook_hours_worked = 10
Weekly_Pay = (Google_Pay * Google_hours_worked) + (Amazon_Pay * Amazon_hours_worked) + (Facebook_Pay * Facebook_hours_worked)
print(Weekly_Pay)
# Enrollment Exercise (if statement is True then can enroll, if False then can't enroll)
class_not_full = True
no_conflict = True
enroll = class_not_full and no_conflict
# product (if statement True offer can be applied, if False offer can't be applied)
person_items = x
not_expired = True
premium_member = True
not_expirend = True
offer_person = person_items >= 2 and not_expired
offer_premium_member = premium_member and not_expired
offer_either = (person_items >= 2 and not_expired) or (premium_member and not_expired)
# Username and Password
username = 'codeup'
password = 'notastrongpassword'
pass_user = (len(password) >= 5)
pass_passwored = (len(username) <= 20)
in_conflict = (username != password)
comb_works = pass_user and pass_password and in_conflict
print(pass_user, pass_password, in_conflict)
|
{"/import_exercises.py": ["/function_exercises.py"]}
|
14,980,635
|
Sujeet9271/AnudanProject
|
refs/heads/main
|
/Municipality/admin.py
|
from Accounts.models import FiscalYear
from Municipality.models import Municipality, Sector, Ward
from django.contrib import admin
from django.utils.translation import gettext_lazy as _
# Register your models here.
@admin.register(Municipality)
class NagarPalikaAdmin(admin.ModelAdmin):
list_display=['id','name','contact_number']
list_display_links=['id','name',]
def has_add_permission(self, request):
if not request.user.is_admin:
return False
return super().has_add_permission(request)
@admin.register(Sector)
class SectorAdmin(admin.ModelAdmin):
list_display=['id','name','municipality']
def get_queryset(self, request):
return super(SectorAdmin,self).get_queryset(request) if request.user.is_superuser else super(SectorAdmin,self).get_queryset(request).filter(municipality = request.user.municipality_staff.municipality.id)
def has_add_permission(self, request):
if not request.user.is_admin:
return False
return super().has_add_permission(request)
def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
if db_field.name == 'municipality':
kwargs['queryset'] = Municipality.objects.filter(id = request.user.municipality_staff.municipality.id) if not request.user.is_superuser else Municipality.objects.all()
kwargs['initial'] = Municipality.objects.get(id = request.user.municipality_staff.municipality.id) if not request.user.is_superuser else None
return super(SectorAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
@admin.register(Ward)
class WardAdmin(admin.ModelAdmin):
list_display=['id','name','municipality']
list_filter=['municipality']
def get_queryset(self, request):
qs = super(WardAdmin,self).get_queryset(request)
return qs if request.user.is_superuser else qs.filter(municipality = request.user.municipality_staff.municipality.id)
def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
if db_field.name == 'municipality':
kwargs['queryset'] = Municipality.objects.filter(id = request.user.municipality_staff.municipality.id) if not request.user.is_superuser else Municipality.objects.all()
kwargs['initial'] = Municipality.objects.get(id = request.user.municipality_staff.municipality.id) if not request.user.is_superuser else None
return super(WardAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
|
{"/anudaan/serializers.py": ["/anudaan/models.py"], "/anudaan/views.py": ["/anudaan/models.py", "/anudaan/serializers.py"], "/Accounts/views.py": ["/Accounts/models.py", "/Accounts/forms.py"], "/Accounts/admin.py": ["/Accounts/models.py", "/Accounts/forms.py", "/Municipality/models.py"], "/anudaan/migrations/0001_initial.py": ["/anudaan/models.py"], "/Accounts/models.py": ["/anudaan/models.py", "/Municipality/models.py"], "/Accounts/forms.py": ["/Accounts/models.py", "/Anudan/models.py"], "/anudaan/admin.py": ["/anudaan/models.py"], "/Municipality/admin.py": ["/Accounts/models.py", "/Municipality/models.py"], "/Anudan/forms.py": ["/Anudan/models.py", "/Accounts/models.py", "/Municipality/models.py"], "/Anudan/migrations/0001_initial.py": ["/Anudan/models.py"], "/Anudan/admin.py": ["/Municipality/models.py", "/Anudan/models.py", "/Anudan/forms.py"], "/Anudan/models.py": ["/Municipality/models.py"], "/AnudaanProject/urls.py": ["/Accounts/views.py"]}
|
14,980,636
|
Sujeet9271/AnudanProject
|
refs/heads/main
|
/Accounts/models.py
|
from django.db import models
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
from Municipality.models import Municipality
# Create your models here.
class CustomAccountManager(BaseUserManager):
def create_user(self, email, username, first_name, last_name, password, **other_fields):
email = self.normalize_email(email)
user = self.model(email=email, username=username, first_name=first_name, last_name=last_name, **other_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, username, first_name, last_name, password, **other_fields):
other_fields.setdefault('is_staff', True)
other_fields.setdefault('is_superuser', True)
other_fields.setdefault('is_admin', True)
if other_fields.get('is_staff') is False:
raise ValueError('Superuser must be assigned is_staff = True')
if other_fields.get('is_superuser') is False:
raise ValueError('Superuser must be assigned is_superuser = True')
return self.create_user(email=email, username=username, password=password, first_name=first_name,
last_name=last_name, **other_fields)
class PalikaUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(verbose_name=_('email'), unique=True)
username = models.CharField(verbose_name=_('username'),max_length=30, unique=True)
first_name = models.CharField(verbose_name=_('first name'),max_length=30, blank=True)
last_name = models.CharField(verbose_name=_('last name'),max_length=30, blank=True)
created = models.DateTimeField(verbose_name=_('created'),default=timezone.now)
is_active = models.BooleanField(verbose_name=_('is active'),default=True)
is_staff = models.BooleanField(verbose_name=_('is staff'),default=False)
is_admin = models.BooleanField(verbose_name=_('is admin'),default=False)
is_superuser = models.BooleanField(verbose_name=_('is superuser'),default=False)
date_joined = models.DateField(verbose_name=_('date joined'),auto_now_add=True,auto_now=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'first_name', 'last_name']
objects = CustomAccountManager()
def __str__(self):
return f'{self.email}'
def address(self):
return f'{self.Profile.address}'
address.short_description = _('address')
def contact_number(self):
return f'{self.Profile.contact_number}'
contact_number.short_description = _('contact number')
def get_fullname(self):
if self.first_name=='':
return self.get_username()
return f'{self.first_name} {self.last_name}'
class Meta:
db_table='Users'
verbose_name = _('user')
verbose_name_plural = _('users')
class MunicipalityStaff(models.Model):
user = models.OneToOneField(PalikaUser, on_delete=models.CASCADE, related_name='municipality_staff',verbose_name=_('user'),)
municipality = models.ForeignKey(Municipality, on_delete=models.CASCADE, related_name='municipality_staff',verbose_name=_('Municipality'),)
def __str__(self):
return f'{self.user.username} works in {self.municipality.name}'
class Meta:
db_table = 'Staff'
verbose_name = _('staff')
verbose_name_plural = _('staffs')
class Profile(models.Model):
user = models.OneToOneField(PalikaUser,verbose_name=_('user'), on_delete=models.CASCADE,related_name='Profile')
address = models.CharField(verbose_name=_('address'), max_length=150, blank=True, null=True)
contact_number = models.PositiveBigIntegerField(verbose_name=_('contact number'), blank=True, null=True)
def __str__(self):
return f"{self.user.username}'s Profile"
class Meta:
db_table='Profile'
verbose_name = 'Profile'
verbose_name_plural = 'Profile'
class FiscalYear(models.Model):
start_date = models.DateField()
end_date = models.DateField()
def __str__(self):
return f'{self.start_date}/{self.end_date}'
class Meta:
db_table = 'Fiscal_Year'
verbose_name = _('Fiscal Year')
verbose_name_plural = _('Fiscal Year')
|
{"/anudaan/serializers.py": ["/anudaan/models.py"], "/anudaan/views.py": ["/anudaan/models.py", "/anudaan/serializers.py"], "/Accounts/views.py": ["/Accounts/models.py", "/Accounts/forms.py"], "/Accounts/admin.py": ["/Accounts/models.py", "/Accounts/forms.py", "/Municipality/models.py"], "/anudaan/migrations/0001_initial.py": ["/anudaan/models.py"], "/Accounts/models.py": ["/anudaan/models.py", "/Municipality/models.py"], "/Accounts/forms.py": ["/Accounts/models.py", "/Anudan/models.py"], "/anudaan/admin.py": ["/anudaan/models.py"], "/Municipality/admin.py": ["/Accounts/models.py", "/Municipality/models.py"], "/Anudan/forms.py": ["/Anudan/models.py", "/Accounts/models.py", "/Municipality/models.py"], "/Anudan/migrations/0001_initial.py": ["/Anudan/models.py"], "/Anudan/admin.py": ["/Municipality/models.py", "/Anudan/models.py", "/Anudan/forms.py"], "/Anudan/models.py": ["/Municipality/models.py"], "/AnudaanProject/urls.py": ["/Accounts/views.py"]}
|
14,980,637
|
Sujeet9271/AnudanProject
|
refs/heads/main
|
/Accounts/migrations/0001_initial.py
|
# Generated by Django 3.2.4 on 2021-06-26 11:33
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('Municipality', '0001_initial'),
('auth', '0012_alter_user_first_name_max_length'),
]
operations = [
migrations.CreateModel(
name='FiscalYear',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('start_date', models.DateField()),
('end_date', models.DateField()),
],
options={
'verbose_name': 'Fiscal Year',
'verbose_name_plural': 'Fiscal Year',
'db_table': 'Fiscal_Year',
},
),
migrations.CreateModel(
name='PalikaUser',
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=254, unique=True, verbose_name='email')),
('username', models.CharField(max_length=30, unique=True, verbose_name='username')),
('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')),
('last_name', models.CharField(blank=True, max_length=30, verbose_name='last name')),
('created', models.DateTimeField(default=django.utils.timezone.now, verbose_name='created')),
('is_active', models.BooleanField(default=True, verbose_name='is active')),
('is_staff', models.BooleanField(default=False, verbose_name='is staff')),
('is_admin', models.BooleanField(default=False, verbose_name='is admin')),
('is_superuser', models.BooleanField(default=False, verbose_name='is superuser')),
('date_joined', models.DateField(auto_now_add=True, verbose_name='date joined')),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'verbose_name': 'user',
'verbose_name_plural': 'users',
'db_table': 'Users',
},
),
migrations.CreateModel(
name='Profile',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('address', models.CharField(blank=True, max_length=150, null=True, verbose_name='address')),
('contact_number', models.PositiveBigIntegerField(blank=True, null=True, verbose_name='contact number')),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='Profile', to=settings.AUTH_USER_MODEL, verbose_name='user')),
],
options={
'verbose_name': 'Profile',
'verbose_name_plural': 'Profile',
'db_table': 'Profile',
},
),
migrations.CreateModel(
name='MunicipalityStaff',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('municipality', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='municipality_staff', to='Municipality.municipality', verbose_name='Municipality')),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='municipality_staff', to=settings.AUTH_USER_MODEL, verbose_name='user')),
],
options={
'verbose_name': 'staff',
'verbose_name_plural': 'staffs',
'db_table': 'Staff',
},
),
]
|
{"/anudaan/serializers.py": ["/anudaan/models.py"], "/anudaan/views.py": ["/anudaan/models.py", "/anudaan/serializers.py"], "/Accounts/views.py": ["/Accounts/models.py", "/Accounts/forms.py"], "/Accounts/admin.py": ["/Accounts/models.py", "/Accounts/forms.py", "/Municipality/models.py"], "/anudaan/migrations/0001_initial.py": ["/anudaan/models.py"], "/Accounts/models.py": ["/anudaan/models.py", "/Municipality/models.py"], "/Accounts/forms.py": ["/Accounts/models.py", "/Anudan/models.py"], "/anudaan/admin.py": ["/anudaan/models.py"], "/Municipality/admin.py": ["/Accounts/models.py", "/Municipality/models.py"], "/Anudan/forms.py": ["/Anudan/models.py", "/Accounts/models.py", "/Municipality/models.py"], "/Anudan/migrations/0001_initial.py": ["/Anudan/models.py"], "/Anudan/admin.py": ["/Municipality/models.py", "/Anudan/models.py", "/Anudan/forms.py"], "/Anudan/models.py": ["/Municipality/models.py"], "/AnudaanProject/urls.py": ["/Accounts/views.py"]}
|
14,980,638
|
Sujeet9271/AnudanProject
|
refs/heads/main
|
/Municipality/migrations/0001_initial.py
|
# Generated by Django 3.2.4 on 2021-06-26 11:33
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Municipality',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=150, verbose_name='Name')),
('contact_number', models.CharField(default=0, max_length=10, verbose_name='Contact Number')),
],
options={
'verbose_name': 'Municipality',
'verbose_name_plural': 'Municipalities',
'db_table': 'Municipality',
},
),
migrations.CreateModel(
name='Ward',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=150, verbose_name='Name')),
('municipality', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='Municipality.municipality', verbose_name='Municipality')),
],
options={
'verbose_name': 'Ward',
'verbose_name_plural': 'Ward',
'db_table': 'Ward',
},
),
migrations.CreateModel(
name='Sector',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=150, verbose_name='Name')),
('municipality', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='Municipality.municipality', verbose_name='Municipality')),
],
options={
'verbose_name': 'Sector',
'verbose_name_plural': 'Sectors',
'db_table': 'Sector',
},
),
]
|
{"/anudaan/serializers.py": ["/anudaan/models.py"], "/anudaan/views.py": ["/anudaan/models.py", "/anudaan/serializers.py"], "/Accounts/views.py": ["/Accounts/models.py", "/Accounts/forms.py"], "/Accounts/admin.py": ["/Accounts/models.py", "/Accounts/forms.py", "/Municipality/models.py"], "/anudaan/migrations/0001_initial.py": ["/anudaan/models.py"], "/Accounts/models.py": ["/anudaan/models.py", "/Municipality/models.py"], "/Accounts/forms.py": ["/Accounts/models.py", "/Anudan/models.py"], "/anudaan/admin.py": ["/anudaan/models.py"], "/Municipality/admin.py": ["/Accounts/models.py", "/Municipality/models.py"], "/Anudan/forms.py": ["/Anudan/models.py", "/Accounts/models.py", "/Municipality/models.py"], "/Anudan/migrations/0001_initial.py": ["/Anudan/models.py"], "/Anudan/admin.py": ["/Municipality/models.py", "/Anudan/models.py", "/Anudan/forms.py"], "/Anudan/models.py": ["/Municipality/models.py"], "/AnudaanProject/urls.py": ["/Accounts/views.py"]}
|
14,980,639
|
Sujeet9271/AnudanProject
|
refs/heads/main
|
/Accounts/admin.py
|
from Municipality.models import Municipality
from django.contrib import admin
from .models import FiscalYear, PalikaUser, MunicipalityStaff, Profile
from django.contrib.auth.admin import UserAdmin,GroupAdmin
from .forms import CustomUserCreationForm, CustomUserChangeForm, FiscalYearForm, PalikaStaffForm, ProfileForm
from django.utils.translation import gettext as _
from django.contrib.auth.models import Group
# Unregister models here
admin.site.unregister(Group)
# Register models here
@admin.register(Group)
class CustomGroupAdmin(GroupAdmin):
def formfield_for_manytomany(self, db_field, request=None, **kwargs):
if not request.user.is_superuser:
if db_field.name == 'permissions':
qs = kwargs.get('queryset', db_field.remote_field.model.objects)
qs = qs.exclude(codename__in=(
'add_municipality',
'delete_municipality',
'add_group',
'change_group',
'delete_group',
'view_group',
'add_fiscalyear',
'delete_fiscalyear',
'change_fiscalyear',
'add_permission',
'change_permission',
'delete_permission',
'view_permission',
'add_contenttype',
'view_contenttype',
'change_contenttype',
'delete_contenttype',
'add_session',
'view_session',
'delete_session',
'change_session',
'add_logentry',
'view_logentry',
'change_logentry',
'delete_logentry',
))
kwargs['queryset'] = qs.select_related('content_type')
return super(CustomGroupAdmin, self).formfield_for_manytomany(
db_field, request=request, **kwargs)
@admin.register(FiscalYear)
class FiscalYearAdmin(admin.ModelAdmin):
list_display = ['start_date','end_date']
form = FiscalYearForm
class PalikaStaffAdminInline(admin.TabularInline):
model = MunicipalityStaff
def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
if db_field.name == 'municipality':
kwargs['queryset'] = Municipality.objects.filter(id = request.user.municipality_staff.municipality.id) if not request.user.is_superuser else Municipality.objects.all()
kwargs['initial'] = Municipality.objects.filter(id = request.user.municipality_staff.municipality.id) if not request.user.is_superuser else None
return super(PalikaStaffAdminInline, self).formfield_for_foreignkey(db_field, request, **kwargs)
class ProfileInline(admin.TabularInline):
model = Profile
@admin.register(PalikaUser)
class UserAdminConfig(UserAdmin):
model = PalikaUser
add_form = CustomUserCreationForm
form = CustomUserChangeForm
inlines = [PalikaStaffAdminInline,ProfileInline]
list_display = ['id','email', 'username', 'first_name', 'last_name', 'address', 'contact_number', 'is_staff', 'is_admin',
'is_superuser', 'municipality_staff',]
list_display_links = ['email', 'username']
readonly_fields = ['last_login', 'date_joined']
list_filter=['is_staff','is_admin']
fieldsets = (
(_('User Details'), {'fields': ('email', 'password')}),
(_('Personal info'), {'fields': ('username', 'first_name', 'last_name')}),
(_('Permissions'), {
'fields': ('is_staff', 'is_admin', 'groups', 'user_permissions'),
}),
(_('Important dates'), {'fields': ('last_login', 'date_joined')}),
)
add_fieldsets = (
(_('Staff Registration'), {
'classes': ('wide',),
'fields': ('email', 'username', 'first_name', 'last_name', 'password1', 'password2',)}),
(_('Permissions'),{'fields':('is_staff','is_admin','groups','user_permissions')}),
)
def formfield_for_manytomany(self, db_field, request=None, **kwargs):
if not request.user.is_superuser:
if db_field.name == 'user_permissions':
qs = kwargs.get('queryset', db_field.remote_field.model.objects)
qs = qs.exclude(codename__in=(
'add_municipality',
'delete_municipality',
'add_fiscalyear',
'delete_fiscalyear',
'change_fiscalyear',
'add_permission',
'change_permission',
'delete_permission',
'add_contenttype',
'view_contenttype',
'change_contenttype',
'delete_contenttype',
'add_session',
'view_session',
'delete_session',
'change_session',
'add_logentry',
'view_logentry',
'change_logentry',
'delete_logentry',
))
kwargs['queryset'] = qs.select_related('content_type')
return super(UserAdminConfig, self).formfield_for_manytomany(
db_field, request=request, **kwargs)
def get_queryset(self, request):
qs = super().get_queryset(request)
if request.user.is_superuser:
return qs
if request.user.is_admin:
return qs.filter(municipality_staff__municipality=request.user.municipality_staff.municipality.id)
return qs.filter(id=request.user.id)
def get_readonly_fields(self, request,obj):
if obj:
if request.user.is_superuser:
return self.readonly_fields
elif request.user.is_admin:
return self.readonly_fields + ['email','is_admin']
return self.readonly_fields +['email','is_staff', 'is_admin','is_active','groups','user_permissions'] if obj.email==request.user.email else self.readonly_fields+['email','password','username','first_name','last_name','groups','user_permissions','is_staff','is_admin','Profile']
else:
if request.user.is_superuser:
return self.readonly_fields
elif request.user.is_admin:
return self.readonly_fields + ['is_admin']
return self.readonly_fields +['is_staff', 'is_admin','is_active','groups','user_permissions']
def has_add_permission(self, request):
if not request.user.is_admin:
return False
return super().has_add_permission(request)
# @admin.register(Profile)
class ProfileAdmin(admin.ModelAdmin):
list_display=['user','address', 'contact_number']
fieldsets = (
(_('User Profile'), {'fields': ('user','address','contact_number')}),
)
def get_queryset(self, request):
qs = super(ProfileAdmin, self).get_queryset(request)
if request.user.is_superuser:
return qs
return qs.filter(user=request.user)
def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
if db_field.name == 'user':
kwargs['queryset'] = PalikaUser.objects.filter(id = request.user.id) if not request.user.is_superuser else PalikaUser.objects.all()
kwargs['initial'] = PalikaUser.objects.get(id = request.user.id) if not request.user.is_superuser else None
return super(ProfileAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
|
{"/anudaan/serializers.py": ["/anudaan/models.py"], "/anudaan/views.py": ["/anudaan/models.py", "/anudaan/serializers.py"], "/Accounts/views.py": ["/Accounts/models.py", "/Accounts/forms.py"], "/Accounts/admin.py": ["/Accounts/models.py", "/Accounts/forms.py", "/Municipality/models.py"], "/anudaan/migrations/0001_initial.py": ["/anudaan/models.py"], "/Accounts/models.py": ["/anudaan/models.py", "/Municipality/models.py"], "/Accounts/forms.py": ["/Accounts/models.py", "/Anudan/models.py"], "/anudaan/admin.py": ["/anudaan/models.py"], "/Municipality/admin.py": ["/Accounts/models.py", "/Municipality/models.py"], "/Anudan/forms.py": ["/Anudan/models.py", "/Accounts/models.py", "/Municipality/models.py"], "/Anudan/migrations/0001_initial.py": ["/Anudan/models.py"], "/Anudan/admin.py": ["/Municipality/models.py", "/Anudan/models.py", "/Anudan/forms.py"], "/Anudan/models.py": ["/Municipality/models.py"], "/AnudaanProject/urls.py": ["/Accounts/views.py"]}
|
14,980,640
|
Sujeet9271/AnudanProject
|
refs/heads/main
|
/Anudan/forms.py
|
from django import forms
from .models import AnudanCompany, AnudanPersonal,Karyakram,Samagri
from django.utils.translation import gettext_lazy as _
from Accounts.models import FiscalYear
from Municipality.models import Municipality
class AnudanPersonalForm(forms.ModelForm):
municipality = forms.ModelChoiceField(label=_('Municipality'),queryset=Municipality.objects.none())
quantity = forms.IntegerField(label = _('Quantity'))
fiscal_year = forms.ModelChoiceField(label=_('Fiscal Year'),queryset=FiscalYear.objects.all())
def __init__(self, *args,**kwargs):
super(AnudanPersonalForm,self).__init__(*args,**kwargs)
self.fields['municipality'].queryset = Municipality.objects.filter(id = self.current_user.municipality_staff.municipality.id) if not self.current_user.is_superuser else Municipality.objects.all()
self.fields['municipality'].initial = Municipality.objects.get(id=self.current_user.municipality_staff.municipality.id) if not self.current_user.is_superuser else None
self.fields['fiscal_year'].initial = FiscalYear.objects.latest('id')
class Meta:
model = AnudanPersonal
fields = ['fiscal_year','municipality','name','ward','tole','nagrikta_number','contact_number','jari_jilla','nagrikta_front','nagrikta_back','sector','karyakram','samagri','quantity']
# class AnudanCompanyForm(forms.ModelForm):
# fiscal_year = forms.ModelChoiceField(label=_('Fiscal Year'),queryset=FiscalYear.objects.all())
# municipality = forms.ModelChoiceField(queryset=Municipality.objects.none(),label=_('Municipality'))
# def __init__(self, *args,**kwargs):
# super(AnudanCompanyForm,self).__init__(*args,**kwargs)
# self.fields['municipality'].queryset = Municipality.objects.filter(id = self.current_user.municipality_staff.municipality.id) if not self.current_user.is_superuser else Municipality.objects.all()
# self.fields['municipality'].initial = Municipality.objects.get(id = self.current_user.municipality_staff.municipality.id) if not self.current_user.is_superuser else None
# class Meta:
# model = AnudanCompany
# fields = ['fiscal_year','municipality','firm_name','vat_no','pan_no','registration_no','ward','tole','registered_place','firm_registration_proof','anya_darta','ward_sifaris','prastavan','approval']
class KaryakramForm(forms.ModelForm):
municipality = forms.ModelChoiceField(label=_('Municipality'),queryset=Municipality.objects.none())
def __init__(self, *args,**kwargs):
super(KaryakramForm,self).__init__(*args,**kwargs)
self.fields['municipality'].queryset = Municipality.objects.filter(id=self.current_user.municipality_staff.municipality.id) if not self.current_user.is_superuser else Municipality.objects.all()
self.fields['municipality'].initial = 0 if not self.current_user.is_superuser else None
class Meta:
model = Karyakram
fields = ['municipality','sector','name']
class SamagriForm(forms.ModelForm):
class Meta:
model = Samagri
fields = ['karyakram','name']
class AnudanCompanyForm(forms.ModelForm):
municipality = forms.ModelChoiceField(queryset=Municipality.objects.none(),label=_('Municipality'))
fiscal_year = forms.ModelChoiceField(queryset=FiscalYear.objects.all(),label=_('Fiscal Year'))
def __init__(self, *args,**kwargs):
super(AnudanCompanyForm,self).__init__(*args,**kwargs)
self.fields['municipality'].queryset = Municipality.objects.filter(id = self.current_user.municipality_staff.municipality.id) if not self.current_user.is_superuser else Municipality.objects.all()
self.fields['municipality'].initial = Municipality.objects.get(id = self.current_user.municipality_staff.municipality.id) if not self.current_user.is_superuser else None
self.fields['fiscal_year'].initial = FiscalYear.objects.latest('id')
class Meta:
model = AnudanCompany
fields = '__all__'
|
{"/anudaan/serializers.py": ["/anudaan/models.py"], "/anudaan/views.py": ["/anudaan/models.py", "/anudaan/serializers.py"], "/Accounts/views.py": ["/Accounts/models.py", "/Accounts/forms.py"], "/Accounts/admin.py": ["/Accounts/models.py", "/Accounts/forms.py", "/Municipality/models.py"], "/anudaan/migrations/0001_initial.py": ["/anudaan/models.py"], "/Accounts/models.py": ["/anudaan/models.py", "/Municipality/models.py"], "/Accounts/forms.py": ["/Accounts/models.py", "/Anudan/models.py"], "/anudaan/admin.py": ["/anudaan/models.py"], "/Municipality/admin.py": ["/Accounts/models.py", "/Municipality/models.py"], "/Anudan/forms.py": ["/Anudan/models.py", "/Accounts/models.py", "/Municipality/models.py"], "/Anudan/migrations/0001_initial.py": ["/Anudan/models.py"], "/Anudan/admin.py": ["/Municipality/models.py", "/Anudan/models.py", "/Anudan/forms.py"], "/Anudan/models.py": ["/Municipality/models.py"], "/AnudaanProject/urls.py": ["/Accounts/views.py"]}
|
14,980,641
|
Sujeet9271/AnudanProject
|
refs/heads/main
|
/Anudan/migrations/0002_anudancompany_contact_number.py
|
# Generated by Django 3.2.4 on 2021-06-26 11:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Anudan', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='anudancompany',
name='contact_number',
field=models.CharField(default=0, max_length=20, verbose_name='Contact Number'),
),
]
|
{"/anudaan/serializers.py": ["/anudaan/models.py"], "/anudaan/views.py": ["/anudaan/models.py", "/anudaan/serializers.py"], "/Accounts/views.py": ["/Accounts/models.py", "/Accounts/forms.py"], "/Accounts/admin.py": ["/Accounts/models.py", "/Accounts/forms.py", "/Municipality/models.py"], "/anudaan/migrations/0001_initial.py": ["/anudaan/models.py"], "/Accounts/models.py": ["/anudaan/models.py", "/Municipality/models.py"], "/Accounts/forms.py": ["/Accounts/models.py", "/Anudan/models.py"], "/anudaan/admin.py": ["/anudaan/models.py"], "/Municipality/admin.py": ["/Accounts/models.py", "/Municipality/models.py"], "/Anudan/forms.py": ["/Anudan/models.py", "/Accounts/models.py", "/Municipality/models.py"], "/Anudan/migrations/0001_initial.py": ["/Anudan/models.py"], "/Anudan/admin.py": ["/Municipality/models.py", "/Anudan/models.py", "/Anudan/forms.py"], "/Anudan/models.py": ["/Municipality/models.py"], "/AnudaanProject/urls.py": ["/Accounts/views.py"]}
|
14,980,642
|
Sujeet9271/AnudanProject
|
refs/heads/main
|
/Municipality/models.py
|
from django.db import models
from django.utils.translation import gettext_lazy as _
# Create your models here.
class Municipality(models.Model):
name = models.CharField(verbose_name=_('Name'),max_length=150)
contact_number = models.CharField(verbose_name=_('Contact Number'),max_length=10,unique=True)
def __str__(self):
return f'{self.name}'
class Meta:
db_table='Municipality'
verbose_name = _('Municipality')
verbose_name_plural = _('Municipalities')
class Sector(models.Model):
municipality = models.ForeignKey(Municipality,verbose_name=_('Municipality'), on_delete=models.CASCADE)
name = models.CharField(max_length=150,verbose_name=_('Name'))
def __str__(self):
return f"{self.name}-{self.municipality.name}"
class Meta:
db_table='Sector'
verbose_name = _('Sector')
verbose_name_plural = _('Sectors')
class Ward(models.Model):
municipality = models.ForeignKey(Municipality,verbose_name=_('Municipality'), on_delete=models.CASCADE)
name = models.CharField(verbose_name=_('Name'),max_length=150)
def __str__(self):
return f'{self.name}-{self.municipality.name}'
class Meta:
db_table='Ward'
verbose_name = _('Ward')
verbose_name_plural = _('Ward')
|
{"/anudaan/serializers.py": ["/anudaan/models.py"], "/anudaan/views.py": ["/anudaan/models.py", "/anudaan/serializers.py"], "/Accounts/views.py": ["/Accounts/models.py", "/Accounts/forms.py"], "/Accounts/admin.py": ["/Accounts/models.py", "/Accounts/forms.py", "/Municipality/models.py"], "/anudaan/migrations/0001_initial.py": ["/anudaan/models.py"], "/Accounts/models.py": ["/anudaan/models.py", "/Municipality/models.py"], "/Accounts/forms.py": ["/Accounts/models.py", "/Anudan/models.py"], "/anudaan/admin.py": ["/anudaan/models.py"], "/Municipality/admin.py": ["/Accounts/models.py", "/Municipality/models.py"], "/Anudan/forms.py": ["/Anudan/models.py", "/Accounts/models.py", "/Municipality/models.py"], "/Anudan/migrations/0001_initial.py": ["/Anudan/models.py"], "/Anudan/admin.py": ["/Municipality/models.py", "/Anudan/models.py", "/Anudan/forms.py"], "/Anudan/models.py": ["/Municipality/models.py"], "/AnudaanProject/urls.py": ["/Accounts/views.py"]}
|
14,980,643
|
Sujeet9271/AnudanProject
|
refs/heads/main
|
/Municipality/migrations/0002_alter_municipality_contact_number.py
|
# Generated by Django 3.2.4 on 2021-06-26 11:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Municipality', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='municipality',
name='contact_number',
field=models.CharField(max_length=10, unique=True, verbose_name='Contact Number'),
),
]
|
{"/anudaan/serializers.py": ["/anudaan/models.py"], "/anudaan/views.py": ["/anudaan/models.py", "/anudaan/serializers.py"], "/Accounts/views.py": ["/Accounts/models.py", "/Accounts/forms.py"], "/Accounts/admin.py": ["/Accounts/models.py", "/Accounts/forms.py", "/Municipality/models.py"], "/anudaan/migrations/0001_initial.py": ["/anudaan/models.py"], "/Accounts/models.py": ["/anudaan/models.py", "/Municipality/models.py"], "/Accounts/forms.py": ["/Accounts/models.py", "/Anudan/models.py"], "/anudaan/admin.py": ["/anudaan/models.py"], "/Municipality/admin.py": ["/Accounts/models.py", "/Municipality/models.py"], "/Anudan/forms.py": ["/Anudan/models.py", "/Accounts/models.py", "/Municipality/models.py"], "/Anudan/migrations/0001_initial.py": ["/Anudan/models.py"], "/Anudan/admin.py": ["/Municipality/models.py", "/Anudan/models.py", "/Anudan/forms.py"], "/Anudan/models.py": ["/Municipality/models.py"], "/AnudaanProject/urls.py": ["/Accounts/views.py"]}
|
14,980,644
|
Sujeet9271/AnudanProject
|
refs/heads/main
|
/Anudan/migrations/0001_initial.py
|
# Generated by Django 3.2.4 on 2021-06-26 11:33
import Anudan.models
from django.db import migrations, models
import django.db.models.deletion
import smart_selects.db_fields
class Migration(migrations.Migration):
initial = True
dependencies = [
('Accounts', '0001_initial'),
('Municipality', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Karyakram',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255, verbose_name='Name')),
('created', models.DateTimeField(auto_now_add=True, verbose_name='created')),
('municipality', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='Municipality.municipality', verbose_name='Municipality')),
('sector', smart_selects.db_fields.ChainedForeignKey(auto_choose=True, chained_field='municipality', chained_model_field='municipality', on_delete=django.db.models.deletion.PROTECT, to='Municipality.sector', verbose_name='Sector')),
],
options={
'verbose_name': 'Karyakram',
'verbose_name_plural': 'Karyakram',
'db_table': 'Karyakram',
},
),
migrations.CreateModel(
name='Medicine',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=150, verbose_name='Name')),
],
options={
'verbose_name': 'Medicine',
'verbose_name_plural': 'Medicines',
'db_table': 'Medicine',
},
),
migrations.CreateModel(
name='MedicineRequest',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=150, verbose_name='Name')),
('contact_number', models.CharField(max_length=10, verbose_name='Contact Number')),
('tole', models.CharField(max_length=150, verbose_name='Tole')),
('created', models.DateField(auto_now_add=True, verbose_name='created')),
('municipality', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='Municipality.municipality', verbose_name='Municipality')),
('ward', smart_selects.db_fields.ChainedForeignKey(auto_choose=True, chained_field='municipality', chained_model_field='municipality', on_delete=django.db.models.deletion.PROTECT, to='Municipality.ward', verbose_name='Ward')),
],
options={
'verbose_name': 'Medicine Request',
'verbose_name_plural': 'Medicine Request',
'db_table': 'Medicine_Request',
},
),
migrations.CreateModel(
name='Unit',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50, verbose_name='Name')),
],
options={
'verbose_name': 'Unit',
'verbose_name_plural': 'Units',
'db_table': 'Unit',
},
),
migrations.CreateModel(
name='Samagri',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255, verbose_name='Name')),
('quantity', models.IntegerField(default=1, verbose_name='Quantity')),
('karyakram', smart_selects.db_fields.ChainedForeignKey(auto_choose=True, chained_field='municipality', chained_model_field='municipality', on_delete=django.db.models.deletion.PROTECT, to='Anudan.karyakram', verbose_name='Karyakram')),
('unit', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='Anudan.unit', verbose_name='Units')),
],
options={
'verbose_name': 'Samagri',
'verbose_name_plural': 'Samagri',
'db_table': 'Samagri',
'ordering': ['karyakram'],
},
),
migrations.CreateModel(
name='MedicineRequested',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('quantity', models.PositiveSmallIntegerField(default=1, verbose_name='Quantity')),
('medicine', models.ForeignKey(max_length=150, on_delete=django.db.models.deletion.CASCADE, related_name='Medicines_Requested', to='Anudan.medicine', verbose_name='Medicine')),
('requested_by', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='Medicines_Requested', to='Anudan.medicinerequest', verbose_name='Requested By')),
],
),
migrations.CreateModel(
name='AnudanPersonal',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255, verbose_name='Name')),
('tole', models.CharField(max_length=150, verbose_name='Tole')),
('nagrikta_number', models.CharField(max_length=20, verbose_name='Nagrikta Number')),
('nagrikta_front', models.ImageField(upload_to=Anudan.models.personal_location, verbose_name='Nagrikta Front Photo')),
('nagrikta_back', models.ImageField(blank=True, upload_to=Anudan.models.personal_location, verbose_name='Nagrikta Back Photo')),
('jari_jilla', models.CharField(max_length=20, verbose_name='Jaari Jilla')),
('contact_number', models.CharField(max_length=20, verbose_name='Contact Number')),
('quantity', models.PositiveSmallIntegerField(default=1)),
('approval', models.CharField(choices=[('Approved', 'Approved'), ('Not Approved', 'Not Approved')], default='Not Approved', max_length=14, verbose_name='Approval')),
('created', models.DateField(auto_now_add=True, verbose_name='created')),
('updated', models.DateField(auto_now=True, verbose_name='updated')),
('fiscal_year', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='Accounts.fiscalyear', verbose_name='Fiscal Year')),
('karyakram', smart_selects.db_fields.ChainedForeignKey(auto_choose=True, chained_field='sector', chained_model_field='sector', on_delete=django.db.models.deletion.PROTECT, to='Anudan.karyakram', verbose_name='Karyakram')),
('municipality', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='Municipality.municipality', verbose_name='Municipality')),
('samagri', smart_selects.db_fields.ChainedForeignKey(auto_choose=True, chained_field='karyakram', chained_model_field='karyakram', on_delete=django.db.models.deletion.PROTECT, to='Anudan.samagri', verbose_name='Samagri')),
('sector', smart_selects.db_fields.ChainedForeignKey(auto_choose=True, chained_field='municipality', chained_model_field='municipality', on_delete=django.db.models.deletion.PROTECT, to='Municipality.sector', verbose_name='Sector')),
('ward', smart_selects.db_fields.ChainedForeignKey(auto_choose=True, chained_field='municipality', chained_model_field='municipality', on_delete=django.db.models.deletion.PROTECT, to='Municipality.ward', verbose_name='Ward')),
],
options={
'verbose_name': 'Anudan Personal',
'verbose_name_plural': 'Anudan Personal',
'db_table': 'Anudan_Personal',
},
),
migrations.CreateModel(
name='AnudanCompany',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('firm_name', models.CharField(max_length=255, verbose_name='Firm name')),
('pan_no', models.CharField(blank=True, max_length=20, null=True, verbose_name='PAN no')),
('vat_no', models.CharField(blank=True, max_length=20, null=True, verbose_name='VAT no')),
('registration_no', models.CharField(blank=True, max_length=20, null=True, verbose_name='Registration Number')),
('tole', models.CharField(max_length=150, verbose_name='Tole')),
('registered_place', models.CharField(max_length=20, verbose_name='Jaari Jilla')),
('anya_darta', models.CharField(blank=True, choices=[('Gharelu', 'Gharelu'), ('Banijya', 'Banijya')], max_length=50, null=True, verbose_name='Registered as')),
('firm_registration_proof', models.ImageField(upload_to=Anudan.models.company_location, verbose_name='Firm Registration Proof')),
('ward_sifaris', models.ImageField(upload_to=Anudan.models.company_location, verbose_name='Ward Sifaris')),
('prastavan', models.ImageField(upload_to=Anudan.models.company_location, verbose_name='Upload Prastavan')),
('approval', models.CharField(choices=[('Approved', 'Approved'), ('Not Approved', 'Not Approved')], default='Not Approved', max_length=14, verbose_name='Approval')),
('created', models.DateField(auto_now_add=True, verbose_name='created')),
('updated', models.DateField(auto_now=True, verbose_name='updated')),
('fiscal_year', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='Accounts.fiscalyear', verbose_name='Fiscal Year')),
('karyakram', smart_selects.db_fields.ChainedForeignKey(auto_choose=True, chained_field='sector', chained_model_field='sector', on_delete=django.db.models.deletion.PROTECT, to='Anudan.karyakram', verbose_name='Karyakram')),
('municipality', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='Municipality.municipality', verbose_name='Municipality')),
('sector', smart_selects.db_fields.ChainedForeignKey(auto_choose=True, chained_field='municipality', chained_model_field='municipality', on_delete=django.db.models.deletion.PROTECT, to='Municipality.sector', verbose_name='Sector')),
('ward', smart_selects.db_fields.ChainedForeignKey(auto_choose=True, chained_field='municipality', chained_model_field='municipality', on_delete=django.db.models.deletion.PROTECT, to='Municipality.ward', verbose_name='Ward')),
],
options={
'verbose_name': 'Anudan Company',
'verbose_name_plural': 'Anudan Company',
'db_table': 'Anudan_Company',
},
),
]
|
{"/anudaan/serializers.py": ["/anudaan/models.py"], "/anudaan/views.py": ["/anudaan/models.py", "/anudaan/serializers.py"], "/Accounts/views.py": ["/Accounts/models.py", "/Accounts/forms.py"], "/Accounts/admin.py": ["/Accounts/models.py", "/Accounts/forms.py", "/Municipality/models.py"], "/anudaan/migrations/0001_initial.py": ["/anudaan/models.py"], "/Accounts/models.py": ["/anudaan/models.py", "/Municipality/models.py"], "/Accounts/forms.py": ["/Accounts/models.py", "/Anudan/models.py"], "/anudaan/admin.py": ["/anudaan/models.py"], "/Municipality/admin.py": ["/Accounts/models.py", "/Municipality/models.py"], "/Anudan/forms.py": ["/Anudan/models.py", "/Accounts/models.py", "/Municipality/models.py"], "/Anudan/migrations/0001_initial.py": ["/Anudan/models.py"], "/Anudan/admin.py": ["/Municipality/models.py", "/Anudan/models.py", "/Anudan/forms.py"], "/Anudan/models.py": ["/Municipality/models.py"], "/AnudaanProject/urls.py": ["/Accounts/views.py"]}
|
14,980,645
|
Sujeet9271/AnudanProject
|
refs/heads/main
|
/Anudan/admin.py
|
from re import template
from django.http.response import HttpResponse
from Municipality.models import Municipality
from django.contrib import admin
from .models import AnudanCompany, Karyakram, Medicine, MedicineRequest, MedicineRequested,Samagri,AnudanPersonal, Unit
from django.utils.translation import gettext_lazy as _
from .forms import AnudanCompanyForm,AnudanPersonalForm,KaryakramForm
import csv
from django.template.loader import get_template
from xhtml2pdf import pisa
from io import BytesIO
# Register your models here.
@admin.register(Medicine)
class MedicineAdmin(admin.ModelAdmin):
list_display=['id','name']
class MedicineInline(admin.TabularInline):
model = MedicineRequested
extra = 1
@admin.register(MedicineRequest)
class MedicineRequestAdmin(admin.ModelAdmin):
list_display = ['id','name','ward','tole']
list_display_links=['id','name']
list_filter = ['ward','tole']
inlines=[MedicineInline]
actions=['export_to_csv','render_pdf_view']
@admin.action(description='Export to CSV')
def export_to_csv(self, request, queryset):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="MedicineRequests.csv"'
print(request.path)
writer = csv.writer(response)
if '/ne/' in request.path:
writer.writerow(['नाम','सम्पर्क नम्बर','नगरपालिका','वडा','टोल','औषधी','मात्रा'])
else:
writer.writerow(['Name','Contact Number','Municipality','Ward','Tole','Medicines','Quantity'])
id = queryset.values_list('id',flat=True)
for id in id:
records=MedicineRequested.objects.filter(requested_by__id=id).values_list('requested_by__name','requested_by__contact_number','requested_by__municipality__name','requested_by__ward__name','requested_by__tole','medicine__name','quantity')
for record in records:
writer.writerow(record)
return response
@admin.action(description='Export to pdf')
def render_pdf_view(self,request,queryset):
template_path = 'MedicineRequest.html'
id = [id for id in queryset.values_list('id',flat=True)]
medicines =MedicineRequested.objects.filter(requested_by__id__in=id).order_by('id')
context = {'queryset': medicines}
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="MedicineRequest.pdf"'
template = get_template(template_path)
html = template.render(context)
pisa_status = pisa.CreatePDF(html, dest=response)
if pisa_status.err:
return HttpResponse('We had some errors <pre>' + html + '</pre>')
return response
def get_queryset(self, request):
qs = super().get_queryset(request)
if request.user.is_superuser:
return qs
return qs.filter(municipality = request.user.municipality_staff.municipality.id)
def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
if db_field.name == 'municipality':
kwargs['queryset'] = Municipality.objects.filter(id = request.user.municipality_staff.municipality.id) if not request.user.is_superuser else Municipality.objects.all()
kwargs['initial'] = Municipality.objects.get(id = request.user.municipality_staff.municipality.id) if not request.user.is_superuser else None
return super(MedicineRequestAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
class SamagriInline(admin.StackedInline):
model = Samagri
extra = 1
@admin.register(Karyakram)
class KaryakramAdmin(admin.ModelAdmin):
list_display=['id','name','municipality']
list_display_links=['id','name']
list_filter=['municipality']
inlines=[SamagriInline]
form=KaryakramForm
def get_queryset(self, request):
qs = super(KaryakramAdmin, self).get_queryset(request)
if request.user.is_superuser:
return qs
return qs.filter(municipality=request.user.municipality_staff.municipality)
def get_form(self, request,*args, **kwargs):
form = super(KaryakramAdmin,self).get_form(request,*args, **kwargs)
form.current_user=request.user
return form
@admin.register(Unit)
class UnitAdmin(admin.ModelAdmin):
list_display = ['id','name']
# @admin.register(Samagri)
# class SamagriAdmin(admin.ModelAdmin):
# list_display=['id','name','karyakram',]
# list_filter=['karyakram']
# list_display_links=['id','name']
# form = SamagriForm
# def get_queryset(self, request):
# qs = super(SamagriAdmin, self).get_queryset(request)
# if request.user.is_superuser:
# return qs
# return qs.filter(municipality=request.user.municipality_staff.municipality)
# def get_form(self, request,*args, **kwargs):
# form = super(SamagriAdmin,self).get_form(request,*args, **kwargs)
# form.current_user=request.user
# return form
@admin.action(permissions=['change'],description='Approve Selected')
def approve(modaladmin,request, queryset):
queryset.update(approval='Approved')
@admin.action(permissions=['change'],description='Disapprove Selected')
def disapprove(modaldamin,request, queryset):
queryset.update(approval='Not Approved')
@admin.register(AnudanPersonal)
class AnudanPersonalAdmin(admin.ModelAdmin):
list_display=['id','name','municipality','ward','tole','karyakram','samagri','approval']
list_filter=['fiscal_year','sector','karyakram','ward','approval']
list_display_links=['id','name']
actions = [approve,disapprove,'export_to_csv','render_pdf_view']
ordering=['ward']
list_editable=['approval']
fieldsets = (
(_('Fiscal Year'),{'fields':('fiscal_year',),'classes':('wide',)}),
(_('Municipality'), {'fields': ('municipality',),'classes':("wide",),'description':_('Select Municipality')}),
(_('Personal info'), {'fields': ( 'name','contact_number',),'classes':("wide",),'description':_('Enter Your Name')}),
(_('Address'), {'fields': ('ward', 'tole',),'classes':("wide",),'description':_('Enter Your Address')}),
(_('Nagrikta Details'), {'fields': ('nagrikta_number', 'jari_jilla','nagrikta_front','nagrikta_back'),'classes':("wide",),'description':_('Enter Your citizenship details')}),
(_('Anudan Request'),{'fields':('sector','karyakram','samagri','quantity'),'classes':("wide",),'description':_('Select Karyakram and Samagri')}),
(_('Approval'),{'fields':('approval',),'classes':("wide",),'description':'Test'})
)
add_fieldsets = (
(_('Fiscal Year'),{'fields':('fiscal_year',),'classes':('wide',)}),
(_('Municipality'), {'fields': ('municipality',),'classes':("wide",),'description':_('Select Municipality')}),
(_('Personal info'), {'fields': ( 'name','contact_number',),'classes':("wide",),'description':_('Enter Your Name')}),
(_('Address'), {'fields': ('ward', 'tole',),'classes':("wide",),'description':_('Enter Your Address')}),
(_('Nagrikta Details'), {'fields': ('nagrikta_number', 'jari_jilla','nagrikta_front','nagrikta_back'),'classes':("wide",),'description':_('Enter Your citizenship details')}),
(_('Anudan Request'),{'fields':('sector','karyakram','samagri','quantity'),'classes':("wide",),'description':_('Select Karyakram and Samagri')}),
)
staff_fieldsets = (
(_('Municipality'), {'fields': ('municipality',),'classes':("collapse",)}),
(_('Fiscal Year'),{'fields':('fiscal_year',),'classes':('wide',)}),
(_('Personal info'), {'fields': ( 'name','contact_number'),'classes':("wide",),'description':_('Enter Your Name')}),
(_('Address'), {'fields': ('ward', 'tole',),'classes':("wide",),'description':_('Enter Your Address')}),
(_('Nagrikta Details'), {'fields': ('nagrikta_number', 'jari_jilla','nagrikta_front','nagrikta_back'),'classes':("wide",),'description':_('Enter Your citizenship details')}),
(_('Anudan Request'),{'fields':('sector','karyakram','samagri','quantity'),'classes':("wide",),'description':_('Select Karyakram and Samagri')}),
)
@admin.action(description='Export to CSV')
def export_to_csv(self, request, queryset):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="books.csv"'
writer = csv.writer(response)
if '/ne/' in request.path:
writer.writerow(['नाम','सम्पर्क नम्बर','नगरपालिका','टोल','वडा','कार्यक्रम','सामग्री','मात्रा','स्वीकृति'])
else:
writer.writerow(['Name','Contact Number','Municipality','Ward','Tole','Karyakram','Samagri','Quantity','Approval'])
books = queryset.values_list('name','contact_number','municipality__name','ward__name','tole','karyakram__name', 'samagri__name', 'quantity', 'approval')
for book in books:
writer.writerow(book)
return response
@admin.action(description='Export to pdf')
def render_pdf_view(self,request,queryset):
template_path = 'AnudanPersonal.html'
context = {'queryset': queryset}
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="AnudanPersonal.pdf"'
template = get_template(template_path)
html = template.render(context)
pisa_status = pisa.CreatePDF(html, dest=response)
if pisa_status.err:
return HttpResponse('We had some errors <pre>' + html + '</pre>')
return response
def get_queryset(self, request):
qs = super(AnudanPersonalAdmin, self).get_queryset(request)
if request.user.is_superuser:
return qs
return qs.filter(municipality=request.user.municipality_staff.municipality)
def get_form(self, request,*args, **kwargs):
form = AnudanPersonalForm
form.current_user=request.user
return form
def get_readonly_fields(self, request, obj=None):
if obj:
if request.user.is_superuser or request.user.is_admin:
return self.readonly_fields
else:
return self.readonly_fields+('approval',) # editing an existing object
if request.user.is_superuser or request.user.is_admin:
return self.readonly_fields
else:
return self.readonly_fields+('approval',)
def get_fieldsets(self, request, obj):
if obj:
return self.fieldsets
return self.add_fieldsets if request.user.is_superuser else self.staff_fieldsets
def get_list_filter(self, request):
if not request.user.is_superuser:
return self.list_filter
return ['municipality'] + self.list_filter
@admin.register(AnudanCompany)
class AnudanCompanyAdmin(admin.ModelAdmin):
list_display=['firm_name','registration_no','pan_no','vat_no','ward','tole','registered_place','municipality','approval']
list_display_links=['firm_name','registration_no','pan_no','vat_no']
list_filter=['fiscal_year','karyakram','ward','approval',]
actions=[approve,disapprove,'export_to_csv','render_pdf_view']
form = AnudanCompanyForm
fieldsets = (
(_('Fiscal Year'),{'fields':('fiscal_year',)}),
(_('Nagar Palika'), {'fields': ('municipality',),'classes':("wide",),'description':_('Select Municipality')}),
(_('Firm info'), {'fields': ( 'firm_name','contact_number','pan_no','vat_no','registration_no','registered_place','firm_registration_proof','anya_darta'),'classes':("wide",),'description':_('About Firm')}),
(_('Address'), {'fields': ('ward', 'tole',),'classes':("wide",),'description':_('Enter Your Address')}),
(_('Anudan Request'),{'fields':('sector','karyakram','ward_sifaris','prastavan'),'classes':("wide",),'description':_('Select Karyakram')}),
(_('Approval'),{'fields':('approval',),'classes':("wide",),'description':'Test'})
)
add_fieldsets = (
(_('Fiscal Year'),{'fields':('fiscal_year',)}),
(_('Nagar Palika'), {'fields': ('municipality',),'classes':("wide",),'description':_('Select Municipality')}),
(_('Firm info'), {'fields': ( 'firm_name','contact_number','pan_no','vat_no','registration_no','registered_place','firm_registration_proof','anya_darta'),'classes':("wide",),'description':_('About Firm')}),
(_('Address'), {'fields': ('ward', 'tole',),'classes':("wide",),'description':_('Enter Your Address')}),
(_('Anudan Request'),{'fields':('sector','karyakram','ward_sifaris','prastavan'),'classes':("wide",),'description':_('Select Karyakram')}),
)
staff_fieldsets = (
(_('Nagar Palika'), {'fields': ('municipality',),'classes':("collapse",),'description':_('Select Municipality')}),
(_('Fiscal Year'),{'fields':('fiscal_year',)}),
(_('Firm info'), {'fields': ( 'firm_name','contact_number','pan_no','vat_no','registration_no','registered_place','firm_registration_proof','anya_darta'),'classes':("wide",),'description':_('About Firm')}),
(_('Address'), {'fields': ('ward', 'tole',),'classes':("wide",),'description':_('Enter Your Address')}),
(_('Anudan Request'),{'fields':('sector','karyakram','ward_sifaris','prastavan'),'classes':("wide",),'description':_('Select Karyakram')}),
)
def get_queryset(self, request):
qs = super(AnudanCompanyAdmin, self).get_queryset(request)
if request.user.is_superuser:
return qs
return qs.filter(municipality=request.user.municipality_staff.municipality)
def get_form(self, request,*args, **kwargs):
form = super(AnudanCompanyAdmin,self).get_form(request,*args, **kwargs)
form.current_user=request.user
return form
def get_list_filter(self, request):
if request.user.is_superuser:
return self.list_filter
return ['municipality'] + self.list_filter
def get_readonly_fields(self, request, obj=None):
if obj:
if request.user.is_superuser or request.user.is_admin:
return self.readonly_fields
else:
return self.readonly_fields+('approval',) # editing an existing object
if request.user.is_superuser or request.user.is_admin:
return self.readonly_fields
else:
return self.readonly_fields+('approval',)
def get_fieldsets(self, request, obj):
if obj:
return self.fieldsets
return self.staff_fieldsets if not request.user.is_superuser else self.add_fieldsets
@admin.action(description='Export to csv')
def export_to_csv(self, request, queryset):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = f'attachment; filename="AnudanCompany.csv"'
writer = csv.writer(response)
if '/ne/' in request.path:
writer.writerow(['नाम','नगरपालिका','टोल','वडा','कार्यक्रम','वडा सिफरिस','प्रस्तावना','स्वीकृति'])
else:
writer.writerow(['Name','Municipality','Ward','Tole','Karyakram','Ward Sifaris','Prastavan','Approval'])
books = queryset.values_list('firm_name','municipality__name','ward__name','tole','karyakram__name','ward_sifaris', 'prastavan','approval')
for book in books:
writer.writerow(book)
return response
@admin.action(description='Export to pdf')
def render_pdf_view(self,request,queryset):
template_path = 'AnudanCompany.html'
context = {'queryset': queryset}
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="AnudanCompany.pdf"'
template = get_template(template_path)
html = template.render(context)
pisa_status = pisa.CreatePDF(html, dest=response)
if pisa_status.err:
return HttpResponse('We had some errors <pre>' + html + '</pre>')
return response
|
{"/anudaan/serializers.py": ["/anudaan/models.py"], "/anudaan/views.py": ["/anudaan/models.py", "/anudaan/serializers.py"], "/Accounts/views.py": ["/Accounts/models.py", "/Accounts/forms.py"], "/Accounts/admin.py": ["/Accounts/models.py", "/Accounts/forms.py", "/Municipality/models.py"], "/anudaan/migrations/0001_initial.py": ["/anudaan/models.py"], "/Accounts/models.py": ["/anudaan/models.py", "/Municipality/models.py"], "/Accounts/forms.py": ["/Accounts/models.py", "/Anudan/models.py"], "/anudaan/admin.py": ["/anudaan/models.py"], "/Municipality/admin.py": ["/Accounts/models.py", "/Municipality/models.py"], "/Anudan/forms.py": ["/Anudan/models.py", "/Accounts/models.py", "/Municipality/models.py"], "/Anudan/migrations/0001_initial.py": ["/Anudan/models.py"], "/Anudan/admin.py": ["/Municipality/models.py", "/Anudan/models.py", "/Anudan/forms.py"], "/Anudan/models.py": ["/Municipality/models.py"], "/AnudaanProject/urls.py": ["/Accounts/views.py"]}
|
14,980,646
|
Sujeet9271/AnudanProject
|
refs/heads/main
|
/Accounts/views.py
|
from django.conf import settings
from django.shortcuts import render,redirect
from django.contrib.auth.forms import AuthenticationForm
from django.contrib import messages
from django.contrib.auth import authenticate,login
import random
from django.core.mail import EmailMessage
import threading
from django.utils.translation import gettext as _
class EmailThread(threading.Thread):
def __init__(self,email):
self.email = email
threading.Thread.__init__(self)
def run(self):
self.email.send()
def send(email,otp):
subject = 'Login OTP'
otp = otp
message = f'Here is the login otp for anudan project {otp}.'
email = EmailMessage(subject=subject ,body=message, from_email='sujeet9271@gmail.com',to=[email])
EmailThread(email).start()
def generate_otp(request):
if request.method == 'POST':
form = AuthenticationForm(request.POST)
email = request.POST['username']
password = request.POST['password']
user = authenticate(email=email,password=password)
if user:
if user.is_active:
request.session['username'] = email
request.session['password'] = password
otp = random.randint(100000,999999)
request.session['otp'] = otp
login(request,user)
# send(email=user.email,otp=otp)
# messages.success(request,_('An OTP is sent to the registered email.'))
# login(request,user)
return redirect('admin:index')
else:
messages.error(request,_('username or password not correct'))
return redirect('admin:login')
else:
form = AuthenticationForm()
return render(request,'admin/login.html',{'form':form})
def otp(request):
if request.method=='POST':
otp = request.session['otp']
otp_post = int(request.POST['otp'])
if otp==otp_post:
email = request.session['username']
password = request.session['password']
user = authenticate(email=email,password=password)
login(request,user)
request.session.delete('otp')
return redirect('admin:index')
else:
email = request.session['username']
password = request.session['password']
user = authenticate(email=email,password=password)
otp = random.randint(100000,999999)
request.session['otp'] = otp
send(email=user.email,otp=otp)
messages.error(request,_('Invalid OTP, Check your email for new otp'))
return render(request,'admin/otp.html')
|
{"/anudaan/serializers.py": ["/anudaan/models.py"], "/anudaan/views.py": ["/anudaan/models.py", "/anudaan/serializers.py"], "/Accounts/views.py": ["/Accounts/models.py", "/Accounts/forms.py"], "/Accounts/admin.py": ["/Accounts/models.py", "/Accounts/forms.py", "/Municipality/models.py"], "/anudaan/migrations/0001_initial.py": ["/anudaan/models.py"], "/Accounts/models.py": ["/anudaan/models.py", "/Municipality/models.py"], "/Accounts/forms.py": ["/Accounts/models.py", "/Anudan/models.py"], "/anudaan/admin.py": ["/anudaan/models.py"], "/Municipality/admin.py": ["/Accounts/models.py", "/Municipality/models.py"], "/Anudan/forms.py": ["/Anudan/models.py", "/Accounts/models.py", "/Municipality/models.py"], "/Anudan/migrations/0001_initial.py": ["/Anudan/models.py"], "/Anudan/admin.py": ["/Municipality/models.py", "/Anudan/models.py", "/Anudan/forms.py"], "/Anudan/models.py": ["/Municipality/models.py"], "/AnudaanProject/urls.py": ["/Accounts/views.py"]}
|
14,980,647
|
Sujeet9271/AnudanProject
|
refs/heads/main
|
/Accounts/forms.py
|
from django.contrib.auth.forms import UserCreationForm,UserChangeForm
from django import forms
from django.forms import fields
from .models import FiscalYear, MunicipalityStaff, PalikaUser, Profile
from Anudan.models import Municipality
from django.utils.translation import gettext as _
class LoginForm(forms.ModelForm):
email = forms.CharField(widget=forms.TextInput)
password = forms.CharField(widget=forms.PasswordInput())
class Meta:
fields = ['email', 'password']
class OTP(forms.Form):
otp = forms.IntegerField()
class Meta:
fields = ['otp']
class CustomUserCreationForm(UserCreationForm):
email = forms.EmailField(label=_('email'))
class Meta:
model = PalikaUser
fields = ("email","username","password1","password2",)
def save(self,commit = True):
user = super(CustomUserCreationForm,self).save(commit=False)
user.is_staff = True
if commit:
user.save()
return user
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = PalikaUser
fields = ('email','username','first_name','last_name',)
class PalikaStaffForm(forms.ModelForm):
municipality = forms.ModelChoiceField(queryset=Municipality.objects.none())
user = forms.ModelChoiceField(PalikaUser.objects.none())
def __init__(self,*args,**kwargs):
super(PalikaStaffForm,self).__init__(*args,**kwargs)
self.fields['municipality'].queryset = Municipality.objects.all().filter(id=self.current_user.municipality_staff.municipality.id) if not self.current_user.is_superuser else Municipality.objects.all()
self.fields['municipality'].initial = Municipality.objects.get(id = self.current_user.municipality_staff.municipality.id) if not self.current_user.is_superuser else None
self.fields['user'].queryset = PalikaUser.objects.all() if self.current_user.is_superuser else PalikaUser.objects.all().filter(municipality_staff__municipality=self.current_user.municipality_staff.municipality)
class Meta:
model = MunicipalityStaff
fields = ['municipality','user']
class ProfileForm(forms.ModelForm):
user = forms.ModelChoiceField(queryset=PalikaUser.objects.none())
address = forms.CharField()
contact_number = forms.IntegerField()
def __init__(self,*args,**kwargs):
super(ProfileForm,self).__init__(*args,**kwargs)
self.fields['user'].queryset = PalikaUser.objects.all().filter(id=self.current_user.id) if not self.current_user.is_superuser else PalikaUser.objects.all()
class Meta:
model = Profile
fields = ['user','address','contact_number']
class FiscalYearForm(forms.ModelForm):
start_date = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}))
end_date = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}))
class Meta:
model = FiscalYear
fields = ['start_date','end_date']
|
{"/anudaan/serializers.py": ["/anudaan/models.py"], "/anudaan/views.py": ["/anudaan/models.py", "/anudaan/serializers.py"], "/Accounts/views.py": ["/Accounts/models.py", "/Accounts/forms.py"], "/Accounts/admin.py": ["/Accounts/models.py", "/Accounts/forms.py", "/Municipality/models.py"], "/anudaan/migrations/0001_initial.py": ["/anudaan/models.py"], "/Accounts/models.py": ["/anudaan/models.py", "/Municipality/models.py"], "/Accounts/forms.py": ["/Accounts/models.py", "/Anudan/models.py"], "/anudaan/admin.py": ["/anudaan/models.py"], "/Municipality/admin.py": ["/Accounts/models.py", "/Municipality/models.py"], "/Anudan/forms.py": ["/Anudan/models.py", "/Accounts/models.py", "/Municipality/models.py"], "/Anudan/migrations/0001_initial.py": ["/Anudan/models.py"], "/Anudan/admin.py": ["/Municipality/models.py", "/Anudan/models.py", "/Anudan/forms.py"], "/Anudan/models.py": ["/Municipality/models.py"], "/AnudaanProject/urls.py": ["/Accounts/views.py"]}
|
14,980,648
|
Sujeet9271/AnudanProject
|
refs/heads/main
|
/Anudan/models.py
|
from django.db import models
from smart_selects.db_fields import ChainedForeignKey
from django.utils.translation import gettext_lazy as _
from Municipality.models import Municipality, Sector, Ward
class Karyakram(models.Model):
municipality = models.ForeignKey(Municipality,on_delete=models.PROTECT,verbose_name=_('Municipality'))
sector = ChainedForeignKey(Sector,chained_field="municipality",
chained_model_field="municipality",
on_delete=models.PROTECT,
auto_choose=True,
verbose_name=_('Sector'))
name = models.CharField(verbose_name=_('Name'),max_length=255)
created = models.DateTimeField(verbose_name=_('created'),auto_now_add=True)
def __str__(self):
return f'{self.name}-{self.municipality.name}'
class Meta:
db_table='Karyakram'
verbose_name= _('Karyakram')
verbose_name_plural = _('Karyakram')
class Unit(models.Model):
name = models.CharField(max_length=50,verbose_name=_('Name'))
def __str__(self):
return f'{self.name}'
class Meta:
db_table='Unit'
verbose_name = _('Unit')
verbose_name_plural = _('Units')
class Samagri(models.Model):
karyakram = ChainedForeignKey(Karyakram,
chained_field="municipality",
chained_model_field="municipality",
on_delete=models.PROTECT,
auto_choose=True,
verbose_name=_('Karyakram')
)
name = models.CharField(verbose_name=_('Name'),max_length=255,)
quantity = models.IntegerField(default=1,verbose_name=_('Quantity'))
unit = models.ForeignKey(Unit,verbose_name=_('Units'),null=True,on_delete=models.SET_NULL)
def __str__(self):
return f'{self.name}'
def karyakram_name(self):
return self.karyakram.name
karyakram_name.short_description = _('Karyakram')
class Meta:
db_table='Samagri'
ordering = ['karyakram']
verbose_name = _('Samagri')
verbose_name_plural = _('Samagri')
# Storing file for personal Anudan
def personal_location(instance, filename):
return f"{instance.municipality.name}/Personal/{instance.name}/{filename}"
# Storing file for Company Anudan
def company_location(instance, filename):
return f"{instance.municipality.name}/Company/{instance.firm_name}/{filename}"
class AnudanPersonal(models.Model):
fiscal_year = models.ForeignKey(to='Accounts.FiscalYear',verbose_name=_('Fiscal Year'),on_delete = models.PROTECT,)
municipality = models.ForeignKey(Municipality, on_delete=models.PROTECT,verbose_name=_('Municipality'))
choices_approval = (
('Approved', _('Approved')),
('Not Approved', _('Not Approved'))
)
name = models.CharField(max_length=255,verbose_name=_('Name'))
ward = ChainedForeignKey(Ward,chained_field="municipality",
chained_model_field="municipality",
on_delete=models.PROTECT,
auto_choose=True,
verbose_name=_('Ward'))
tole = models.CharField(verbose_name=_('Tole'),max_length=150)
nagrikta_number = models.CharField(verbose_name=_('Nagrikta Number'),max_length=20)
nagrikta_front = models.ImageField(upload_to=personal_location, verbose_name=_('Nagrikta Front Photo'))
nagrikta_back = models.ImageField(upload_to=personal_location, verbose_name=_('Nagrikta Back Photo'),blank = True)
jari_jilla = models.CharField(max_length=20, verbose_name=_('Jaari Jilla'))
contact_number = models.CharField(verbose_name=_('Contact Number'),max_length=20)
sector = ChainedForeignKey(Sector,chained_field="municipality",
chained_model_field="municipality",
on_delete=models.PROTECT,
auto_choose=True,
verbose_name=_('Sector'))
karyakram = ChainedForeignKey(Karyakram,
chained_field="sector",
chained_model_field="sector",
on_delete=models.PROTECT,
auto_choose=True,
verbose_name=_('Karyakram'))
samagri = ChainedForeignKey(Samagri,
chained_field="karyakram",
chained_model_field="karyakram",
auto_choose=True,
on_delete=models.PROTECT,
verbose_name=_('Samagri')
)
quantity = models.PositiveSmallIntegerField(default=1)
approval = models.CharField(choices=choices_approval, default='Not Approved', max_length=14,verbose_name=_('Approval'))
created = models.DateField(verbose_name=_('created'),auto_now_add=True,auto_now=False)
updated = models.DateField(verbose_name=_('updated'),auto_now=True)
def __str__(self):
return f'{self.name}-{self.karyakram}-{self.samagri}-{self.approval}'
class Meta:
db_table='Anudan_Personal'
verbose_name = _('Anudan Personal')
verbose_name_plural = _('Anudan Personal')
class AnudanCompany(models.Model):
fiscal_year = models.ForeignKey(to='Accounts.FiscalYear',verbose_name=_('Fiscal Year'),on_delete = models.PROTECT)
municipality = models.ForeignKey(Municipality, on_delete=models.PROTECT,verbose_name=_('Municipality'))
choices_approval = (
('Approved', _('Approved')),
('Not Approved', _('Not Approved'))
)
firm_name = models.CharField(max_length=255,verbose_name=_('Firm name'))
contact_number = models.CharField(verbose_name=_('Contact Number'),max_length=20,default=0)
pan_no = models.CharField(verbose_name=_('PAN no'),null=True,blank=True,max_length=20)
vat_no = models.CharField(verbose_name=_('VAT no'),null=True,blank=True,max_length=20)
registration_no = models.CharField(verbose_name=_('Registration Number'),null=True,blank=True,max_length=20)
ward = ChainedForeignKey(Ward,chained_field="municipality",
chained_model_field="municipality",
on_delete=models.PROTECT,
auto_choose=True,
verbose_name=_('Ward'))
tole = models.CharField(verbose_name=_('Tole'),max_length=150)
registered_place = models.CharField(max_length=20, verbose_name=_('Jaari Jilla'))
choices_darta = (
('Gharelu',_('Gharelu')),
('Banijya',_('Banijya'))
)
anya_darta = models.CharField(choices=choices_darta,max_length=50,blank=True,null=True,verbose_name=_('Registered as'))
firm_registration_proof = models.ImageField(upload_to=company_location, verbose_name=_('Firm Registration Proof'))
sector = ChainedForeignKey(Sector,chained_field="municipality",
chained_model_field="municipality",
on_delete=models.PROTECT,
auto_choose=True,
verbose_name=_('Sector'))
karyakram = ChainedForeignKey(Karyakram,
chained_field="sector",
chained_model_field="sector",
on_delete=models.PROTECT,
auto_choose=True,
verbose_name=_('Karyakram'))
ward_sifaris = models.ImageField(upload_to=company_location, verbose_name=_('Ward Sifaris'))
prastavan = models.ImageField(upload_to=company_location, verbose_name=_('Upload Prastavan'))
approval = models.CharField(choices=choices_approval, default='Not Approved', max_length=14,verbose_name=_('Approval'))
created = models.DateField(verbose_name=_('created'),auto_now_add=True,auto_now=False)
updated = models.DateField(verbose_name=_('updated'),auto_now=True)
def __str__(self):
return f'{self.firm_name}-{self.registration_no}-{self.approval}'
class Meta:
db_table='Anudan_Company'
verbose_name = _('Anudan Company')
verbose_name_plural = _('Anudan Company')
class Medicine(models.Model):
name=models.CharField(verbose_name=_('Name'),max_length=150)
def __str__(self):
return f'{self.name}'
class Meta:
db_table = 'Medicine'
verbose_name=_('Medicine')
verbose_name_plural = _('Medicines')
class MedicineRequest(models.Model):
municipality = models.ForeignKey(Municipality,on_delete=models.DO_NOTHING,verbose_name=_('Municipality'))
name = models.CharField(verbose_name=_('Name'),max_length=150)
contact_number = models.CharField(verbose_name=_('Contact Number'),max_length=10)
ward = ChainedForeignKey(Ward,chained_field="municipality",
chained_model_field="municipality",
on_delete=models.PROTECT,
auto_choose=True,
verbose_name=_('Ward'))
tole = models.CharField(verbose_name=_('Tole'),max_length=150)
created = models.DateField(verbose_name=_('created'),auto_now_add=True,auto_now=False)
def __str__(self):
return f'{self.ward}-{self.tole}-{self.name}'
class Meta:
db_table = 'Medicine_Request'
verbose_name =_('Medicine Request')
verbose_name_plural = _('Medicine Request')
class MedicineRequested(models.Model):
requested_by = models.ForeignKey(MedicineRequest,on_delete=models.CASCADE,verbose_name=_('Requested By'),related_name='Medicines_Requested')
medicine = models.ForeignKey(Medicine,verbose_name=_('Medicine'),max_length=150,related_name='Medicines_Requested',on_delete=models.CASCADE)
quantity = models.PositiveSmallIntegerField(_('Quantity'),default=1)
def __str__(self):
return f'{self.medicine.name} requested by {self.requested_by.name} from {self.requested_by.tole} of {self.requested_by.municipality.name}'
|
{"/anudaan/serializers.py": ["/anudaan/models.py"], "/anudaan/views.py": ["/anudaan/models.py", "/anudaan/serializers.py"], "/Accounts/views.py": ["/Accounts/models.py", "/Accounts/forms.py"], "/Accounts/admin.py": ["/Accounts/models.py", "/Accounts/forms.py", "/Municipality/models.py"], "/anudaan/migrations/0001_initial.py": ["/anudaan/models.py"], "/Accounts/models.py": ["/anudaan/models.py", "/Municipality/models.py"], "/Accounts/forms.py": ["/Accounts/models.py", "/Anudan/models.py"], "/anudaan/admin.py": ["/anudaan/models.py"], "/Municipality/admin.py": ["/Accounts/models.py", "/Municipality/models.py"], "/Anudan/forms.py": ["/Anudan/models.py", "/Accounts/models.py", "/Municipality/models.py"], "/Anudan/migrations/0001_initial.py": ["/Anudan/models.py"], "/Anudan/admin.py": ["/Municipality/models.py", "/Anudan/models.py", "/Anudan/forms.py"], "/Anudan/models.py": ["/Municipality/models.py"], "/AnudaanProject/urls.py": ["/Accounts/views.py"]}
|
14,980,649
|
Sujeet9271/AnudanProject
|
refs/heads/main
|
/AnudaanProject/urls.py
|
from django.conf.urls import i18n,static
from django.contrib import admin
from django.urls import path,include
from django.shortcuts import redirect
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from Accounts.views import generate_otp,otp
def switch_lang_code(path, language):
# Get the supported language codes
lang_codes = [c for (c, name) in settings.LANGUAGES]
# Validate the inputs
if path == '':
raise Exception('URL path for language switch is empty')
elif path[0] != '/':
raise Exception('URL path for language switch does not start with "/"')
elif language not in lang_codes:
raise Exception('%s is not a supported language code' % language)
# Split the parts of the path
parts = path.split('/')
# Add or substitute the new language prefix
if parts[1] in lang_codes:
parts[1] = language
else:
parts[0] = "/" + language
# Return the full new path
return '/'.join(parts)
def index(request):
return redirect('admin/')
urlpatterns = i18n.i18n_patterns(
path('admin/login/',generate_otp, name='admin:login'),
path('admin/login/otp/',otp, name='otp'),
path('admin/', admin.site.urls),
path('chaining/', include('smart_selects.urls')),
prefix_default_language=False
)+static.static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
admin.site.site_header=_('Anudan Project')
admin.site.site_url =''
admin.site.index_title=_('Home')
admin.site.site_title=_('Anudan Project')
|
{"/anudaan/serializers.py": ["/anudaan/models.py"], "/anudaan/views.py": ["/anudaan/models.py", "/anudaan/serializers.py"], "/Accounts/views.py": ["/Accounts/models.py", "/Accounts/forms.py"], "/Accounts/admin.py": ["/Accounts/models.py", "/Accounts/forms.py", "/Municipality/models.py"], "/anudaan/migrations/0001_initial.py": ["/anudaan/models.py"], "/Accounts/models.py": ["/anudaan/models.py", "/Municipality/models.py"], "/Accounts/forms.py": ["/Accounts/models.py", "/Anudan/models.py"], "/anudaan/admin.py": ["/anudaan/models.py"], "/Municipality/admin.py": ["/Accounts/models.py", "/Municipality/models.py"], "/Anudan/forms.py": ["/Anudan/models.py", "/Accounts/models.py", "/Municipality/models.py"], "/Anudan/migrations/0001_initial.py": ["/Anudan/models.py"], "/Anudan/admin.py": ["/Municipality/models.py", "/Anudan/models.py", "/Anudan/forms.py"], "/Anudan/models.py": ["/Municipality/models.py"], "/AnudaanProject/urls.py": ["/Accounts/views.py"]}
|
15,031,620
|
li-jonathan/wearable-computing-toolkit
|
refs/heads/master
|
/mbient_data_file.py
|
import pandas as pd
import os
import sys
import argparse
"""
MBientDataFile class
Written by Dr. Forsyth.
"""
#### Begin MBientDataFile Class ####
class MBientDataFile:
filePath=None
sensorType=None
sampleRate=None
sensorName=None
captureDateTime=None
MAC=None
startTime=None
_epoch_column_label='epoc (ms)'
def _calc_sample_rate_and_start_time(self):
# read the first 10 rows so we can get the sample rate
# TODO: make this not hard coded. Will error is file is less than numRows
numRows = 100
data = pd.read_csv(self.filePath, nrows=numRows)
times = data[self._epoch_column_label]
deltas = times.diff()
# average period between samples in milliseconds
totalPeriod = deltas.sum(skipna=True) / (numRows - 1)
self.sampleRate = 1 / (totalPeriod / 1000)
self.startTime=times.get(0)
def __init__(self,file_path):
self.filePath=file_path
(head,tail)=os.path.split(file_path)
splits = tail.split("_")
self.sensorName=splits[0]
self.captureDateTime=splits[1]
self.MAC=splits[2]
self.sensorType=splits[3].split(".")[0]
self._calc_sample_rate_and_start_time()
def generate_data_frame(self):
df = pd.read_csv(self.filePath)
# delete UTC timestamp column
if 'timestamp (-0400)' in df.columns:
del df['timestamp (-0400)']
if 'timestamp (-0500)' in df.columns:
del df['timestamp (-0500)']
del df['elapsed (s)'] # delete elapse column
# rename data columns to append sensor name
if self.sensorType=='Gyroscope':
df=df.rename(columns={'x-axis (deg/s)': str(self.sensorName+"_Gx")})
df=df.rename(columns={'y-axis (deg/s)': str(self.sensorName + "_Gy")})
df=df.rename(columns={'z-axis (deg/s)': str(self.sensorName + "_Gz")})
elif self.sensorType=='Accelerometer':
df=df.rename(columns={'x-axis (g)': str(self.sensorName + "_Ax")})
df=df.rename(columns={'y-axis (g)': str(self.sensorName + "_Ay")})
df=df.rename(columns={'z-axis (g)': str(self.sensorName + "_Az")})
return df
|
{"/app.py": ["/combine_files.py", "/label_datasets.py"], "/combine_files.py": ["/mbient_data_file.py"]}
|
15,031,621
|
li-jonathan/wearable-computing-toolkit
|
refs/heads/master
|
/combine_files.py
|
import pandas as pd
import os
import sys
from mbient_data_file import MBientDataFile
#from toolkit.mbient_data_file import MBientDataFile
"""
CombineFiles
Written by Dr. Forsyth, modified for Wearable Toolkit.
"""
class CombineFiles():
def __init__(self, source, destination):
"""Constructor."""
self.src_folder = source
self.dest_folder = destination
self.log = []
def make_paths_absolute(self):
"""Math paths absolute."""
self.log.append("Making paths absolute...")
if os.path.isabs(self.src_folder) != True:
self.src_folder = os.path.abspath(self.src_folder)
if os.path.isabs(self.dest_folder) != True:
self.dest_folder = os.path.abspath(self.dest_folder)
def validate_folders(self):
"""Determine if source and destination folders are valid folders."""
self.log.append("Validating folders...")
if os.path.isdir(self.src_folder)==False:
self.log.append('Source folder '+self.src_folder+' cannot be found!\nExiting...')
sys.exit(0)
if os.path.isdir(self.dest_folder)==False:
self.log.append('Destination folder' +self.dest_folder+' cannot be found!\nExiting...')
sys.exit(0)
def main(self):
"""Main."""
source = self.src_folder
dest = self.dest_folder
# get all the files out of the src/ folder
input_file_path = source + '/' #this line may no longer be necessary
files = os.listdir(input_file_path)
mbient_files = list()
for file in files:
if "Accelerometer" or "Gyroscope" in file:
dataFile= MBientDataFile(input_file_path+file)
mbient_files.append(dataFile)
# basic sanity checking. See if all have same sample right and
# if they start are "roughly" the same time
# Check #0 Did we get any files?!
if len(mbient_files) == 0:
self.log.append('No files in source directory. Exiting.')
return
# Check #1: See if files are all the same sample right
initRate = mbient_files[0].sampleRate
for i in range(1,len(mbient_files)):
#TODO: come up with a better method than this. 2Hz sampling error may a lot...
if abs(initRate - mbient_files[i].sampleRate)>2:
self.log.append("[IGNORE] Error! All files are not the same sample rate!")
# return
# Check #2: See if they all start at the "same" time
startTimes = list()
for file in mbient_files:
startTimes.append(file.startTime)
minimum = min(startTimes)
maximum = max(startTimes)
delta = abs(minimum - maximum)
synchronize=False
if delta>1000:
self.log.append("Files have different start times. Synchronizing....")
synchronize=True
# generate dataframes from each file. Concat into single file and
# if needed to synchronize follow https://mbientlab.com/tutorials/Apps.html#synchronizing-multiple-datasets-in-python
# perform left merge based upon the "oldest" file
# find the youngest file and make it "left"
# (this will be the file with the oldest starting timestamp)
def sortMethod(mbientFile):
return mbientFile.startTime
mbient_files=sorted(mbient_files,key=sortMethod,reverse=True)
left = mbient_files[0].generate_data_frame()
for i in range(1,len(mbient_files)):
right = mbient_files[i].generate_data_frame()
#merge from right to left on 'epoc' column. Nearest match with 5ms tolerance
left = pd.merge_asof(left,right,on='epoc (ms)',direction='nearest',tolerance=5)
# all files are now merged into the "left" file
dest_file_path = dest + '/merged.csv'
# don't print out index and truncate floats to three decimal places (which is the largest provided by input/source)
left.to_csv(dest_file_path,index=False,float_format="%.3f")
self.log.append("Successfully merged files in " + dest_file_path)
def run(self):
"""Run functions."""
self.make_paths_absolute()
self.validate_folders()
self.main()
|
{"/app.py": ["/combine_files.py", "/label_datasets.py"], "/combine_files.py": ["/mbient_data_file.py"]}
|
15,031,622
|
li-jonathan/wearable-computing-toolkit
|
refs/heads/master
|
/app.py
|
import os
import tkinter as tk
from tkinter import *
from tkinter import filedialog
from tkinter import scrolledtext
from combine_files import CombineFiles
from label_datasets import LabelDatasets
# from toolkit.combine_files import CombineFiles
# from toolkit.label_datasets import LabelDatasets
"""
Main application for Wearable Computing Toolkit
Combines multiple data stream csv files into one.
Input list of activities to use when labeling previously created file.
Usage: python app.py
"""
class App(tk.Frame):
def __init__(self, master=None):
"""Constructor."""
super().__init__(master)
self.master = master
self.master.protocol("WM_DELETE_WINDOW", self.close_window)
self.cf_frame = Frame(master, bg="white") # combine files frame
self.ld_frame = Frame(master, bg="white") # label datasets frame
self.init_app()
self.create_combine_files_widgets()
self.create_label_datasets_widgets()
def close_window(self):
"""Close window."""
self.master.quit()
self.master.destroy()
def init_app(self):
"""Initialize app settings and variables."""
self.master.title("Combine Files & Label Datasets")
self.master.config(background = "white")
self.master.minsize(930, 300)
self.src_dir = None # source directory
self.dest_dir = None # destination directory
self.merged_file = None # merged csv filename
self.activities = None # list of activites as string
def create_combine_files_widgets(self):
"""Widgets to combine files from source directory into destination directory."""
self.cf_frame.pack(side="left", padx=10, pady=10)
title_label = tk.Label(self.cf_frame, bg="white", text="Merge and align data streams", font=("Arial 18 bold"))
title_label.grid(row=0, column=0, columnspan=3, padx=5, pady=5)
### ===== BROWSE SOURCE DIRECTORY ===== ###
# choose source directory
src_dir_prompt = tk.Label(self.cf_frame, text="Choose source directory", bg="white")
src_dir_prompt.grid(row=1, column=0, padx=5, pady=5, sticky=W)
# browse source directory
browse_src_btn = tk.Button(self.cf_frame, text="Browse...", command=self.browse_src_dir)
browse_src_btn.grid(row=1, column=1, padx=5, pady=5)
# display selected source directory
self.src_dir_lbl = tk.Label(self.cf_frame, bg="white")
self.src_dir_lbl.grid(row=1, column=2, padx=5, pady=5)
### ===== BROWSE DESTINATION DIRECTORY ===== ###
# choose destination directory
dest_dir_prompt = tk.Label(self.cf_frame, text="Choose destination directory", bg="white")
dest_dir_prompt.grid(row=2, column=0, padx=5, pady=5, sticky=W)
# browse destination directory
browse_dest_btn = tk.Button(self.cf_frame, text="Browse...", command=self.browse_dest_dir)
browse_dest_btn.grid(row=2, column=1, padx=5, pady=5)
# display selected destination directory
self.dest_dir_lbl = tk.Label(self.cf_frame, bg="white")
self.dest_dir_lbl.grid(row=2, column=2, padx=5, pady=5)
### ===== COMBINE FILES ===== ###
combine_files_btn = tk.Button(self.cf_frame, text="Combine files", command=self.combine_files)
combine_files_btn.grid(row=3, column=0, columnspan=3, padx=5, pady=5)
# log for combining files pipeline
self.combine_files_log = scrolledtext.ScrolledText(self.cf_frame, wrap = tk.WORD, bg="white", width=50, height=5)
self.combine_files_log.grid(row=4, column=0, columnspan=3, padx=5, pady=5)
def browse_src_dir(self):
"""Browse for source directory."""
# TODO: allow for browsing into subdirectories (ex: "src/short")
selected_dir = filedialog.askdirectory(parent=root, initialdir=os.getcwd(), title='Please select the source directory')
self.src_dir = selected_dir[selected_dir.rfind('/')+1:] + "/"
self.src_dir_lbl["text"] = self.src_dir
def browse_dest_dir(self):
"""Browse for destination directory."""
# TODO: allow for browsing into subdirectories (ex: "dest/long")
selected_dir = filedialog.askdirectory(parent=root, initialdir=os.getcwd(), title='Please select the destination directory')
self.dest_dir = selected_dir[selected_dir.rfind('/')+1:] + "/"
self.dest_dir_lbl["text"] = self.dest_dir
def combine_files(self):
"""Combine files using src and dest."""
cf = CombineFiles(self.src_dir, self.dest_dir)
cf.run()
# show log for combining files
for l in cf.log:
self.combine_files_log.insert(tk.END, l + "\n")
self.combine_files_log.config(state=DISABLED) # disable editing log box
def create_label_datasets_widgets(self):
"""Widgets to label datasets with activities"""
self.ld_frame.pack(side="right", padx=10, pady=10)
title_label = tk.Label(self.ld_frame, bg="white", text="Label datasets with activity names", font=("Arial 18 bold"))
title_label.grid(row=0, column=0, columnspan=3, pady=5)
### ===== BROWSE FOR MERGED FILE ===== ###
# browse merged file
merged_file_bf_btn = tk.Button(self.ld_frame, text="Browse for merged file", command=self.browse_merged_file)
merged_file_bf_btn.grid(row=1, column=0, columnspan=3, padx=5, pady=5)
# display selected merged csv file
self.merged_file_lbl = tk.Label(self.ld_frame, bg="white")
self.merged_file_lbl.grid(row=2, column=0, columnspan=3, padx=5, pady=5)
### ===== LIST ALL ACTIVITIES ===== ###
activities_lbl = tk.Label(self.ld_frame, text="List activities (comma separated)", bg="white")
activities_lbl.grid(row=3, column=0, columnspan=3, padx=5, pady=5)
# list of activities
self.activities_list = tk.Text(self.ld_frame, bg="white", width=50, height=4)
self.activities_list.grid(row=4, column=0, columnspan=3, padx=5, pady=5)
# label datasets
lbl_datasets_btn = tk.Button(self.ld_frame, text="Label datasets", command=self.label_datasets)
lbl_datasets_btn.grid(row=5, column=0, columnspan=3, padx=5, pady=5)
def browse_merged_file(self):
"""Browse for merged file."""
# TODO: allow for browsing into subdirectories
selected_file = filedialog.askopenfilename(parent=root, initialdir=os.getcwd(), title='Please select the merged file')
self.merged_file = selected_file[selected_file.rfind("/", 0, selected_file.rfind("/"))+1:]
self.merged_file_lbl["text"] = self.merged_file
def label_datasets(self):
"""Label datasets."""
self.activities = self.activities_list.get("1.0",END) # get comma list of activities
print(len(self.activities))
# check for activities
if len(self.activities) == 0:
messagebox.showinfo("Error", "No activities entered.")
# call label datasets gui
ld = LabelDatasets(self.merged_file, self.activities)
ld.run()
# clear the text box if there are activities
if len(self.activities) > 1:
self.activities_list.delete(0, 'end')
if __name__ == '__main__':
root = tk.Tk()
app = App(master=root)
app.mainloop()
|
{"/app.py": ["/combine_files.py", "/label_datasets.py"], "/combine_files.py": ["/mbient_data_file.py"]}
|
15,076,243
|
szutu/Portal
|
refs/heads/master
|
/portal.py
|
from flask import Flask, render_template, request, redirect, url_for, flash
import database
app = Flask(__name__)
app.config.update(dict(
SECRET_KEY='bradzosekretnawartosc',
))
#docelowo dane będą w przechowywane w bazie
DANE = [{
'pytanie': 'Stolica Kaszub, to:',
'odpowiedzi': ['Gdańsk', 'Kościerzyna', 'Kartuzy'],
'odpok': 'Kartuzy'},
{
'pytanie': 'TAK po kaszubsku to:',
'odpowiedzi': ['jeee', 'jo', 'wsio'],
'odpok': 'jo'},
{
'pytanie': 'Kaszuby to:',
'odpowiedzi': ['Najpiękniejszy rejon', 'Brzydki rejon', 'Co to Kaszuby?'],
'odpok': 'Najpiękniejszy rejon'},
]
USERS =[{
'id':'1','nazwa':'Jakub98'},
{
'id':'2','nazwa':'RomekKaszuber'},
{
'id':'3','nazwa':'Kartuzjanin88'},
{
'id':'4','nazwa':'ŚlązakSzpieg'},
{
'id':'5','nazwa':'RomanMitoman'},
{
'id':'6','nazwa':'BoskiBezTroski76'},
]
@app.route('/')
def main():
return render_template("stronaPowitalna.html")
@app.route('/User/<userId>')
def user(userId):
wybrany = USERS[(int(userId)-1)]['nazwa']
return f'Użytkownik o numerze id: {userId} to: ' + wybrany
@app.route('/Dodaj/<zmienna1>+<zmienna2>')
def dodaj(zmienna1, zmienna2):
wynik = int(zmienna1)+int(zmienna2)
return f'wynik dodawania to {wynik}'
@app.route('/WolniKaszubi')
def WolniKaszubi():
return render_template("stronaPowitalna.html")
@app.route('/listaPodstron')
def ListaPodstron():
return render_template("listaPodstron.html")
@app.route('/ONas')
def ONas():
return render_template('oNas.html', zm='Nasz serwis jest wolny od wszystkiego, nie ma śledzenia, nie ma leżenia, nie ma niczego.')
@app.route('/Logowanie', methods=['GET', 'POST'])
def Logowanie():
if request.method == 'POST':
_name = request.form['inputName']
_email = request.form['inputEmail']
_password = request.form['inputPassword']
print(_name, _email, _password)
database.insert_one_row(_name, _email, _password)
return render_template("logowanie.html")
@app.route('/TestKaszuba', methods=['GET', 'POST'])
def TestKaszuba():
if request.method == 'POST':
punkty = 0
odpowiedzi = request.form
for pnr, odp in odpowiedzi.items():
if odp == DANE[int(pnr)]['odpok']:
punkty += 1
if punkty == 3: ###test
print('zdałes')
flash('Liczba poprawnych odpowiedzi, to: {0}'.format(punkty))
return redirect(url_for('TestKaszuba'))
return render_template('TestKaszuba.html', pytania=DANE)
@app.route('/Wyszukiwarka', methods=['GET', 'POST'])
def Wyszukiwarka():
if request.method == 'POST':
id = request.form['id']
#znaleziony = USERS[(int(id)-1)]['nazwa']
znaleziony = database.select_where('3',id)
flash('Użytkownik o numerze id: {0}, to {1}' .format(id, znaleziony))
return redirect(url_for('Wyszukiwarka'))
return render_template('wyszukiwarka.html')
if __name__ == '__main__':
app.run(debug=True)
|
{"/portal.py": ["/database.py"]}
|
15,076,244
|
szutu/Portal
|
refs/heads/master
|
/database.py
|
import mysql.connector
import re
# inicjacja połączenia z bazą
mydb = mysql.connector.connect(host="localhost", user="jakub", passwd="fajerwerki", database="mydatabase")
print(mydb)
# inicjacja kursora po naszej bazie z poziomu Python baza nazywa sie mydb nie 'mydatabase'
mycursor = mydb.cursor()
def create_table(table_name):
# mycursor.execute("CREATE DATABASE mydatabase") #w tym wypadku rzeczy w cudzyslowiu sa kąpilowane
# mycursor.execute("ALTER TABLE users ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY")
mycursor.execute("CREATE TABLE {0} (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), email VARCHAR(255), password VARCHAR(255))" .format(table_name))
# powyzsze są zakomitowane bo raz wykonane są już zapisane!!, możliwe ze to sie powinno gdzie indziej pisac
def show_db():
# wyswietlenie zawartosci bazy
mycursor.execute("SHOW DATABASES")
for x in mycursor:
print(x)
def show_table():
mycursor.execute("SHOW TABLES")
for x in mycursor:
print(x)
# sprawdzenie czy jest kontakt z bazą
def check_connection():
if (mydb):
print('Kontakt z bazą')
else:
print('Nie ma kontaktu z baza')
def insert_one_row(arg1, arg2, arg3):
# uzupelniania tabeli (jeden wiersz)
#sql = "INSERT INTO users (name, nick) VALUES (%s, %s, )"
sql = "INSERT INTO dane (name, email, password) VALUES (%s, %s, %s)"
val = (arg1, arg2, arg3)
mycursor.execute(sql, val)
mydb.commit() # ten commit jest wymagany aby dokonac zmian w bazie
print(mycursor.rowcount, "record inserted.")
# uzupelnienie tabeli (wiele wierszy)
def insert_many_rows():
sql = "INSERT INTO users (name, nick) VALUES (%s, %s)"
val = [ # tutaj mamy listę krotek, aby mozna za jednym razem wstawic wiele
('Roman', 'romekAtomek'),
('Andrzej', 'Andrjuu'),
('Monika', 'DziewczynaRatownika88'),
('Jan', 'JohnNr5'),
('Beata', 'Betrixy'),
]
mycursor.executemany(sql, val) # tutaj dopisek 'many' wskazuje na uzupelnienie WIELU wierszy na raz
mydb.commit() # wymagane aby dokonac zmian w bazie
print(mycursor.rowcount, "was inserted.")
print("1 record inserted, ID:", mycursor.lastrowid) # kazde odpalenie dodaje kolejne rekordy
def select_from_table():
# mycursor.execute("SELECT * FROM users")
mycursor.execute("SELECT name FROM users") # wybrane kolumny tylko
myresult = mycursor.fetchall()
# myresult = mycursor.fetchone() #zwraca pierwszy wiersz z select
for x in myresult:
print(x)
def select_where(choice, search):
if choice == '1':
sql = ("SELECT * FROM users WHERE nick ='%s'" % search)
elif choice == '2':
sql = ("SELECT * FROM users WHERE nick LIKE '%{0}%'" .format(search))
else:
sql = ("SELECT * FROM dane WHERE id LIKE '%{0}%'" .format(search))
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
return myresult
def sort_db(choice1, choice2):
if choice1 == "nick":
sql = "SELECT * FROM users ORDER BY nick "
elif choice1 == "name":
sql = "SELECT * FROM users ORDER BY name "
elif choice1 == "id":
sql = "SELECT * FROM users ORDER BY id "
if choice2 == "asc" or choice2 == "ASC":
sql += "ASC" #alternative other order
else:
sql += "DESC"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
def delete_record():
sql = "DELETE FROM users WHERE nick ='Andrjuu'" # string 'sql' to polecenie SQL
mycursor.execute(sql) # tutaj 'wysylamy' polecenie SQL do kursora iterujacego po bazie
mydb.commit() # konieczne zeby dokonac zmian w bazie tj. dodawanie usuwanie itp
print(mycursor.rowcount, "record(s) deleted")
def delete_table(table):
sql = "DROP TABLE IF EXISTS "
sql += table
mycursor.execute(sql)
def update_table(what_to_change, previos_value, new_value):
#tabele trzeba zmieniac w poleceniu na razie
if what_to_change == "nick":
sql = "UPDATE users SET nick =%s WHERE nick = %s"
elif what_to_change == "name":
sql = "UPDATE users SET name =%s WHERE name = %s"
val = (new_value, previos_value)
mycursor.execute(sql, val)
print(mycursor.rowcount, "record(s) updated")
#create_table(input("Podaj nazwę tabeli która chcesz utworzyć: "))
#insert_many_rows()
# show_db()
#show_table()
# select_from_table()
#select_where(input("Jeżeli chcesz wyszukać po całym nicku wpisz: 1\nJeżeli po jego części wpisz: 2\n"), input("Wpisz szukaną fraze: "))
#sort_db((input("Jeśli chcesz posotrować po nickach wpisz: 'nick', jeśli po imionach wpisz 'name', jeśli id to 'id' ")), (input("jesli chcesz posortować rosnąca wpisz: 'asc', jeśli malejąco wpisz cokolwiek ")))
#delete_record()
#delete_table('users')
#update_table((input("podaj która kolumne chcesz zastąpić, wpisz 'nick' lub 'name'")), (input("podaj którą wartość chcesz zastąpić")), (input("podaj nową wartość: ")))
#sort_db()
#insert_one_row(input("podaj nazwę tabeli, którą chcesz uzupełnić: "), (input("podaj imie: ")), (input("podaj email: "), input("Podaj haslo")))
|
{"/portal.py": ["/database.py"]}
|
15,195,046
|
SumanSunuwar/Todo-app
|
refs/heads/master
|
/userprofile/admin.py
|
from django.contrib import admin
from userprofile.models import Profile
# Register your models here.
@admin.register(Profile)
class ProfileAdmin(admin.ModelAdmin):
list_display = ("user", "first_name", "middle_name", "last_name", "contact", "address",)
|
{"/home/admin.py": ["/home/models.py"], "/home/views.py": ["/home/models.py", "/home/forms.py"], "/home/urls.py": ["/home/views.py"], "/userprofile/views.py": ["/userprofile/forms.py"], "/userprofile/urls.py": ["/userprofile/views.py"], "/userprofile/admin.py": ["/userprofile/models.py"], "/home/forms.py": ["/home/models.py"]}
|
15,195,047
|
SumanSunuwar/Todo-app
|
refs/heads/master
|
/home/models.py
|
from django.db import models
# Create your models here.
#Let's create an object > Todo object
# fields : title , description, date
class Todo(models.Model):
title = models.CharField(max_length=255)
description = models.TextField(null=True, blank=True)
date = models.DateField(null=True,blank=True)
todo_image = models.ImageField(upload_to="upload/todo",blank=True, null=True)
def __str__(self):
return self.title
|
{"/home/admin.py": ["/home/models.py"], "/home/views.py": ["/home/models.py", "/home/forms.py"], "/home/urls.py": ["/home/views.py"], "/userprofile/views.py": ["/userprofile/forms.py"], "/userprofile/urls.py": ["/userprofile/views.py"], "/userprofile/admin.py": ["/userprofile/models.py"], "/home/forms.py": ["/home/models.py"]}
|
15,195,048
|
SumanSunuwar/Todo-app
|
refs/heads/master
|
/home/admin.py
|
from django.contrib import admin
from home.models import Todo
# Register your models here.
@admin.register(Todo)
class TodoAdmin(admin.ModelAdmin):
list_display = ("title", "description", "date", "todo_image", "is_greater_priority", "profile", )
list_filter = ("date", "title",)
search_fields = ("title", "date",)
|
{"/home/admin.py": ["/home/models.py"], "/home/views.py": ["/home/models.py", "/home/forms.py"], "/home/urls.py": ["/home/views.py"], "/userprofile/views.py": ["/userprofile/forms.py"], "/userprofile/urls.py": ["/userprofile/views.py"], "/userprofile/admin.py": ["/userprofile/models.py"], "/home/forms.py": ["/home/models.py"]}
|
15,195,049
|
SumanSunuwar/Todo-app
|
refs/heads/master
|
/userprofile/forms.py
|
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django import forms
from django.contrib.auth.forms import User
class CutomAuthenticationForm(AuthenticationForm):
pass
class CustomUserSignupForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = (
"username",
"email",
"password1",
"password2"
)
|
{"/home/admin.py": ["/home/models.py"], "/home/views.py": ["/home/models.py", "/home/forms.py"], "/home/urls.py": ["/home/views.py"], "/userprofile/views.py": ["/userprofile/forms.py"], "/userprofile/urls.py": ["/userprofile/views.py"], "/userprofile/admin.py": ["/userprofile/models.py"], "/home/forms.py": ["/home/models.py"]}
|
15,195,050
|
SumanSunuwar/Todo-app
|
refs/heads/master
|
/home/forms.py
|
from django import forms
from home.models import Todo
from django.db.models import fields
#class TodoForm(forms.Form):
# title = forms.CharField()
# description = forms.CharField()
# date = forms.DateField()
class TodoForm(forms.ModelForm):
class Meta:
model = Todo
fields = ("title", "description", "date", "todo_image", "is_greater_priority", "profile",)
|
{"/home/admin.py": ["/home/models.py"], "/home/views.py": ["/home/models.py", "/home/forms.py"], "/home/urls.py": ["/home/views.py"], "/userprofile/views.py": ["/userprofile/forms.py"], "/userprofile/urls.py": ["/userprofile/views.py"], "/userprofile/admin.py": ["/userprofile/models.py"], "/home/forms.py": ["/home/models.py"]}
|
15,251,903
|
reg-11/122-Project
|
refs/heads/master
|
/esko_app/urls.py
|
from django.urls import path, include
from .views import (PostListView, PostDetailView,PostCreateView, PostUpdateView,
PostDeleteView, AddCommentView, HomeListView, PasswordsChangeView,
TagIndexView, ReportView, ReportDeleteView, ReportPostDeleteView)
from . import views
from django.contrib.auth import views as auth_views
from django.conf import settings
from django.conf.urls.static import static
app_name = 'esko_app'
urlpatterns = [
path('', views.index, name='index'),
path('signup/', views.signup, name='signup'),
path('login/', views.loginPage, name='login'),
path('home/', views.home, name='home'),
path('profile/', views.profile, name='profile'),
path('category/', views.category, name='category'),
path('search_tags/', views.search_tags, name='search_tags'),
# path('sell/', views.sell, name='sell'),
path('profileOther/<username>/', views.profileOther, name='profile-other'),
path('profileOtherComment/<username>/', views.profileOtherComment, name='profile-other-comment'),
path('postCategory/', views.PostByCategory, name='post_by_category'),
path('searchTag/', views.SearchByTag, name='search_by_tags'),
path('reported-posts/', views.reportedPosts, name='reported-posts'),
path('post/<int:pk>/report', ReportView.as_view(), name='report-post'),
path('report/<int:pk>/delete/', ReportDeleteView.as_view(), name='report-delete'),
path('rpost/<int:pk>/delete/', ReportPostDeleteView.as_view(), name='rpost-delete'),
# path('home/', HomeListView.as_view(), name='home'),
# path('profile/', PostListView.as_view(), name='profile'),
path('about/', views.about, name='about'),
path('logout/', views.logoutUser, name='logout'),
path('password-reset/',
PasswordsChangeView.as_view(template_name='esko_app/password_reset.html'),
name= 'password_reset'),
path('password-reset/done/', views.password_success, name= 'password_success'),
path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'),
path('post/new/', PostCreateView.as_view(), name='post-create'),
path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'),
path('profileSettings/', views.profileSettings, name='profileSettings'),
path('like/<int:pk>/',views.LikeView, name='like_post'),
# path('likeHome/',views.LikeViewHome, name='like_post_home'),
path('post/<int:pk>/comment', AddCommentView.as_view(), name='add_comment'),
path('tags/<slug:tag_slug>/', TagIndexView.as_view(), name='posts_by_tags'),
# path('post/new/', views.post, name='post-create'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
{"/esko_app/views.py": ["/esko_app/models.py", "/esko_app/forms.py", "/esko_app/filters.py"], "/esko_app/filters.py": ["/esko_app/models.py"], "/esko_app/urls.py": ["/esko_app/views.py"], "/esko_app/admin.py": ["/esko_app/models.py"], "/esko_app/forms.py": ["/esko_app/models.py"]}
|
15,251,904
|
reg-11/122-Project
|
refs/heads/master
|
/esko_app/migrations/0027_auto_20210530_1506.py
|
# Generated by Django 3.2.3 on 2021-05-30 07:06
from django.db import migrations, models
import taggit.managers
class Migration(migrations.Migration):
dependencies = [
('taggit', '0003_taggeditem_add_unique_index'),
('esko_app', '0026_delete_report'),
]
operations = [
migrations.AlterField(
model_name='post',
name='category',
field=models.CharField(choices=[('sell', 'sell'), ('find', 'find'), ('services/rent', 'services/rent'), ('swap', 'swap')], max_length=13),
),
migrations.RemoveField(
model_name='post',
name='tags',
),
migrations.AddField(
model_name='post',
name='tags',
field=taggit.managers.TaggableManager(help_text='A comma-separated list of tags.', through='taggit.TaggedItem', to='taggit.Tag', verbose_name='Tags'),
),
]
|
{"/esko_app/views.py": ["/esko_app/models.py", "/esko_app/forms.py", "/esko_app/filters.py"], "/esko_app/filters.py": ["/esko_app/models.py"], "/esko_app/urls.py": ["/esko_app/views.py"], "/esko_app/admin.py": ["/esko_app/models.py"], "/esko_app/forms.py": ["/esko_app/models.py"]}
|
15,251,905
|
reg-11/122-Project
|
refs/heads/master
|
/esko_app/admin.py
|
from django.contrib import admin
from .models import Profile, Post, Category, Comment, Report
# Register your models here.
admin.site.register(Profile)
admin.site.register(Post)
admin.site.register(Comment)
admin.site.register(Category)
admin.site.register(Report)
|
{"/esko_app/views.py": ["/esko_app/models.py", "/esko_app/forms.py", "/esko_app/filters.py"], "/esko_app/filters.py": ["/esko_app/models.py"], "/esko_app/urls.py": ["/esko_app/views.py"], "/esko_app/admin.py": ["/esko_app/models.py"], "/esko_app/forms.py": ["/esko_app/models.py"]}
|
15,251,906
|
reg-11/122-Project
|
refs/heads/master
|
/esko_app/forms.py
|
from django.forms import ModelForm
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django import forms
from .models import Profile, Post, Comment, Report
# from taggit.forms import TagField
CATEGORIES = [
('sell', 'sell'),
('find', 'find'),
('services/rent', 'services/rent'),
('swap', 'swap'),
]
PROBLEMS = [
('hate speech', 'hate speech'),
('violence', 'violence'),
('harassment', 'harassment'),
('nudity', 'nudity'),
('false information', 'false information'),
('spam', 'spam'),
('others', 'others')
]
class CreateUserForm(UserCreationForm):
password1 = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control','placeholder':'Password'}))
password2 = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control','placeholder':'Confirm Password'}))
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
widgets = {
'username': forms.TextInput(attrs={'class': 'form-control','placeholder':'Username'}),
'email': forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter UP email'}),
}
def clean_email(self, *args, **kwargs):
email = self.cleaned_data.get("email")
if not email.endswith("@up.edu.ph"):
raise forms.ValidationError("This is not a valid email")
return email
class UserUpdateForm(forms.ModelForm):
# email = forms.TextInput(attrs={'class': 'form-control'})
class Meta:
model = User
fields = ['username', 'email']
widgets = {
'username': forms.TextInput(attrs={'class': 'form-control'}),
# 'email': forms.TextInput(attrs={'class': 'form-control'}),
}
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['profile_pic', 'year_level','phone_number','sns_account','bio']
widgets = {
'profile_pic': forms.FileInput(attrs={'class': 'form-control', 'style': 'margin-left:15px; width:50%'}),
'year_level': forms.TextInput(attrs={'class': 'form-control'}),
'phone_number': forms.TextInput(attrs={'class': 'form-control'}),
'sns_account': forms.TextInput(attrs={'class': 'form-control'}),
'bio': forms.Textarea(attrs={'class': 'form-control'}),
}
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['body']
widgets = {
# 'commenter': forms.TextInput(attrs={'class': 'form-control'}),
'body': forms.Textarea(attrs={'rows':3, 'class': 'form-control', 'style': 'width:93%;margin-left:35px','placeholder':'Type your comment here'}),
}
class CreatePostForm(forms.ModelForm):
class Meta:
model = Post
category = forms.ChoiceField(choices=CATEGORIES)
# tags = TagField()
fields = ['category', 'description', 'tags','post_image']
# fields = ['category', 'description', 'tags']
widgets = {
'description': forms.Textarea(attrs={'class': 'form-control', 'rows':4}),
'tags': forms.TextInput(attrs={'class': 'form-control'}),
'post_image': forms.FileInput(attrs={'class': 'form-control','multiple': True}),
}
class ReportForm(forms.ModelForm):
class Meta:
model = Report
problem = forms.ChoiceField(choices=PROBLEMS)
# tags = TagField()
fields = ['problem', 'notes']
# fields = ['category', 'description', 'tags']
widgets = {
'notes': forms.Textarea(attrs={'class': 'form-control', 'rows':2}),
# 'tags': forms.TagField(attrs={'class': 'form-control'}),
# 'post_image': forms.FileInput(attrs={'class': 'form-control','multiple': True}),
}
|
{"/esko_app/views.py": ["/esko_app/models.py", "/esko_app/forms.py", "/esko_app/filters.py"], "/esko_app/filters.py": ["/esko_app/models.py"], "/esko_app/urls.py": ["/esko_app/views.py"], "/esko_app/admin.py": ["/esko_app/models.py"], "/esko_app/forms.py": ["/esko_app/models.py"]}
|
15,251,907
|
reg-11/122-Project
|
refs/heads/master
|
/esko_app/migrations/0002_profile.py
|
# Generated by Django 3.2.3 on 2021-05-24 15:03
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('esko_app', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Profile',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('profile_picture', models.ImageField(default='default.jpg', upload_to='profile_pics')),
('year_level', models.CharField(blank=True, max_length=30)),
('phone_number', models.IntegerField(blank=True)),
('sns_account', models.URLField()),
('bio', models.CharField(blank=True, max_length=200)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='esko_app.user')),
],
),
]
|
{"/esko_app/views.py": ["/esko_app/models.py", "/esko_app/forms.py", "/esko_app/filters.py"], "/esko_app/filters.py": ["/esko_app/models.py"], "/esko_app/urls.py": ["/esko_app/views.py"], "/esko_app/admin.py": ["/esko_app/models.py"], "/esko_app/forms.py": ["/esko_app/models.py"]}
|
15,251,908
|
reg-11/122-Project
|
refs/heads/master
|
/esko_app/apps.py
|
from django.apps import AppConfig
class EskoAppConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'esko_app'
def ready(self):
import esko_app.signals
|
{"/esko_app/views.py": ["/esko_app/models.py", "/esko_app/forms.py", "/esko_app/filters.py"], "/esko_app/filters.py": ["/esko_app/models.py"], "/esko_app/urls.py": ["/esko_app/views.py"], "/esko_app/admin.py": ["/esko_app/models.py"], "/esko_app/forms.py": ["/esko_app/models.py"]}
|
15,251,909
|
reg-11/122-Project
|
refs/heads/master
|
/esko_app/migrations/0001_initial.py
|
# Generated by Django 3.2.3 on 2021-05-20 16:27
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('user_id', models.AutoField(primary_key=True, serialize=False)),
('email', models.CharField(max_length=50, unique=True)),
('password', models.CharField(max_length=30, unique=True)),
('username', models.CharField(blank=True, max_length=30, unique=True)),
('year_level', models.CharField(blank=True, max_length=30)),
('phone_number', models.IntegerField(blank=True)),
('sns_account', models.URLField()),
('bio', models.CharField(blank=True, max_length=200)),
],
),
migrations.CreateModel(
name='Post',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('category', models.CharField(max_length=30)),
('description', models.CharField(max_length=200)),
('tags', models.CharField(max_length=100)),
('image', models.ImageField(blank=True, null=True, upload_to='')),
('date', models.DateField()),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='esko_app.user')),
],
),
]
|
{"/esko_app/views.py": ["/esko_app/models.py", "/esko_app/forms.py", "/esko_app/filters.py"], "/esko_app/filters.py": ["/esko_app/models.py"], "/esko_app/urls.py": ["/esko_app/views.py"], "/esko_app/admin.py": ["/esko_app/models.py"], "/esko_app/forms.py": ["/esko_app/models.py"]}
|
15,251,910
|
reg-11/122-Project
|
refs/heads/master
|
/esko_app/migrations/0026_delete_report.py
|
# Generated by Django 3.2.3 on 2021-05-29 11:23
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('esko_app', '0025_report'),
]
operations = [
migrations.DeleteModel(
name='Report',
),
]
|
{"/esko_app/views.py": ["/esko_app/models.py", "/esko_app/forms.py", "/esko_app/filters.py"], "/esko_app/filters.py": ["/esko_app/models.py"], "/esko_app/urls.py": ["/esko_app/views.py"], "/esko_app/admin.py": ["/esko_app/models.py"], "/esko_app/forms.py": ["/esko_app/models.py"]}
|
15,251,911
|
reg-11/122-Project
|
refs/heads/master
|
/esko_app/filters.py
|
from django import forms
import django_filters
from .models import Post, Category
class PostFilter(django_filters.FilterSet):
sell = 'sell'
services = 'services/rent'
swap = 'swap'
find = 'find'
category_choices = [
(sell, sell),
(services, services),
(swap, swap),
(find, find),
]
#category = django_filters.ChoiceFilter(choices=Post.objects.all())
#category = django_filters.ChoiceFilter(choices=category_choices, widget=forms.Select(attrs={'class':'form-select', 'style':'background:$primary'}))
class Meta:
model = Post
fields = [
'category',
]
|
{"/esko_app/views.py": ["/esko_app/models.py", "/esko_app/forms.py", "/esko_app/filters.py"], "/esko_app/filters.py": ["/esko_app/models.py"], "/esko_app/urls.py": ["/esko_app/views.py"], "/esko_app/admin.py": ["/esko_app/models.py"], "/esko_app/forms.py": ["/esko_app/models.py"]}
|
15,251,912
|
reg-11/122-Project
|
refs/heads/master
|
/esko_app/migrations/0031_auto_20210602_1720.py
|
# Generated by Django 3.2.3 on 2021-06-02 09:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('esko_app', '0030_report'),
]
operations = [
migrations.RemoveField(
model_name='post',
name='tags',
),
migrations.AddField(
model_name='post',
name='tags',
field=models.CharField(default='tags', max_length=100),
preserve_default=False,
),
]
|
{"/esko_app/views.py": ["/esko_app/models.py", "/esko_app/forms.py", "/esko_app/filters.py"], "/esko_app/filters.py": ["/esko_app/models.py"], "/esko_app/urls.py": ["/esko_app/views.py"], "/esko_app/admin.py": ["/esko_app/models.py"], "/esko_app/forms.py": ["/esko_app/models.py"]}
|
15,251,913
|
reg-11/122-Project
|
refs/heads/master
|
/esko_app/views.py
|
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.views import PasswordChangeView
from django.contrib.auth.forms import PasswordChangeForm
from django.http import HttpResponseRedirect
from django.urls import reverse_lazy, reverse
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from .models import User, Post, Comment, Report
from .forms import CreateUserForm, UserUpdateForm, ProfileUpdateForm, CommentForm, CreatePostForm, ReportForm
from .filters import PostFilter
from django.core.paginator import Paginator
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from taggit.models import Tag
# from django.forms import modelformset_factory
# from .forms import ImageForm
# from .models import Images
# Create your views here.
#landing page
def index(request):
return render(request, 'esko_app/index.html')
#sign-up page
def signup(request):
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
print('yes')
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Account successfully created!')
return redirect('/esko_app/login/')
else:
print('no')
form = CreateUserForm()
return render(request, 'esko_app/signup.html', {'form': form})
def loginPage(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
# correct username and password login the user
login(request, user)
return redirect('/esko_app/home/')
else:
messages.error(request, 'Error wrong username/password')
return render(request, 'esko_app/login.html')
def logoutUser(request):
logout(request)
return redirect('/esko_app/login/')
def about(request):
return render(request, 'esko_app/about.html')
def category(request):
return render(request, 'esko_app/category.html')
def search_tags(request):
if request.method == "POST":
searched = request.POST['searched']
# tags = Tag.objects.filter()
return render(request, 'esko_app/search_tags.html', {'searched':searched})
else:
return render(request, 'esko_app/search_tags.html', {})
class PostListView(ListView):
model = Post
template_name = 'esko_app/profile.html' # <app>/model_viewtype.html
context_object_name = 'posts'
ordering = ['-date']
class HomeListView(ListView):
model = Post
template_name = 'esko_app/home.html' # <app>/model_viewtype.html
context_object_name = 'posts'
ordering = ['-date']
# @login_required(login_url= '/esko_app/login/')
# def home(request):
# posts = Post.objects.all().order_by('-date')
# # images = Images.objects.all()
# for post in posts:
# total_likes = post.total_likes()
# liked = False
# if post.likes.filter(id=request.user.id).exists():
# liked = True
# filtered_posts = PostFilter(
# request.GET,
# queryset=posts
# )
# post_paginator = Paginator(filtered_posts.qs, 3)
# page_num = request.GET.get('page')
# page = post_paginator.get_page(page_num)
# context = {
# 'count' : post_paginator.count,
# 'page' : page,
# 'total_likes': total_likes,
# 'liked': liked,
# # 'images': images,
# }
# return render(request, 'esko_app/home.html', context)
@login_required(login_url= '/esko_app/login/')
def home(request):
posts = Post.objects.all().order_by('-date')
for post in posts:
total_likes = post.total_likes()
tag_list = post.tag_list()
# print(tag_list)
liked = False
if post.likes.filter(id=request.user.id).exists():
liked = True
filtered_posts = PostFilter(
request.GET,
queryset=posts
)
post_paginator = Paginator(filtered_posts.qs, 3)
page_num = request.GET.get('page')
page = post_paginator.get_page(page_num)
context = {
'count' : post_paginator.count,
'page' : page,
'total_likes': total_likes,
'liked': liked,
'tag_list': tag_list,
}
return render(request, 'esko_app/home.html', context)
@login_required(login_url= '/esko_app/login/')
def PostByCategory(request):
posts = Post.objects.all().order_by('-date')
for post in posts:
total_likes = post.total_likes()
liked = False
if post.likes.filter(id=request.user.id).exists():
liked = True
filtered_posts = PostFilter(
request.GET,
queryset=posts
)
post_paginator = Paginator(filtered_posts.qs, 3)
page_num = request.GET.get('page')
page = post_paginator.get_page(page_num)
context = {
'count' : post_paginator.count,
'page' : page,
'total_likes': total_likes,
'liked': liked,
}
# return render(request, 'esko_app/home.html', context)
return render(request, 'esko_app/sell.html', context)
class TagIndexView(ListView):
model = Post
template_name = 'esko_app/tagView.html' # <app>/model_viewtype.html
context_object_name = 'posts'
ordering = ['-date']
def get_queryset(self):
return Post.objects.filter(tags__slug=self.kwargs.get('tag_slug'))
def SearchByTag(request):
if request.method == 'GET': # If the form is submitted
search_query = request.GET.get('search_box', None)
posts = Post.objects.filter(tags__contains=str(search_query))
total_likes = 0
liked = False
# tag_list = ['tags']
for post in posts:
total_likes = post.total_likes()
# tag_list = post.tag_list()
liked = False
if post.likes.filter(id=request.user.id).exists():
liked = True
filtered_posts = PostFilter(
request.GET,
queryset=posts
)
post_paginator = Paginator(filtered_posts.qs, 3)
page_num = request.GET.get('page')
page = post_paginator.get_page(page_num)
context = {
'count' : post_paginator.count,
'page' : page,
'total_likes': total_likes,
'liked': liked,
'search_query': search_query,
'tag_list' : post.tag_list(),
}
return render(request, 'esko_app/search_tags.html', context)
@login_required(login_url= '/esko_app/login/')
def profile(request):
posts = Post.objects.filter(author=request.user).order_by('-date')
total_likes = 0
liked = False
for post in posts:
total_likes = post.total_likes()
tag_list = post.tag_list()
liked = False
if post.likes.filter(id=request.user.id).exists():
liked = True
filtered_posts = PostFilter(
request.GET,
queryset=posts
)
post_paginator = Paginator(filtered_posts.qs, 3)
page_num = request.GET.get('page')
page = post_paginator.get_page(page_num)
context = {
'count' : post_paginator.count,
'page' : page,
'total_likes': total_likes,
'liked': liked,
'tag_list': tag_list
}
return render(request,'esko_app/profile.html', context)
def profileOther(request,username):
post = get_object_or_404(Post,id=request.POST.get('post_id'))
total_likes = post.total_likes()
liked = False
if post.likes.filter(id=request.user.id).exists():
liked = True
posts = Post.objects.filter(author=post.author).order_by('-date')
print(posts)
context = {
'user' : post.author,
'posts' :posts,
'total_likes': total_likes,
'liked': liked,
'tag_list': post.tag_list(),
}
return render(request,'esko_app/other_profile.html', context)
def profileOtherComment(request,username):
comment = get_object_or_404(Comment,id=request.POST.get('comment_id'))
comments = Comment.objects.filter(commenter=comment.commenter)
posts = Post.objects.filter(author=comment.commenter).order_by('-date')
context = {
'user' : comment.commenter,
'posts' :posts,
}
return render(request,'esko_app/other_profile_comment.html', context)
class PostDetailView(LoginRequiredMixin,DetailView):
model = Post
def get_context_data(self,*args, **kwargs):
context = super(PostDetailView,self).get_context_data()
# getting number of likes
get_post = get_object_or_404(Post, id=self.kwargs['pk'])
total_likes = get_post.total_likes()
tag_list = get_post.tag_list()
liked = False
if get_post.likes.filter(id=self.request.user.id).exists():
liked = True
context["total_likes"] = total_likes
context["liked"] = liked
context["tag_list"] = tag_list
print(tag_list)
print(get_post.tags)
return context
class PostCreateView(LoginRequiredMixin,CreateView):
model = Post
form_class = CreatePostForm
# fields = ['category','description','tags','post_image']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
class PostUpdateView(LoginRequiredMixin,UserPassesTestMixin,UpdateView):
model = Post
form_class = CreatePostForm
# fields = ['category','description','tags','post_image']
def form_valid(self, form):
form.instance.author = self.request.user
return super(PostUpdateView,self).form_valid(form)
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
class PostDeleteView(LoginRequiredMixin,UserPassesTestMixin,DeleteView):
model = Post
success_url = '/esko_app/profile'
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
class ReportPostDeleteView(LoginRequiredMixin,UserPassesTestMixin,DeleteView):
model = Post
success_url = '/esko_app/reported-posts'
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
@login_required(login_url= '/esko_app/login/')
def LikeView(request,pk):
post = get_object_or_404(Post,id=request.POST.get('post_id'))
liked = False
if post.likes.filter(id=request.user.id).exists():
post.likes.remove(request.user)
liked = False
else:
post.likes.add(request.user)
liked = True
return HttpResponseRedirect(reverse('esko_app:post-detail',args=[str(pk)]))
class AddCommentView(LoginRequiredMixin,CreateView):
model = Comment
form_class= CommentForm
template_name = 'esko_app/add_comment.html'
def form_valid(self, form):
form.instance.commenter = self.request.user
form.instance.post_id = self.kwargs['pk']
return super().form_valid(form)
def get_success_url(self, **kwargs):
return reverse('esko_app:post-detail', kwargs={'pk':self.kwargs['pk']})
@login_required(login_url= '/esko_app/login/')
def reportedPosts(request):
reports = Report.objects.all().order_by('-date_reported')
#posts = Post.objects.all(repo_id__pk=rpost.post)
context = {
'reports' : reports
}
return render(request, 'esko_app/reported-post.html', context)
class ReportView(LoginRequiredMixin,CreateView):
model = Report
form_class= ReportForm
template_name = 'esko_app/add_report.html'
def form_valid(self, form):
form.instance.reporter = self.request.user
form.instance.post_id = self.kwargs['pk']
return super().form_valid(form)
def get_success_url(self, **kwargs):
return reverse('esko_app:post-detail', kwargs={'pk':self.kwargs['pk']})
class ReportDeleteView(LoginRequiredMixin,UserPassesTestMixin,DeleteView):
model = Report
success_url = '/esko_app/reported-posts'
def test_func(self):
report = self.get_object()
if self.request.user.is_superuser:
return True
return False
@login_required(login_url= '/esko_app/login/')
def profileSettings(request):
if request.method == 'POST':
u_form = UserUpdateForm(request.POST,instance=request.user)
p_form = ProfileUpdateForm(request.POST,request.FILES, instance=request.user.profile)
if u_form.is_valid() and p_form.is_valid():
u_form.save()
p_form.save()
messages.success(request, f'Your profile has been updated!')
return redirect('/esko_app/profileSettings/')
else:
u_form = UserUpdateForm(instance=request.user)
p_form = ProfileUpdateForm(instance=request.user.profile)
context = {
'u_form': u_form,
'p_form': p_form
}
return render(request, 'esko_app/profilesettings.html',context)
class PasswordsChangeView(PasswordChangeView):
form_class = PasswordChangeForm
success_url = reverse_lazy('esko_app:password_success')
def password_success(request):
return render(request, 'esko_app/password_reset_done.html')
|
{"/esko_app/views.py": ["/esko_app/models.py", "/esko_app/forms.py", "/esko_app/filters.py"], "/esko_app/filters.py": ["/esko_app/models.py"], "/esko_app/urls.py": ["/esko_app/views.py"], "/esko_app/admin.py": ["/esko_app/models.py"], "/esko_app/forms.py": ["/esko_app/models.py"]}
|
15,251,914
|
reg-11/122-Project
|
refs/heads/master
|
/esko_app/migrations/0028_auto_20210530_2331.py
|
# Generated by Django 3.2.3 on 2021-05-30 15:31
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('esko_app', '0027_auto_20210530_1506'),
]
operations = [
migrations.RemoveField(
model_name='post',
name='post_image',
),
migrations.CreateModel(
name='Images',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('image', models.ImageField(blank=True, null=True, upload_to='post_pics', verbose_name='Image')),
('post', models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, to='esko_app.post')),
],
),
]
|
{"/esko_app/views.py": ["/esko_app/models.py", "/esko_app/forms.py", "/esko_app/filters.py"], "/esko_app/filters.py": ["/esko_app/models.py"], "/esko_app/urls.py": ["/esko_app/views.py"], "/esko_app/admin.py": ["/esko_app/models.py"], "/esko_app/forms.py": ["/esko_app/models.py"]}
|
15,251,915
|
reg-11/122-Project
|
refs/heads/master
|
/esko_app/models.py
|
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from PIL import Image
from django.urls import reverse
# from taggit.managers import TaggableManager
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=30)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('/esko_app/home/')
# class Post(models.Model):
# CATEGORIES = [
# ('sell', 'sell'),
# ('find', 'find'),
# ('services/rent', 'services/rent'),
# ('swap', 'swap'),
# ]
# author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
# category = models.CharField(max_length=13,choices=CATEGORIES)
# description = models.TextField(max_length=250)
# # tags = models.CharField(max_length=100)
# post_image = models.ImageField(upload_to='post_pics',null=True,blank=True)
# date = models.DateTimeField(auto_now_add=True)
# likes = models.ManyToManyField(User, related_name='user_posts')
# tags = TaggableManager()
# def total_likes(self):
# return self.likes.count()
# def __str__(self):
# return self.category
# def get_absolute_url(self):
# return reverse('esko_app:post-detail', kwargs={'pk':self.pk})
class Post(models.Model):
CATEGORIES = [
('sell', 'sell'),
('find', 'find'),
('services/rent', 'services/rent'),
('swap', 'swap'),
]
author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
category = models.CharField(max_length=13,choices=CATEGORIES)
description = models.TextField(max_length=250)
tags = models.CharField(max_length=100)
post_image = models.ImageField(upload_to='post_pics',null=True,blank=True)
date = models.DateTimeField(auto_now_add=True)
likes = models.ManyToManyField(User, related_name='user_posts')
# tags = TaggableManager()
def tag_list(self):
return self.tags.split(',')
def total_likes(self):
return self.likes.count()
def __str__(self):
return self.category
def get_absolute_url(self):
return reverse('esko_app:post-detail', kwargs={'pk':self.pk})
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
profile_pic = models.ImageField(default='default.jpg', upload_to='profile_pics', blank=True)
year_level = models.CharField(max_length=30, blank=True)
phone_number = models.IntegerField(null=True,blank=True)
sns_account = models.URLField(max_length = 200,blank=True)
bio = models.CharField(max_length=200, blank=True)
def __str__(self):
return f'{self.user.username} Profile'
def save(self, *args, **kwargs):
super(Profile,self).save(*args, **kwargs)
img = Image.open(self.profile_pic.path)
if img.height > 400 or img.width > 400:
output_size = (400,400)
img.thumbnail(output_size)
img.save(self.profile_pic.path)
class Comment(models.Model):
post = models.ForeignKey(Post,related_name="comments",on_delete=models.CASCADE)
commenter = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
body = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '%s - %s' % (self.post.category, self.commenter)
class Report(models.Model):
PROBLEMS = [
('hate speech', 'hate speech'),
('violence', 'violence'),
('harassment', 'harassment'),
('nudity', 'nudity'),
('false information', 'false information'),
('spam', 'spam'),
('others', 'others')
]
reporter = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
post = models.ForeignKey(Post,related_name="reports",on_delete=models.CASCADE)
date_reported = models.DateTimeField(auto_now_add=True)
problem = models.CharField(max_length=50,choices=PROBLEMS)
notes = models.TextField(null=True,blank=True)
def __str__(self):
return '%s - %s' % (self.problem, self.reporter)
|
{"/esko_app/views.py": ["/esko_app/models.py", "/esko_app/forms.py", "/esko_app/filters.py"], "/esko_app/filters.py": ["/esko_app/models.py"], "/esko_app/urls.py": ["/esko_app/views.py"], "/esko_app/admin.py": ["/esko_app/models.py"], "/esko_app/forms.py": ["/esko_app/models.py"]}
|
15,251,916
|
reg-11/122-Project
|
refs/heads/master
|
/esko_app/migrations/0021_alter_post_category.py
|
# Generated by Django 3.2.3 on 2021-05-29 04:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('esko_app', '0020_alter_post_category'),
]
operations = [
migrations.AlterField(
model_name='post',
name='category',
field=models.CharField(choices=[('sell', 'sell'), ('find', 'find'), ('services', 'services/rent'), ('swap', 'swap')], max_length=8),
),
]
|
{"/esko_app/views.py": ["/esko_app/models.py", "/esko_app/forms.py", "/esko_app/filters.py"], "/esko_app/filters.py": ["/esko_app/models.py"], "/esko_app/urls.py": ["/esko_app/views.py"], "/esko_app/admin.py": ["/esko_app/models.py"], "/esko_app/forms.py": ["/esko_app/models.py"]}
|
15,251,917
|
reg-11/122-Project
|
refs/heads/master
|
/esko_app/migrations/0004_auto_20210525_0004.py
|
# Generated by Django 3.2.3 on 2021-05-24 16:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('esko_app', '0003_auto_20210524_2313'),
]
operations = [
migrations.AlterField(
model_name='profile',
name='profile_picture',
field=models.ImageField(blank=True, default='default.jpg', upload_to='profile_pics'),
),
migrations.AlterField(
model_name='profile',
name='sns_account',
field=models.URLField(blank=True),
),
]
|
{"/esko_app/views.py": ["/esko_app/models.py", "/esko_app/forms.py", "/esko_app/filters.py"], "/esko_app/filters.py": ["/esko_app/models.py"], "/esko_app/urls.py": ["/esko_app/views.py"], "/esko_app/admin.py": ["/esko_app/models.py"], "/esko_app/forms.py": ["/esko_app/models.py"]}
|
15,251,918
|
reg-11/122-Project
|
refs/heads/master
|
/esko_app/migrations/0011_alter_post_image.py
|
# Generated by Django 3.2.3 on 2021-05-26 10:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('esko_app', '0010_auto_20210526_1631'),
]
operations = [
migrations.AlterField(
model_name='post',
name='image',
field=models.ImageField(blank=True, null=True, upload_to='post_pics'),
),
]
|
{"/esko_app/views.py": ["/esko_app/models.py", "/esko_app/forms.py", "/esko_app/filters.py"], "/esko_app/filters.py": ["/esko_app/models.py"], "/esko_app/urls.py": ["/esko_app/views.py"], "/esko_app/admin.py": ["/esko_app/models.py"], "/esko_app/forms.py": ["/esko_app/models.py"]}
|
15,251,919
|
reg-11/122-Project
|
refs/heads/master
|
/esko_app/migrations/0030_report.py
|
# Generated by Django 3.2.3 on 2021-05-30 22:28
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('esko_app', '0029_auto_20210531_0114'),
]
operations = [
migrations.CreateModel(
name='Report',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date_reported', models.DateTimeField(auto_now_add=True)),
('problem', models.CharField(choices=[('hate speech', 'hate speech'), ('violence', 'violence'), ('harassment', 'harassment'), ('nudity', 'nudity'), ('false information', 'false information'), ('spam', 'spam'), ('others', 'others')], max_length=50)),
('notes', models.TextField(blank=True, null=True)),
('post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='reports', to='esko_app.post')),
('reporter', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
|
{"/esko_app/views.py": ["/esko_app/models.py", "/esko_app/forms.py", "/esko_app/filters.py"], "/esko_app/filters.py": ["/esko_app/models.py"], "/esko_app/urls.py": ["/esko_app/views.py"], "/esko_app/admin.py": ["/esko_app/models.py"], "/esko_app/forms.py": ["/esko_app/models.py"]}
|
15,270,899
|
aswathyarun89/My-Smart-Class
|
refs/heads/master
|
/myapp2/migrations/0019_auto_20210310_1602.py
|
# Generated by Django 3.1.2 on 2021-03-10 16:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myapp2', '0018_auto_20210310_1501'),
]
operations = [
migrations.AlterField(
model_name='user_info',
name='User_Photo',
field=models.FileField(blank=True, max_length=50, null=True, upload_to=''),
),
]
|
{"/myapp2/views.py": ["/myapp2/models.py"], "/myapp2/admin.py": ["/myapp2/models.py"]}
|
15,270,900
|
aswathyarun89/My-Smart-Class
|
refs/heads/master
|
/myapp2/migrations/0007_auto_20201223_0909.py
|
# Generated by Django 3.1.2 on 2020-12-23 09:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myapp2', '0006_user_info_gender'),
]
operations = [
migrations.AlterField(
model_name='user_info',
name='Date_Birth',
field=models.DateField(blank=True),
),
migrations.AlterField(
model_name='user_info',
name='User_Photo',
field=models.CharField(blank=True, max_length=50),
),
]
|
{"/myapp2/views.py": ["/myapp2/models.py"], "/myapp2/admin.py": ["/myapp2/models.py"]}
|
15,270,901
|
aswathyarun89/My-Smart-Class
|
refs/heads/master
|
/myapp2/migrations/0013_auto_20210128_1314.py
|
# Generated by Django 3.1.2 on 2021-01-28 13:14
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('myapp2', '0012_course_info'),
]
operations = [
migrations.AddField(
model_name='course_info',
name='Course_Owner_Id',
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='myapp2.user_info'),
preserve_default=False,
),
migrations.AlterField(
model_name='course_info',
name='Course_Owner',
field=models.CharField(max_length=30),
),
]
|
{"/myapp2/views.py": ["/myapp2/models.py"], "/myapp2/admin.py": ["/myapp2/models.py"]}
|
15,270,902
|
aswathyarun89/My-Smart-Class
|
refs/heads/master
|
/myapp2/migrations/0010_course_info.py
|
# Generated by Django 3.1.2 on 2021-01-27 23:48
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('myapp2', '0009_delete_course_info'),
]
operations = [
migrations.CreateModel(
name='Course_Info',
fields=[
('Course_Id', models.BigIntegerField(primary_key=True, serialize=False)),
('Course_Name', models.CharField(max_length=30)),
('Course_Descrp', models.CharField(blank=True, max_length=200)),
('Course_Duration', models.CharField(blank=True, max_length=20)),
('Course_Logo', models.CharField(blank=True, max_length=50)),
('Course_StartDate', models.DateField(blank=True)),
('Course_EndDate', models.DateField(blank=True)),
('Course_Owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='myapp2.user_info')),
],
),
]
|
{"/myapp2/views.py": ["/myapp2/models.py"], "/myapp2/admin.py": ["/myapp2/models.py"]}
|
15,270,903
|
aswathyarun89/My-Smart-Class
|
refs/heads/master
|
/myapp2/migrations/0015_user_info_full_name.py
|
# Generated by Django 3.1.2 on 2021-03-01 16:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myapp2', '0014_course_student_map'),
]
operations = [
migrations.AddField(
model_name='user_info',
name='Full_Name',
field=models.CharField(blank=True, max_length=50),
),
]
|
{"/myapp2/views.py": ["/myapp2/models.py"], "/myapp2/admin.py": ["/myapp2/models.py"]}
|
15,270,904
|
aswathyarun89/My-Smart-Class
|
refs/heads/master
|
/myapp2/migrations/0005_course_info_user_cred.py
|
# Generated by Django 3.1.2 on 2020-12-21 16:21
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('myapp2', '0004_user_info'),
]
operations = [
migrations.CreateModel(
name='User_Cred',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('User_Type', models.CharField(max_length=10)),
('User_Id', models.CharField(max_length=30)),
('Password', models.CharField(max_length=20)),
('User_Reg_No', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='myapp2.user_info')),
],
),
migrations.CreateModel(
name='Course_Info',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Course_Id', models.BigIntegerField()),
('Course_Name', models.CharField(max_length=30)),
('Course_Descrp', models.CharField(max_length=200)),
('Course_Duration', models.CharField(max_length=20)),
('Course_Logo', models.CharField(max_length=50)),
('Course_StartDate', models.DateField()),
('Course_EndDate', models.DateField()),
('Course_Owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='myapp2.user_info')),
],
),
]
|
{"/myapp2/views.py": ["/myapp2/models.py"], "/myapp2/admin.py": ["/myapp2/models.py"]}
|
15,270,905
|
aswathyarun89/My-Smart-Class
|
refs/heads/master
|
/myapp2/migrations/0017_course_student_map.py
|
# Generated by Django 3.1.2 on 2021-03-02 23:59
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('myapp2', '0016_delete_course_student_map'),
]
operations = [
migrations.CreateModel(
name='Course_Student_Map',
fields=[
('CSM_Id', models.BigIntegerField(primary_key=True, serialize=False)),
('Assigned_Date', models.DateField(blank=True)),
('CSM_Status', models.CharField(blank=True, max_length=20)),
('Course_Progress', models.BigIntegerField()),
('Course_Id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='myapp2.course_info')),
('User_Reg_No', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='myapp2.user_info')),
],
),
]
|
{"/myapp2/views.py": ["/myapp2/models.py"], "/myapp2/admin.py": ["/myapp2/models.py"]}
|
15,270,906
|
aswathyarun89/My-Smart-Class
|
refs/heads/master
|
/myapp2/models.py
|
from django.db import models
# Create your models here.
class User_Info(models.Model):
User_Reg_No=models.BigIntegerField(primary_key = True)
User_Reg_Date=models.DateField()
User_Joining_Date=models.DateField()
First_Name=models.CharField(max_length=30)
Last_Name=models.CharField(max_length=30)
Full_Name=models.CharField(max_length=50,blank=True)
Date_Birth=models.DateField(blank=True)
Mobile_No=models.CharField(max_length=30)
Address=models.CharField(max_length=50)
Email=models.CharField(max_length=20)
Status=models.CharField(max_length=10)
User_Photo=models.CharField(max_length=50,blank=True)
Gender=models.CharField(max_length=6)
class User_Cred(models.Model):
User_Type=models.CharField(max_length=10)
User_Id=models.CharField(max_length=30)
Password=models.CharField(max_length=20)
User_Reg_No=models.ForeignKey(User_Info,on_delete=models.CASCADE)
class Course_Info(models.Model):
Course_Id=models.BigIntegerField(primary_key = True)
Course_Name=models.CharField(max_length=30)
Course_Descrp=models.CharField(max_length=200,blank=True)
Course_Duration=models.CharField(max_length=20,blank=True)
Course_Logo=models.CharField(max_length=50,blank=True)
Course_StartDate=models.DateField(blank=True)
Course_EndDate=models.DateField(blank=True)
Course_Owner=models.CharField(max_length=30)
Course_Owner_Id=models.ForeignKey(User_Info,on_delete=models.CASCADE)
class Course_Student_Map(models.Model):
CSM_Id=models.BigIntegerField(primary_key = True)
Course_Id=models.ForeignKey(Course_Info,on_delete=models.CASCADE)
User_Reg_No=models.ForeignKey(User_Info,on_delete=models.CASCADE)
Assigned_Date=models.DateField(blank=True)
CSM_Status=models.CharField(max_length=20,blank=True)
Course_Progress=models.BigIntegerField()
|
{"/myapp2/views.py": ["/myapp2/models.py"], "/myapp2/admin.py": ["/myapp2/models.py"]}
|
15,270,907
|
aswathyarun89/My-Smart-Class
|
refs/heads/master
|
/myapp2/migrations/0009_delete_course_info.py
|
# Generated by Django 3.1.2 on 2021-01-27 23:46
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('myapp2', '0008_auto_20210127_2338'),
]
operations = [
migrations.DeleteModel(
name='Course_Info',
),
]
|
{"/myapp2/views.py": ["/myapp2/models.py"], "/myapp2/admin.py": ["/myapp2/models.py"]}
|
15,270,908
|
aswathyarun89/My-Smart-Class
|
refs/heads/master
|
/myapp2/migrations/0018_auto_20210310_1501.py
|
# Generated by Django 3.1.2 on 2021-03-10 15:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myapp2', '0017_course_student_map'),
]
operations = [
migrations.AlterField(
model_name='user_info',
name='User_Photo',
field=models.CharField(blank=True, max_length=50, null=True),
),
]
|
{"/myapp2/views.py": ["/myapp2/models.py"], "/myapp2/admin.py": ["/myapp2/models.py"]}
|
15,270,909
|
aswathyarun89/My-Smart-Class
|
refs/heads/master
|
/myapp2/migrations/0003_auto_20201221_1616.py
|
# Generated by Django 3.1.2 on 2020-12-21 16:16
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('myapp2', '0002_user1'),
]
operations = [
migrations.DeleteModel(
name='user',
),
migrations.DeleteModel(
name='user1',
),
]
|
{"/myapp2/views.py": ["/myapp2/models.py"], "/myapp2/admin.py": ["/myapp2/models.py"]}
|
15,270,910
|
aswathyarun89/My-Smart-Class
|
refs/heads/master
|
/myapp2/views.py
|
from django.shortcuts import render,redirect
from .models import *
from random import random
from django.core.files.storage import FileSystemStorage
import datetime
from django.http.response import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.db.models import Q
from itertools import chain
from operator import attrgetter
from django.core import serializers
from django.db.models import Value as V
from django.db.models.functions import Concat
from django.db.models import Prefetch
import json
import collections
# Create your views here.
#Loading the home page
def myfunction(request):
return render(request, 'index.html')
#Admin Module starts
#Loading the admindashbaord
def dashboard(request):
if not request.session.get('iden_key', None):
return render(request,'index.html')
else:
v_profile=request.session['iden_key']
profile=User_Cred.objects.get(id=v_profile)
return render(request,'Administrator/Admindashboard.html',{'data':profile})
# Add/Update Instructor html starts
# Add update instructor html page
def addinstructor(request):
if not request.session.get('iden_key', None):
return render(request,'index.html')
else:
v_profile=request.session['iden_key']
profile=User_Cred.objects.get(id=v_profile)
# v_display=User_Cred.objects.filter(User_Type="Instructor")
# return render(request, 'Administrator/AddUpdateInstructor.html',{'data':profile,'display':v_display})
return render(request, 'Administrator/AddUpdateInstructor.html',{'data':profile})
# Add update instructor html page displaying the user details already added
def displaydataajfun(request):
v_display=User_Cred.objects.filter(User_Type="Instructor")
# a=User_Info.objects.all()
# data=[{'iden1':i.User_Reg_No,'iden2':i.First_Name,'iden3':i.Last_Name,'iden4':i.Email}for i in a]
data=[{'iden1':i.User_Reg_No.User_Reg_No,'iden2':i.User_Reg_No.First_Name,'iden3':i.User_Reg_No.Last_Name,'iden4':i.User_Reg_No.Email}for i in v_display]
return JsonResponse({'key':data})
# Add instructor form in Add update instructor html page(Admin module)
@csrf_exempt
def addinstructorform(request):
if request.POST.get('action')=='addinstructor':
name1 = request.POST.get('fir_name')
name2 = request.POST.get('l_name')
e_mail = request.POST.get('e_mail')
mob_no =request.POST.get('mob_no')
address1 = request.POST.get('post_ad')
user_name = request.POST.get('u_name')
password = request.POST.get('pass_word')
join_date = request.POST.get('user_join_date')
reg_date = datetime.datetime.now()
user_status = 'Active'
gender = request.POST.get('gender')
# Photo upload clode block - start
try:
myfile=request.FILES.get('ins_photo')
print(myfile)
except:
print("error and except block ran")
file_name= ''
else:
print("No error so ELSE block ran")
file_name=str(random())+myfile.name
fs=FileSystemStorage()
fs.save(file_name,myfile)
# Photo upload clode block - End
# Adding the User Registeration Number starts
try:
last_entry = User_Info.objects.latest('User_Reg_No')
except:
reg_No = 1000
else:
reg_No = last_entry.User_Reg_No+1
# Adding the User Registeration Number ends
User_Info_obj=User_Info(First_Name=name1,Last_Name=name2,Email=e_mail,Address=address1,User_Joining_Date=join_date,User_Reg_Date=reg_date,Status=user_status,Gender=gender,Mobile_No=mob_no,User_Reg_No=reg_No,User_Photo=file_name)
User_Info_obj.save()
obj=User_Info.objects.latest('User_Reg_No')
User_Cred_obj = User_Cred(User_Id=user_name,Password=password,User_Type='Instructor',User_Reg_No=obj)
User_Cred_obj.save()
return JsonResponse({'success':''})
# return render(request,'Administrator/AddUpdateInstructor.html')
# Add instructor form in Add update instructor html page(Admin module)
# Check if the username already exists
@csrf_exempt
def inputcheckfun(request):
y=request.POST['name']
try:
x= User_Cred.objects.get(User_Id=y)
return JsonResponse({'error':'Username already exists'})
except User_Cred.DoesNotExist:
return JsonResponse({'error':''})
# Search function in the admin module in(Add update instructor html page)
@csrf_exempt
def your_view(request):
if (request.method=="POST"):
v_profile=request.session['iden_key']
profile=User_Cred.objects.get(id=v_profile)
search_text=request.POST['name']
try:
records=User_Cred.objects.filter(User_Type="Instructor").select_related('User_Reg_No').filter(Q(User_Reg_No__First_Name__icontains=search_text)|Q(User_Reg_No__Last_Name__icontains=search_text)|Q(User_Reg_No__Email__iexact=search_text))
if records==[]:
return redirect('addins')
else:
data=[{'key1':i.User_Reg_No.User_Reg_No,'key2':i.User_Reg_No.First_Name,'key3':i.User_Reg_No.Last_Name,'key4':i.User_Reg_No.Email}for i in records]
return JsonResponse({'key_id':data})
# return render(request,'Administrator/AddUpdateInstructor.html',{'myitem':records,'data':profile})
except User_Info.DoesNotExist:
return redirect('addins')
else:
records = []
return render(request, 'Administrator/AddUpdateInstructor.html')
# Data view in Add update instructor html page
@csrf_exempt
def viewdataajfun(request):
v_view=request.POST['view_id']
single_data=User_Info.objects.get(User_Reg_No=v_view)
single_data_cred=User_Cred.objects.get(User_Reg_No=v_view)
data=[{'data1':single_data.User_Reg_No,'data2':single_data.First_Name,'data3':single_data.Last_Name,'data4':single_data.Email,'data5':single_data.Mobile_No,'data6':single_data.Address,'data7':single_data.Status,'data8':single_data.User_Joining_Date,'data9':single_data.User_Photo}]
data_cred=[{'data_cred_1':single_data_cred.User_Id,'data_cred_2':single_data_cred.Password,'data_cred_3':single_data_cred.User_Type}]
return JsonResponse({'key':data,'key1':data_cred})
# Data upate in Add update instructor html page starts in admin module
@csrf_exempt
def update_ajfun(request):
v_updateid=request.POST['update_id']
v_first_name = request.POST['f_name']
print(v_first_name)
v_last_name = request.POST['l_name']
v_email = request.POST['e_mail']
v_mob_no = request.POST['mob_no']
v_address = request.POST['post_ad']
reg_date = datetime.datetime.now()
v_password = request.POST['p_word']
v_status = request.POST['u_status']
v_joining_date = request.POST['user_join_date']
User_Info.objects.filter(User_Reg_No=v_updateid).update(First_Name=v_first_name,Last_Name=v_last_name,Email=v_email,Mobile_No=v_mob_no,Address=v_address,Status=v_status,User_Joining_Date=v_joining_date,User_Reg_Date=reg_date)
User_Cred.objects.filter(User_Reg_No=v_updateid).update(Password=v_password)
return JsonResponse({'key_update':'Update successfully completed! Click on OK to continue'})
# Add/Update Instructor html ends
# Add/Update Student html starts
# Add update student html page in admin module(only loading the page)
def addstudent(request):
if not request.session.get('iden_key', None):
return render(request,'index.html')
else:
v_profile=request.session['iden_key']
profile=User_Cred.objects.get(id=v_profile)
return render(request, 'Administrator/AddUpdateStudent.html',{'data':profile})
# Add update instructor html page displaying the student details already added
def displaystudentdataajfun(request):
v_display=User_Cred.objects.filter(User_Type="Student")
studentdata=[{'s_data1':i.User_Reg_No.User_Reg_No,'s_data2':i.User_Reg_No.First_Name,'s_data3':i.User_Reg_No.Last_Name,'s_data4':i.User_Reg_No.Email,}for i in v_display]
return JsonResponse({'s_data':studentdata})
# Add student form in Add update instructor html page(Admin module)
@csrf_exempt
def studentformfun(request):
if request.POST.get('action')=='addstudent':
v_fname = request.POST.get('f_name')
v_lname = request.POST.get('l_name')
v_e_mail = request.POST.get('e_mail')
v_mob_no = request.POST.get('mob_no')
v_address1 = request.POST.get('post_ad')
v_user_name = request.POST.get('u_name')
v_password = request.POST.get('pass_word')
v_join_date = request.POST.get('user_join_date')
v_reg_date = datetime.datetime.now()
v_user_status = 'Active'
v_gender = request.POST.get('gender')
# Photo upload clode block - start
try:
myfile=request.FILES.get('stu_photo')
except:
file_name= ''
else:
file_name=str(random())+myfile.name
fs=FileSystemStorage()
fs.save(file_name,myfile)
# Photo upload clode block - End
try:
lastentry = User_Info.objects.latest('User_Reg_No')
except:
v_reg_No = 1000
else:
v_reg_No = lastentry.User_Reg_No+1
User_Info_obj_stu=User_Info(First_Name=v_fname,Last_Name=v_lname,Email=v_e_mail,Address=v_address1,User_Joining_Date=v_join_date,User_Reg_Date=v_reg_date,Status=v_user_status,Gender=v_gender,Mobile_No=v_mob_no,User_Reg_No=v_reg_No,User_Photo=file_name)
User_Info_obj_stu.save()
obj_stu=User_Info.objects.latest('User_Reg_No')
User_Cred_obj_stu = User_Cred(User_Id=v_user_name,Password=v_password,User_Type='Student',User_Reg_No=obj_stu)
User_Cred_obj_stu.save()
return JsonResponse({'success':''})
# Check if the username already exists
@csrf_exempt
def stu_form_inputcheckfun(request):
y=request.POST['name']
try:
x= User_Cred.objects.get(User_Id=y)
return JsonResponse({'error':'Username already exists'})
except User_Cred.DoesNotExist:
return JsonResponse({'error':''})
#search functionality in Add/Update Student.html in Admin Module
@csrf_exempt
def searchstudentfunction(request):
if(request.method=="POST"):
search_student=request.POST['search_name']
try:
# records=User_Cred.objects.filter(User_Type="Instructor").select_related('User_Reg_No').filter(Q(User_Reg_No__First_Name__icontains=search_text)|Q(User_Reg_No__Last_Name__icontains=search_text)|Q(User_Reg_No__Email__iexact=search_text))
Student_search_data=User_Cred.objects.filter(User_Type="Student").select_related('User_Reg_No').filter(Q(User_Reg_No__First_Name__icontains=search_student)|Q(User_Reg_No__Last_Name__icontains=search_student)|Q(User_Reg_No__Email__iexact=search_student))
if Student_search_data==[]:
return redirect('addstu')
else:
data=[{'data1':i.User_Reg_No.User_Reg_No,'data2':i.User_Reg_No.First_Name,'data3':i.User_Reg_No.Last_Name,'data4':i.User_Reg_No.Email}for i in Student_search_data]
return JsonResponse({'stukey':data})
except User_Info.DoesNotExist:
return redirect('addstu')
else:
Student_search_data=[]
return render(request, 'Administrator/AddUpdateStudent.html')
# Add/Update Student html page Edit functionality- Viewing Single data
@csrf_exempt
def viewstudentdatafunction(request):
view_stu_id=request.POST['s_view_id']
stu_single_data_Info=User_Info.objects.get(User_Reg_No=view_stu_id)
stu_single_data_cred=User_Cred.objects.get(User_Reg_No=view_stu_id)
stu_data_info=[{'data1':stu_single_data_Info.User_Reg_No,'data2':stu_single_data_Info.First_Name,'data3':stu_single_data_Info.Last_Name,'data4':stu_single_data_Info.Email,'data5':stu_single_data_Info.Mobile_No,'data6':stu_single_data_Info.Address,'data7':stu_single_data_Info.Status,'data8':stu_single_data_Info.User_Joining_Date,'data9':stu_single_data_Info.User_Photo}]
stu_data_cred=[{'data_cred_1':stu_single_data_cred.User_Id,'data_cred_2':stu_single_data_cred.Password,'data_cred_3':stu_single_data_cred.User_Type}]
return JsonResponse({'key_info':stu_data_info,'key_cred':stu_data_cred})
# Add/Update Student html page Edit functionality- Updating Single data
@csrf_exempt
def updatestudentdatafunction(request):
v_updateid=request.POST['student_update_id']
v_first_name = request.POST['f_name']
print(v_first_name)
v_last_name = request.POST['l_name']
v_email = request.POST['e_mail']
v_mob_no = request.POST['mob_no']
v_address = request.POST['post_ad']
reg_date = datetime.datetime.now()
v_password = request.POST['p_word']
v_status = request.POST['u_status']
v_joining_date = request.POST['user_join_date']
User_Info.objects.filter(User_Reg_No=v_updateid).update(First_Name=v_first_name,Last_Name=v_last_name,Email=v_email,Mobile_No=v_mob_no,Address=v_address,Status=v_status,User_Joining_Date=v_joining_date,User_Reg_Date=reg_date)
User_Cred.objects.filter(User_Reg_No=v_updateid).update(Password=v_password)
return JsonResponse({'key_stu_update':'Update successfully completed! Click on OK to continue'})
# Add/Update Student html ends
# Create Update Course html page in admin module
def createcourse(request):
if not request.session.get('iden_key', None):
return render(request,'index.html')
else:
v_profile=request.session['iden_key']
profile=User_Cred.objects.get(id=v_profile)
course_owner_name=User_Cred.objects.filter(User_Type="Instructor").prefetch_related(Prefetch('User_Reg_No',queryset=User_Info.objects.annotate(full_name=Concat('First_Name', V(' '),'Last_Name'))))
course_student_name = User_Cred.objects.filter(User_Type="Student").prefetch_related(Prefetch('User_Reg_No',queryset=User_Info.objects.annotate(full_name=Concat('First_Name', V(' '),'Last_Name'))))
return render(request, 'Administrator/CreateCourses.html',{'data':profile,'selectedvalue':course_owner_name,'c_student_name':course_student_name})
# Display the course details for which the course owners are Instructors
def coursedataajfun(request):
course_data=Course_Info.objects.all().select_related('Course_Owner_Id')
data=[{'iden1':i.Course_Id,'iden2':i.Course_Name,'iden3':i.Course_Duration,'iden4':i.Course_Owner}for i in course_data]
return JsonResponse({'key':data})
# Add course form in Add update instructor html page(Admin module)
@csrf_exempt
def addcourseform(request):
print('Error Checking')
if request.POST.get('action')=='createcourse':
print('Error Checking')
course_name = request.POST.get('crs_name')
course_owner_name= request.POST.get('crs_owner')
course_owner=course_owner_name.split(' ')[0]
print(course_owner)
course_duration = request.POST.get('crs_duration')
print(course_duration)
course_details = request.POST.get('crs_details')
course_start_date=request.POST.get('crs_startdate')
course_end_date=request.POST.get('crs_enddate')
course_myfile=request.FILES.get('crs_logopic')
course_file_name=str(random())+course_myfile.name
fs=FileSystemStorage()
fs.save(course_file_name,course_myfile)
obj1=User_Info.objects.get(First_Name=course_owner)
Course_Info_obj=Course_Info(Course_Owner_Id=obj1,Course_Name=course_name,Course_Owner=course_owner,Course_Duration=course_duration,Course_Descrp=course_details,Course_StartDate=course_start_date,Course_EndDate=course_end_date,Course_Logo=course_file_name)
Course_Info_obj.save()
return JsonResponse({'success':''})
# Search function in the admin module in(Create/Update course html page)
@csrf_exempt
def searchcourse(request):
if (request.method=="POST"):
v_profile=request.session['iden_key']
profile=User_Cred.objects.get(id=v_profile)
search_text=request.POST['name']
try:
c_data=Course_Info.objects.filter(Q(Course_Name__icontains=search_text)|Q(Course_Id__icontains=search_text))
if c_data==[]:
return redirect('createcourse')
else:
data=[{'key1':i.Course_Id,'key2':i.Course_Name,'key3':i.Course_Duration,'key4':i.Course_Owner}for i in c_data]
return JsonResponse({'key_course':data})
except User_Info.DoesNotExist:
return redirect('addins')
else:
c_data = []
return render(request, 'Administrator/AddUpdateInstructor.html')
@csrf_exempt
def viewcoursedataajfun(request):
v_view=request.POST['view_id']
# v_courseid=request.POST['cid']
single_data=Course_Info.objects.get(Course_Id=v_view)
# course_owner_name=User_Cred.objects.filter(User_Type="Instructor").prefetch_related(Prefetch('User_Reg_No',queryset=User_Info.objects.annotate(full_name=Concat('First_Name', V(' '),'Last_Name'))))
csm_obj=Course_Student_Map.objects.filter(Course_Id=v_view)
CourseDetails=[{'data1':single_data.Course_Id,'data2':single_data.Course_Name,'data3':single_data.Course_Owner,'data4':single_data.Course_Duration,'data5':single_data.Course_Descrp,'data6':single_data.Course_Logo}]
csm_table_data=[{'td1':x.User_Reg_No_id,'td2':x.User_Reg_No.First_Name,'td3':x.User_Reg_No.Last_Name}for x in csm_obj]
print(csm_obj)
return JsonResponse({'key_course':CourseDetails,'table_key':csm_table_data})
# return JsonResponse({'key_course':CourseDetails})
@csrf_exempt
def assign_student(request):
try:
CSM_Id_last_entry = Course_Student_Map.objects.latest('CSM_Id')
except:
csmid = 101
else:
csmid = CSM_Id_last_entry.CSM_Id+1
crs_id=request.POST.get('c_id')
crs_student_id=request.POST['stu_id']
crs_assigned_date = datetime.datetime.now()
crs_status="Assigned"
crs_progress=0
try:
verify=Course_Student_Map.objects.get(Course_Id=crs_id,User_Reg_No=crs_student_id)
print(verify)
except:
course_info_pk=Course_Info.objects.get(Course_Id=crs_id)
user_info_pk=User_Info.objects.get(User_Reg_No=crs_student_id)
Course_Student_Map_Obj=Course_Student_Map(CSM_Id=csmid,Course_Id_id=course_info_pk.Course_Id,User_Reg_No_id=user_info_pk.User_Reg_No,Assigned_Date=crs_assigned_date,CSM_Status=crs_status,Course_Progress=crs_progress)
Course_Student_Map_Obj.save()
return JsonResponse({'alert':'Data Sucessfully added','Ref_crsid':crs_id})
else:
return JsonResponse({'alert':'Student already added'})
# instructor calendar page in admin module
def instructorcalendar(request):
if not request.session.get('iden_key', None):
return render(request,'index.html')
else:
v_profile=request.session['iden_key']
profile=User_Cred.objects.get(id=v_profile)
course_data=Course_Info.objects.all()
return render(request, 'Administrator/InstructorCalender.html',{'data':profile,'course_display':course_data})
#Admin Module End
# Instructor Module starts
# Loading the instructor dashboard
def instructordashboard(request):
if not request.session.get('iden_key', None):
return render(request,'index.html')
else:
v_profile=request.session['iden_key']
profile=User_Cred.objects.get(id=v_profile)
return render(request,'Instructor/InstructorDashboard.html',{'data':profile})
# Add Student form in Instructor module
def addstudentinspage(request):
if not request.session.get('iden_key', None):
return render(request,'index.html')
else:
v_profile=request.session['iden_key']
profile=User_Cred.objects.get(id=v_profile)
return render(request, 'Instructor/AddUpdateStudent.html',{'data':profile})
#Loding the createcourse page in instructor module
def createcourseinspage(request):
if not request.session.get('iden_key', None):
return render(request,'index.html')
else:
v_profile=request.session['iden_key']
profile=User_Cred.objects.get(id=v_profile)
course_owner_name=User_Cred.objects.filter(User_Type="Instructor").prefetch_related(Prefetch('User_Reg_No',queryset=User_Info.objects.annotate(full_name=Concat('First_Name', V(' '),'Last_Name'))))
course_student_name = User_Cred.objects.filter(User_Type="Student").prefetch_related(Prefetch('User_Reg_No',queryset=User_Info.objects.annotate(full_name=Concat('First_Name', V(' '),'Last_Name'))))
return render(request, 'Instructor/CreateCourses.html',{'data':profile,'selectedvalue':course_owner_name,'c_student_name':course_student_name})
def instructorcalendarinspage(request):
return render(request, 'Instructor/InstructorCalender.html')
def assignedcoursesins(request):
return render(request, 'Instructor/ViewAssignedCourses.html')
def scheduleclass(request):
return render(request, 'Instructor/ScheduleStartClass.html')
def assignments(request):
return render(request, 'Instructor/Assignments.html')
def assessments(request):
return render(request, 'Instructor/Assesments.html')
def documents(request):
return render(request, 'Instructor/UploadDocuments.html')
def certificate(request):
return render(request, 'Instructor/Certificate.html')
# Student Module
def viewstudentcourse(request):
return render(request, 'Student/ViewMyCourse.html')
def studentassignment(request):
return render(request, 'Student/Assignments.html')
def studentassessment(request):
return render(request, 'Student/Assessments.html')
def studentcertificate(request):
return render(request, 'Student/Certificate.html')
# Login Function
def loginfun(request):
if(request.method=="POST"):
user_name=request.POST['username']
password=request.POST['password']
try:
x= User_Cred.objects.get(User_Id=user_name)
if (x.User_Id==user_name and x.Password==password):
request.session['iden_key']=x.id
if(x.User_Type=='Admin'):
return redirect('admindashboard/')
elif(x.User_Type=='Instructor'):
return redirect('insdashboard/')
else:
return redirect('studashboard/')
else:
return render(request,'index.html',{'error':'Incorrect Username or Password'})
except User_Cred.DoesNotExist:
return render(request,'index.html',{'error':'Incorrect Username or Password'})
else:
return render(request,'index.html')
# Session function
def studentdashboard(request):
if not request.session.get('iden_key', None):
return render(request,'index.html')
else:
v_profile=request.session['iden_key']
profile=User_Cred.objects.get(id=v_profile)
return render(request,'Student/StudentDashboard.html',{'data':profile})
# Logout function
def logoutfun(request):
if not request.session.get('iden_key', None):
return render(request,'index.html')
else:
del request.session['iden_key']
return render(request,'index.html')
|
{"/myapp2/views.py": ["/myapp2/models.py"], "/myapp2/admin.py": ["/myapp2/models.py"]}
|
15,270,911
|
aswathyarun89/My-Smart-Class
|
refs/heads/master
|
/myapp2/migrations/0006_user_info_gender.py
|
# Generated by Django 3.1.2 on 2020-12-22 14:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myapp2', '0005_course_info_user_cred'),
]
operations = [
migrations.AddField(
model_name='user_info',
name='Gender',
field=models.CharField(default='male', max_length=6),
preserve_default=False,
),
]
|
{"/myapp2/views.py": ["/myapp2/models.py"], "/myapp2/admin.py": ["/myapp2/models.py"]}
|
15,270,912
|
aswathyarun89/My-Smart-Class
|
refs/heads/master
|
/myapp2/migrations/0011_delete_course_info.py
|
# Generated by Django 3.1.2 on 2021-01-27 23:56
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('myapp2', '0010_course_info'),
]
operations = [
migrations.DeleteModel(
name='Course_Info',
),
]
|
{"/myapp2/views.py": ["/myapp2/models.py"], "/myapp2/admin.py": ["/myapp2/models.py"]}
|
15,270,913
|
aswathyarun89/My-Smart-Class
|
refs/heads/master
|
/myapp2/migrations/0023_auto_20210322_1705.py
|
# Generated by Django 3.1.2 on 2021-03-22 17:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myapp2', '0022_auto_20210310_1626'),
]
operations = [
migrations.AlterField(
model_name='user_info',
name='Mobile_No',
field=models.CharField(max_length=30),
),
]
|
{"/myapp2/views.py": ["/myapp2/models.py"], "/myapp2/admin.py": ["/myapp2/models.py"]}
|
15,270,914
|
aswathyarun89/My-Smart-Class
|
refs/heads/master
|
/myapp2/migrations/0008_auto_20210127_2338.py
|
# Generated by Django 3.1.2 on 2021-01-27 23:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myapp2', '0007_auto_20201223_0909'),
]
operations = [
migrations.RemoveField(
model_name='course_info',
name='id',
),
migrations.AlterField(
model_name='course_info',
name='Course_Descrp',
field=models.CharField(blank=True, max_length=200),
),
migrations.AlterField(
model_name='course_info',
name='Course_Duration',
field=models.CharField(blank=True, max_length=20),
),
migrations.AlterField(
model_name='course_info',
name='Course_EndDate',
field=models.DateField(blank=True),
),
migrations.AlterField(
model_name='course_info',
name='Course_Id',
field=models.BigIntegerField(primary_key=True, serialize=False),
),
migrations.AlterField(
model_name='course_info',
name='Course_Logo',
field=models.CharField(blank=True, max_length=50),
),
migrations.AlterField(
model_name='course_info',
name='Course_StartDate',
field=models.DateField(blank=True),
),
]
|
{"/myapp2/views.py": ["/myapp2/models.py"], "/myapp2/admin.py": ["/myapp2/models.py"]}
|
15,270,915
|
aswathyarun89/My-Smart-Class
|
refs/heads/master
|
/myapp2/admin.py
|
from django.contrib import admin
# Register your models here.
from .models import *
admin.site.register(User_Info)
admin.site.register(User_Cred)
admin.site.register(Course_Info)
|
{"/myapp2/views.py": ["/myapp2/models.py"], "/myapp2/admin.py": ["/myapp2/models.py"]}
|
15,270,916
|
aswathyarun89/My-Smart-Class
|
refs/heads/master
|
/myapp2/migrations/0021_auto_20210310_1623.py
|
# Generated by Django 3.1.2 on 2021-03-10 16:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myapp2', '0020_auto_20210310_1617'),
]
operations = [
migrations.AlterField(
model_name='user_info',
name='User_Photo',
field=models.CharField(blank=True, default='', max_length=50),
),
]
|
{"/myapp2/views.py": ["/myapp2/models.py"], "/myapp2/admin.py": ["/myapp2/models.py"]}
|
15,270,917
|
aswathyarun89/My-Smart-Class
|
refs/heads/master
|
/myapp2/migrations/0004_user_info.py
|
# Generated by Django 3.1.2 on 2020-12-21 16:18
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('myapp2', '0003_auto_20201221_1616'),
]
operations = [
migrations.CreateModel(
name='User_Info',
fields=[
('User_Reg_No', models.BigIntegerField(primary_key=True, serialize=False)),
('User_Reg_Date', models.DateField()),
('User_Joining_Date', models.DateField()),
('First_Name', models.CharField(max_length=30)),
('Last_Name', models.CharField(max_length=30)),
('Date_Birth', models.DateField()),
('Mobile_No', models.BigIntegerField()),
('Address', models.CharField(max_length=50)),
('Email', models.CharField(max_length=20)),
('Status', models.CharField(max_length=10)),
('User_Photo', models.CharField(max_length=50)),
],
),
]
|
{"/myapp2/views.py": ["/myapp2/models.py"], "/myapp2/admin.py": ["/myapp2/models.py"]}
|
15,270,918
|
aswathyarun89/My-Smart-Class
|
refs/heads/master
|
/myapp2/urls.py
|
from django.urls import path
from . import views
urlpatterns = [
# Loading the index page
path('',views.myfunction,name="pgm"),
# Login form
path('loginform',views.loginfun,name='loginform'),
# Logout form
path('logout',views.logoutfun,name="logout"),
# Admin Module Path starts
# Loading the admindashbaord html page
path('admindashboard/',views.dashboard,name="admindashboard"),
# Add/Update Instructor html page begins
# Add/Update Instructor html page with displaying the page except the Userdetails
path('addins/',views.addinstructor,name="addins"),
# Add/Update Instructor html page with displaying the page with userdetails
path('addins/dis_data_addins',views.displaydataajfun,name="dis_data_addins"),
# Add/Update Instructor html page with adding a new instructor
path('addins/insformsubmit',views.addinstructorform,name="insformsubmit"),
# Check if the username already exists for AddInstructor form
path('addins/inputcheck',views.inputcheckfun,name="inputcheck"),
# Search functionality in Add/Update Instructor page
path('addins/exact_url',views.your_view,name="exact_url"),
# Data displayed in Add/Update Instructor page for edit/update functionality
path('addins/view_data_aj',views.viewdataajfun,name="view_data_aj"),
# Update functionality in Add/Update Instructor page
path('addins/update_aj',views.update_ajfun,name="update_aj"),
# Add/Update Instructor html page Ends
# Add/Update Student html page begins
# Add/Update Student html page with displaying the page except the Student details
path('addstu/',views.addstudent,name="addstu"),
# Add/Update Student html page with displaying the page with student details
path('addstu/display_studentdata',views.displaystudentdataajfun,name="display_studentdata"),
# Add Student form in Admin module
path('addstu/stuformsubmit',views.studentformfun,name="stuformsubmit"),
# Check if the username already exists for AdddStudent form
path('addstu/inputcheck',views.stu_form_inputcheckfun,name="inputcheck"),
# Search Student functionality in Admin Module
path('addstu/searchstudent',views.searchstudentfunction,name="searchstudent"),
# View Student data in Admin Module
path('addstu/viewstudentdata_aj',views.viewstudentdatafunction,name="viewstudentdata_aj"),
# Update Student data in Admin Module
path('addstu/updatestudent_aj',views.updatestudentdatafunction,name="updatestudent_aj"),
# Add/Update Student html page ends
# Add/Update Course html page starts
# Add/Update Course html page with displaying the page except the course details
path('createcourse/',views.createcourse,name="createcourse"),
# Display Course data in Add/Update Course html page in Admin Module
path('createcourse/dis_data_createcourse',views.coursedataajfun,name="dis_data_createcourse"),
# Add Course form in Admin module
path('createcourse/addcrsform',views.addcourseform,name="addcrsform"),
# Search functionality in Add/Update Course html page
path('createcourse/search_course',views.searchcourse,name="search_course"),
# Data displayed in Create/Update Course page for edit/update functionality
path('createcourse/view_course_data_aj',views.viewcoursedataajfun,name="view_course_data_aj"),
# Assign student to course in Add/Update Course html page
path('createcourse/assign_student_csm',views.assign_student,name="assign_student_csm"),
# Add/Update Course html page ends
# View Instructor calender starts in Admin Module starts
# Loading the instructor calender in Admin Module
path('inscal',views.instructorcalendar,name="inscal"),
# Admin Module Path Ends
# Instructor Module path starts
# Instructor dashboard in Instructor module
path('insdashboard/', views.instructordashboard, name='insdashboard'),
# Add/Update Student html page in Instructor Module starts
# Add/Update Student html page with displaying the page except the studentdetails in Instructor Module
path('addstuins/',views.addstudentinspage,name="addstuins"),
# Add/Update InstrStudentuctor html page with displaying the page with studentdetails Instructor Module
path('addstuins/display_studentdata',views.displaystudentdataajfun,name="display_studentdata"),
# Add Student form in Instructor module
path('addstuins/stuformsubmit',views.studentformfun,name="stuformsubmit"),
# Check if the username already exists for AdddStudent form
path('addstuins/inputcheck',views.stu_form_inputcheckfun,name="inputcheck"),
# Search functionality in Add/Update Student page in Instructor Module
path('addstuins/searchstudent',views.searchstudentfunction,name="searchstudent"),
# View Student data in Instructor Module
path('addstuins/viewstudentdata_aj',views.viewstudentdatafunction,name="viewstudentdata_aj"),
# Update Student data in Instructor Module
path('addstuins/updatestudent_aj',views.updatestudentdatafunction,name="updatestudent_aj"),
# Add/Update Student html page in Instructor Module ends
# Create Course html page in Instructor Module Starts
#Loding the createcourse page in instructor module
path('createcourseins/',views.createcourseinspage,name="createcourseins"),
# Display Course data in Add/Update Course html page in Admin Module
path('createcourseins/dis_data_createcourse',views.coursedataajfun,name="dis_data_createcourse"),
# Add Course form in Admin module
path('createcourseins/addcrsform',views.addcourseform,name="addcrsform"),
# Search functionality in Add/Update Course html page
path('createcourseins/search_course',views.searchcourse,name="search_course"),
# Data displayed in Create/Update Course page for edit/update functionality
path('createcourseins/view_course_data_aj',views.viewcoursedataajfun,name="view_course_data_aj"),
# Assign student to course in Add/Update Course html page
path('createcourseins/assign_student_csm',views.assign_student,name="assign_student_csm"),
# Add/Update Course html page in Instructor Module ends
path('inscalins/',views.instructorcalendarinspage,name="inscalins"),
path('viewassigncourse/',views.assignedcoursesins,name="viewassigncourse"),
path('scheclass/',views.scheduleclass,name="scheclass"),
path('asgmt/',views.assignments,name="asgmt"),
path('assesmt/',views.assessments,name="assesmt"),
path('document/',views.documents,name="document"),
path('cert/',views.certificate,name="cert"),
# Student Module Path
path('studashboard/',views.studentdashboard,name="studashboard"),
path('stucourse/',views.viewstudentcourse,name="stucourse"),
path('stuassignments/',views.studentassignment,name="stuassignments"),
path('stuassessments/',views.studentassessment,name="stuassessments"),
path('stucertificate/',views.studentcertificate,name="stucertificate"),
# Login Function
]
|
{"/myapp2/views.py": ["/myapp2/models.py"], "/myapp2/admin.py": ["/myapp2/models.py"]}
|
15,270,919
|
aswathyarun89/My-Smart-Class
|
refs/heads/master
|
/myapp2/migrations/0022_auto_20210310_1626.py
|
# Generated by Django 3.1.2 on 2021-03-10 16:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myapp2', '0021_auto_20210310_1623'),
]
operations = [
migrations.AlterField(
model_name='user_info',
name='User_Photo',
field=models.CharField(blank=True, max_length=50),
),
]
|
{"/myapp2/views.py": ["/myapp2/models.py"], "/myapp2/admin.py": ["/myapp2/models.py"]}
|
15,270,920
|
aswathyarun89/My-Smart-Class
|
refs/heads/master
|
/myapp2/migrations/0020_auto_20210310_1617.py
|
# Generated by Django 3.1.2 on 2021-03-10 16:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myapp2', '0019_auto_20210310_1602'),
]
operations = [
migrations.AlterField(
model_name='user_info',
name='User_Photo',
field=models.CharField(max_length=50, null=True),
),
]
|
{"/myapp2/views.py": ["/myapp2/models.py"], "/myapp2/admin.py": ["/myapp2/models.py"]}
|
15,283,681
|
shreyasrye/Premier-Soccer-Leaderboard-Tracker
|
refs/heads/main
|
/website/blog/models.py
|
from django.db import models
from django.contrib.auth.models import User
class Team(models.Model):
name = models.CharField(max_length=100)
creater = models.ForeignKey(User, on_delete=models.CASCADE)
code = models.CharField(max_length=100)
def __str__(self):
return self.name
class League(models.Model):
name = models.CharField(max_length=100)
creater = models.ForeignKey(User, on_delete=models.CASCADE)
code = models.CharField(max_length=100)
def __str__(self):
return self.name
class UserTeams:
user = models.ForeignKey(user, on_delete=models.CASCADE)
team = models.ForeignKey(Team, on_delete=models.CASCADE)
|
{"/website/blog/admin.py": ["/website/blog/models.py"], "/website/blog/views.py": ["/website/blog/models.py"]}
|
15,308,640
|
sshmudio/dg
|
refs/heads/main
|
/plow/addons/f.py
|
import os
import subprocess
import sys
RED = ("\033[31m", "\033[0m")
def open_image(directory, image):
answer = input(
"Would you like to open the image of the computed passport file? [y] / n : ").lower()
if answer in ("y", "yes") or answer == "":
try:
# TODO: Test abspath() on Windows
image_path = os.path.join(
os.pardir, os.pardir, "docs", "images", directory, image)
print(image_path)
if sys.platform.startswith('darwin'):
subprocess.call(('open', image_path))
elif os.name == 'nt':
os.startfile(image_path)
elif os.name == 'posix':
subprocess.call(('xdg-open', image_path))
except Exception:
print(
"%s- An unexpected error occurred. The file could not be opened%s" % RED)
for msg in sys.exc_info():
print("\033[31m!", str(msg))
elif answer in ("n", "no"):
exit()
else:
print("%sInvalid response%s" % RED)
open_image(directory, image)
def parent_dir():
return os.path.dirname(__file__).replace("examples/functions", "")
|
{"/request_da/request_data.py": ["/plow/plow.py", "/plow/rand_let.py", "/source_podliver/settings.py"], "/indigo/admin.py": ["/cfdns/models.py", "/dolphin/models.py", "/farming/models.py", "/fbprofiles/models.py", "/idgenerator/models.py", "/indigo/models.py"], "/idgenerator/views.py": ["/idgenerator/forms.py", "/request_da/request_data.py", "/plow/plow.py", "/idgenerator/models.py"], "/dolphin/tasks.py": ["/dolphin/models.py"], "/indigo/tasks.py": ["/indigo/models.py"], "/idgenerator/forms.py": ["/idgenerator/models.py"], "/cfdns/tasks.py": ["/cfdns/models.py"], "/idgenerator/urls.py": ["/idgenerator/views.py"]}
|
15,308,641
|
sshmudio/dg
|
refs/heads/main
|
/plow/addons/p.py
|
import cv2
image_path = "input/asd.jpg"
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
image = cv2.imread(image_path)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(10, 10)
)
faces_detected = format(len(faces)) + " faces detected!"
print(faces_detected)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (255, 255, 0), 2)
viewImage(image, faces_detected)
|
{"/request_da/request_data.py": ["/plow/plow.py", "/plow/rand_let.py", "/source_podliver/settings.py"], "/indigo/admin.py": ["/cfdns/models.py", "/dolphin/models.py", "/farming/models.py", "/fbprofiles/models.py", "/idgenerator/models.py", "/indigo/models.py"], "/idgenerator/views.py": ["/idgenerator/forms.py", "/request_da/request_data.py", "/plow/plow.py", "/idgenerator/models.py"], "/dolphin/tasks.py": ["/dolphin/models.py"], "/indigo/tasks.py": ["/indigo/models.py"], "/idgenerator/forms.py": ["/idgenerator/models.py"], "/cfdns/tasks.py": ["/cfdns/models.py"], "/idgenerator/urls.py": ["/idgenerator/views.py"]}
|
15,308,642
|
sshmudio/dg
|
refs/heads/main
|
/plow/addons/s.py
|
from PIL import Image, ImageDraw, ImageFont
label = 'PT99399239'
font = ImageFont.truetype('PRFW.TTF', 120)
line_height = sum(font.getmetrics()) # в нашем случае 33 + 8 = 41
fontimage = Image.new('L', (font.getsize(label)[0], line_height))
# И рисуем на ней белый текст
ImageDraw.Draw(fontimage).text((0, 0), label, fill=255, font=font)
fontimage = fontimage.rotate(90, resample=Image.BICUBIC, expand=True)
orig = Image.open('ukraine_inernational.jpg')
orig.paste((41, 37, 43), box=(30, 180), mask=fontimage)
orig.show()
|
{"/request_da/request_data.py": ["/plow/plow.py", "/plow/rand_let.py", "/source_podliver/settings.py"], "/indigo/admin.py": ["/cfdns/models.py", "/dolphin/models.py", "/farming/models.py", "/fbprofiles/models.py", "/idgenerator/models.py", "/indigo/models.py"], "/idgenerator/views.py": ["/idgenerator/forms.py", "/request_da/request_data.py", "/plow/plow.py", "/idgenerator/models.py"], "/dolphin/tasks.py": ["/dolphin/models.py"], "/indigo/tasks.py": ["/indigo/models.py"], "/idgenerator/forms.py": ["/idgenerator/models.py"], "/cfdns/tasks.py": ["/cfdns/models.py"], "/idgenerator/urls.py": ["/idgenerator/views.py"]}
|
15,308,643
|
sshmudio/dg
|
refs/heads/main
|
/plow/addons/bg.py
|
from PIL import Image
# Create an Image Object from an Image
im = Image.open("input/s.png")
# Display actual image
im.show()
# Make the new image half the width and half the height of the original image
resized_im = im.resize((round(im.size[0]*0.5), round(im.size[1]*0.5)))
# Display the resized imaged
resized_im.show()
# Save the cropped image
resized_im.save('resizedBeach1.jpg')
|
{"/request_da/request_data.py": ["/plow/plow.py", "/plow/rand_let.py", "/source_podliver/settings.py"], "/indigo/admin.py": ["/cfdns/models.py", "/dolphin/models.py", "/farming/models.py", "/fbprofiles/models.py", "/idgenerator/models.py", "/indigo/models.py"], "/idgenerator/views.py": ["/idgenerator/forms.py", "/request_da/request_data.py", "/plow/plow.py", "/idgenerator/models.py"], "/dolphin/tasks.py": ["/dolphin/models.py"], "/indigo/tasks.py": ["/indigo/models.py"], "/idgenerator/forms.py": ["/idgenerator/models.py"], "/cfdns/tasks.py": ["/cfdns/models.py"], "/idgenerator/urls.py": ["/idgenerator/views.py"]}
|
15,308,644
|
sshmudio/dg
|
refs/heads/main
|
/request_da/request_data.py
|
import json
from plow.plow import *
from pathlib import Path
from source_podliver.settings import MEDIA_ROOT
import random
def get_data_from_form(date_form):
typedoc = date_form['typedoc']
country = date_form['country']
surname = date_form['surname']
given_name = date_form['given_name']
passport_number = date_form['passport_number']
genre = date_form['genre']
nationality = date_form['nationality']
birth_date = date_form['birth_date']
personal_number = date_form['personal_number']
locations = date_form['locations']
id_number = date_form['id_number']
data_start = date_form['data_start']
exp_date = date_form['exp_date']
issuing = date_form['issuing']
pasport_photo_path = date_form['photo_doc']
mrz = TD3CodeGenerator(typedoc, country, surname, given_name, passport_number, nationality, birth_date, genre, exp_date, id_number,
dictionary.cyrillic_ukrainian())
print(mrz)
save_after_main_data_p = write_main_data(
mrz, 'media/cfg/tmp/after_m_data.png', typedoc, country, id_number, surname, given_name, genre, birth_date)
print(save_after_main_data_p)
write_id_path = write_id(save_after_main_data_p, passport_number)
print(write_id_path)
print(pasport_photo_path)
done_image = f'media/cfg/out/passport{random.randint(1000,9999)}.png'
all_done = paste_photo(write_id_path, pasport_photo_path,
'media/cfg/template/holo.png', done_image)
print(done_image)
return done_image
|
{"/request_da/request_data.py": ["/plow/plow.py", "/plow/rand_let.py", "/source_podliver/settings.py"], "/indigo/admin.py": ["/cfdns/models.py", "/dolphin/models.py", "/farming/models.py", "/fbprofiles/models.py", "/idgenerator/models.py", "/indigo/models.py"], "/idgenerator/views.py": ["/idgenerator/forms.py", "/request_da/request_data.py", "/plow/plow.py", "/idgenerator/models.py"], "/dolphin/tasks.py": ["/dolphin/models.py"], "/indigo/tasks.py": ["/indigo/models.py"], "/idgenerator/forms.py": ["/idgenerator/models.py"], "/cfdns/tasks.py": ["/cfdns/models.py"], "/idgenerator/urls.py": ["/idgenerator/views.py"]}
|
15,308,645
|
sshmudio/dg
|
refs/heads/main
|
/idgenerator/views.py
|
from django.shortcuts import redirect, render
from django.views.generic import ListView
from .forms import DocForm
from request_da.request_data import get_data_from_form
from .models import Doc
from django.contrib import messages
class DocListView(ListView):
model = Doc
template_name = "ii.html"
def get(self, request):
form = DocForm()
return render(request, 'ii.html', context={'form': form})
def post(self, request):
form = DocForm(request.POST, request.FILES)
if form.is_valid():
form.save()
done_image = get_data_from_form(form.cleaned_data)
messages.success(request, 'Документ сгенерирован')
return redirect(done_image)
|
{"/request_da/request_data.py": ["/plow/plow.py", "/plow/rand_let.py", "/source_podliver/settings.py"], "/indigo/admin.py": ["/cfdns/models.py", "/dolphin/models.py", "/farming/models.py", "/fbprofiles/models.py", "/idgenerator/models.py", "/indigo/models.py"], "/idgenerator/views.py": ["/idgenerator/forms.py", "/request_da/request_data.py", "/plow/plow.py", "/idgenerator/models.py"], "/dolphin/tasks.py": ["/dolphin/models.py"], "/indigo/tasks.py": ["/indigo/models.py"], "/idgenerator/forms.py": ["/idgenerator/models.py"], "/cfdns/tasks.py": ["/cfdns/models.py"], "/idgenerator/urls.py": ["/idgenerator/views.py"]}
|
15,308,646
|
sshmudio/dg
|
refs/heads/main
|
/plow/addons/tt.py
|
from PIL import Image, ImageDraw, ImageFont
new_img = Image.new('RGB', (730, 120), (0, 0, 0, 0))
pencil = ImageDraw.Draw(new_img)
main_info = ImageFont.truetype('PRFW.TTF', 120)
pencil.text((0, 0), "PT99399239", (41, 37, 43), font=main_info)
new_img.save('im.png')
|
{"/request_da/request_data.py": ["/plow/plow.py", "/plow/rand_let.py", "/source_podliver/settings.py"], "/indigo/admin.py": ["/cfdns/models.py", "/dolphin/models.py", "/farming/models.py", "/fbprofiles/models.py", "/idgenerator/models.py", "/indigo/models.py"], "/idgenerator/views.py": ["/idgenerator/forms.py", "/request_da/request_data.py", "/plow/plow.py", "/idgenerator/models.py"], "/dolphin/tasks.py": ["/dolphin/models.py"], "/indigo/tasks.py": ["/indigo/models.py"], "/idgenerator/forms.py": ["/idgenerator/models.py"], "/cfdns/tasks.py": ["/cfdns/models.py"], "/idgenerator/urls.py": ["/idgenerator/views.py"]}
|
15,308,647
|
sshmudio/dg
|
refs/heads/main
|
/cfdns/python-cloudflare/CloudFlare/api_decode_from_web.py
|
""" API extras for Cloudflare API"""
import datetime
from bs4 import BeautifulSoup, Comment
API_TYPES = ['GET', 'POST', 'PATCH', 'PUT', 'DELETE']
def do_section(section):
""" API extras for Cloudflare API"""
cmds = []
# look for deprecated first in section
deprecated = False
deprecated_date = ''
deprecated_already = False
for tag2 in section.find_all('h3'):
# <h3 class="text-warning" data-reactid="13490">Deprecation Warning</h3>
if 'Deprecation Warning' in str(tag2):
deprecated = True
break
for tag2 in section.find_all('p'):
# <p class="deprecation-date" data-reactid="13491">End of life Date: November 2, 2020</p>
if 'End of life Date:' in str(tag2):
for child in tag2.children:
deprecated_date = str(child).replace('End of life Date:','').strip()
try:
# clean up date
d = datetime.datetime.strptime(deprecated_date, '%B %d, %Y')
if d <= datetime.datetime.now():
# already done!
deprecated_already = True
deprecated_date = d.strftime('%Y-%m-%d')
except ValueError:
# Lets not worry about all the date formats that could show-up. Leave as a string
pass
break
if deprecated_date != '':
break
# look for all API calls in section
for tag2 in section.find_all('pre'):
cmd = []
for child in tag2.children:
if isinstance(child, Comment):
# remove <!-- react-text ... -> parts
continue
cmd.append(child.strip())
if len(cmd) == 0:
continue
action = cmd[0]
if action == '' or action not in API_TYPES:
continue
cmd = ''.join(cmd[1:])
if cmd[0] != '/':
cmd = '/' + cmd
v = {'action': action, 'cmd': cmd, 'deprecated': deprecated, 'deprecated_date': deprecated_date, 'deprecated_already': deprecated_already}
cmds.append(v)
return cmds
def api_decode_from_web(content):
""" API extras for Cloudflare API"""
soup = BeautifulSoup(content, 'html.parser')
all_cmds = []
for section in soup.find_all('section'):
all_cmds += do_section(section)
return sorted(all_cmds, key=lambda v: v['cmd'])
|
{"/request_da/request_data.py": ["/plow/plow.py", "/plow/rand_let.py", "/source_podliver/settings.py"], "/indigo/admin.py": ["/cfdns/models.py", "/dolphin/models.py", "/farming/models.py", "/fbprofiles/models.py", "/idgenerator/models.py", "/indigo/models.py"], "/idgenerator/views.py": ["/idgenerator/forms.py", "/request_da/request_data.py", "/plow/plow.py", "/idgenerator/models.py"], "/dolphin/tasks.py": ["/dolphin/models.py"], "/indigo/tasks.py": ["/indigo/models.py"], "/idgenerator/forms.py": ["/idgenerator/models.py"], "/cfdns/tasks.py": ["/cfdns/models.py"], "/idgenerator/urls.py": ["/idgenerator/views.py"]}
|
15,308,648
|
sshmudio/dg
|
refs/heads/main
|
/plow/plow.py
|
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from mrz.generator.td3 import *
from transliterate import translit
MF = ImageFont.truetype('cfg/font/sans.ttf', 34) # Основной шрифт
FFMRZ = ImageFont.truetype('cfg/font/cour.ttf', 47) # Шрифт для MRZ
WIDTH = 440
SW = 440 # НАчальная ширина
SH = 1060
MFC = (40, 40, 40) # Основной цвет шрифта
def write_main_data(mrz, save_after_main_data, typedoc, country, id_number, surname, given_name, genre, birth_date):
""" Нанесение на шаблон документа основной информации """
img = Image.open('cfg/template/uain.png') # Шаблон паспорта
draw = ImageDraw.Draw(img)
draw.text((WIDTH, SH), str(typedoc), MFC, font=MF) # Иип документа
draw.text((WIDTH + 140, SH), str(country),
MFC, font=MF) # Страна выдачи
draw.text((WIDTH + 489, SH), id_number, MFC,
font=MF) # Уникальный номер документа
draw.text((WIDTH, SH + 67), str(surname + '/' + translit(surname,
'uk', reversed=True)).upper(), MFC,
font=MF) # Фамилия
draw.text((WIDTH, SH + 134), str(given_name + '/' + translit(given_name,
'uk', reversed=True)).upper(), MFC,
font=MF) # Имя влядельца документа
draw.text((WIDTH, SH + 201), country, MFC, font=MF) # Гражданство
draw.text((WIDTH, SH + 268), str('22 ЛЮТ/FEB 89'),
MFC, font=MF) # Дата рождения
''' ПОЛ '''
if genre == "M":
g = 'Ч/M'
else:
g = 'Ж/F'
draw.text((WIDTH, SH + 335), g, MFC, font=MF) # Пол
''' end ПОЛ '''
draw.text((WIDTH + 489, SH + 268), str(birth_date) +
'-' + '1233', MFC, font=MF) # Персональный номер
draw.text((WIDTH + 160, SH + 335), str('м. Київ/UKR').upper(),
MFC, font=MF) # Город
draw.text((WIDTH + 460, 770), "ЕН № 14205", (178, 34, 34),
font=ImageFont.truetype('media/cfg/font/sans.ttf', 40))
draw.text((WIDTH, SH + 402), "22 ЛЮТ/FEB 15", MFC, font=MF) # Дата выдачи
draw.text((WIDTH, SH + 469), "19 ЛЮТ/FEB 25",
MFC, font=MF) # Дата окончания
# Орган который выдал документ
draw.text((WIDTH + 489, SH + 402), '8099', MFC, font=MF)
draw.text((60, SH + 650), str(mrz), MFC, font=FFMRZ) # Добавляем mrz
img.save(save_after_main_data)
return save_after_main_data
def write_id(save_after_main_data_p, id_number):
passport_number = id_number
font = ImageFont.truetype('cfg/font/SNEgCheck1MP.ttf', 120)
line_height = sum(font.getmetrics()) # в нашем случае 33 + 8 = 41
fontimage = Image.new('L', (font.getsize(passport_number)[0], line_height))
# И рисуем на ней белый текст
ImageDraw.Draw(fontimage).text(
(0, 0), passport_number, fill=120, font=font)
fontimage = fontimage.rotate(90, resample=Image.BICUBIC, expand=True)
orig = Image.open(save_after_main_data_p)
orig.paste((67, 67, 67), box=(30, 180), mask=fontimage)
orig.save(save_after_main_data_p)
return save_after_main_data_p
def paste_photo(passport_temp_path, passport_photo_path, holohrama_path, all_done_path):
passport_temp = Image.open(passport_temp_path).convert('RGBA')
passport_photo = Image.open(passport_photo_path)
width, height = passport_photo.size
new_height = 425 # Высота
new_width = int(new_height * width / height)
passport_photo = passport_photo.resize(
(new_width, new_height), Image.ANTIALIAS)
if passport_photo.mode != 'RGBA':
alpha_passpor_photo = Image.new('RGBA', (10, 10), 20)
passport_photo.putalpha(alpha_passpor_photo)
paste_mask_passport_photo = passport_photo.split()[
3].point(lambda i: i * 17 / 100.)
passport_temp.paste(passport_photo, (80, SH + 125),
mask=paste_mask_passport_photo)
img = Image.open(holohrama_path) # открываем файл голограммы
wpercent = (500 / float(img.size[0]))
hsize = int((float(img.size[1]) * float(wpercent)))
img = img.resize((500, hsize), Image.ANTIALIAS)
if img.mode != 'RGBA':
alpha = Image.new('RGBA', (10, 10), 20)
img.putalpha(alpha)
paste_mask = img.split()[3].point(lambda i: i * 17 / 100.)
passport_temp.paste(img, (140, SH + 310), mask=paste_mask)
passport_temp.save(all_done_path)
# passport_temp = Image.open(passport_temp_path).convert('RGBA')
# passport_photo = Image.open(passport_photo_path)
# width, height = passport_photo.size
# new_height = 425 # Высота
# new_width = int(new_height * width / height)
# # gradient = get_gradient_3d(512, 256, (0, 0, 0), (255, 255, 255), (True, True, True))
# # Image.fromarray(np.uint8(gradient)).save('cfg/out/gg.jpg', quality=95)
# passport_photo = passport_photo.resize(
# (new_width, new_height), Image.ANTIALIAS)
# passport_temp.paste(passport_photo, (80, SH + 125), passport_photo)
# img = Image.open(holohrama_path)
# wpercent = (500 / float(img.size[0]))
# hsize = int((float(img.size[1]) * float(wpercent)))
# img = img.resize((500, hsize), Image.ANTIALIAS)
# if img.mode != 'RGBA':
# alpha = Image.new('RGBA', (10, 10), 20)
# img.putalpha(alpha)
# paste_mask = img.split()[3].point(lambda i: i * 17 / 100.)
# passport_temp.paste(img, (140, SH + 310), mask=paste_mask)
# passport_temp.save(all_done_path)
# return all_done_path
|
{"/request_da/request_data.py": ["/plow/plow.py", "/plow/rand_let.py", "/source_podliver/settings.py"], "/indigo/admin.py": ["/cfdns/models.py", "/dolphin/models.py", "/farming/models.py", "/fbprofiles/models.py", "/idgenerator/models.py", "/indigo/models.py"], "/idgenerator/views.py": ["/idgenerator/forms.py", "/request_da/request_data.py", "/plow/plow.py", "/idgenerator/models.py"], "/dolphin/tasks.py": ["/dolphin/models.py"], "/indigo/tasks.py": ["/indigo/models.py"], "/idgenerator/forms.py": ["/idgenerator/models.py"], "/cfdns/tasks.py": ["/cfdns/models.py"], "/idgenerator/urls.py": ["/idgenerator/views.py"]}
|
15,308,649
|
sshmudio/dg
|
refs/heads/main
|
/cfdns/python-cloudflare/examples/g.py
|
import CloudFlare
def main():
cf = CloudFlare.CloudFlare(
email='whitetech.lp@gmail.com', token='ff029fbbc9b791bac44bba34f88b3738bea3f')
zones = cf.zones.get()
for zone in zones:
print(zone.keys())
# for zone in zones:
# zone_id = zone['id']
# zone_name = zone['name']
# settings_ssl = cf.zones.settings.ssl.get(zone_id)
# ssl_status = settings_ssl['value']
# settings_ipv6 = cf.zones.settings.ipv6.get(zone_id)
# ipv6_status = settings_ipv6['value']
# # print(zone_id, zone_name, ssl_status, ipv6_status)
# print(zone_id)
if __name__ == '__main__':
main()
|
{"/request_da/request_data.py": ["/plow/plow.py", "/plow/rand_let.py", "/source_podliver/settings.py"], "/indigo/admin.py": ["/cfdns/models.py", "/dolphin/models.py", "/farming/models.py", "/fbprofiles/models.py", "/idgenerator/models.py", "/indigo/models.py"], "/idgenerator/views.py": ["/idgenerator/forms.py", "/request_da/request_data.py", "/plow/plow.py", "/idgenerator/models.py"], "/dolphin/tasks.py": ["/dolphin/models.py"], "/indigo/tasks.py": ["/indigo/models.py"], "/idgenerator/forms.py": ["/idgenerator/models.py"], "/cfdns/tasks.py": ["/cfdns/models.py"], "/idgenerator/urls.py": ["/idgenerator/views.py"]}
|
15,308,650
|
sshmudio/dg
|
refs/heads/main
|
/idgenerator/forms.py
|
from django import forms
from django.forms import widgets
from .models import Doc
from django.core.exceptions import ValidationError
class DocForm(forms.ModelForm):
class Meta:
model = Doc
fields = '__all__'
# localized_fields = '__all__'
|
{"/request_da/request_data.py": ["/plow/plow.py", "/plow/rand_let.py", "/source_podliver/settings.py"], "/indigo/admin.py": ["/cfdns/models.py", "/dolphin/models.py", "/farming/models.py", "/fbprofiles/models.py", "/idgenerator/models.py", "/indigo/models.py"], "/idgenerator/views.py": ["/idgenerator/forms.py", "/request_da/request_data.py", "/plow/plow.py", "/idgenerator/models.py"], "/dolphin/tasks.py": ["/dolphin/models.py"], "/indigo/tasks.py": ["/indigo/models.py"], "/idgenerator/forms.py": ["/idgenerator/models.py"], "/cfdns/tasks.py": ["/cfdns/models.py"], "/idgenerator/urls.py": ["/idgenerator/views.py"]}
|
15,308,651
|
sshmudio/dg
|
refs/heads/main
|
/idgenerator/urls.py
|
from django.urls import path
from .views import DocListView
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', DocListView.as_view()),
]
|
{"/request_da/request_data.py": ["/plow/plow.py", "/plow/rand_let.py", "/source_podliver/settings.py"], "/indigo/admin.py": ["/cfdns/models.py", "/dolphin/models.py", "/farming/models.py", "/fbprofiles/models.py", "/idgenerator/models.py", "/indigo/models.py"], "/idgenerator/views.py": ["/idgenerator/forms.py", "/request_da/request_data.py", "/plow/plow.py", "/idgenerator/models.py"], "/dolphin/tasks.py": ["/dolphin/models.py"], "/indigo/tasks.py": ["/indigo/models.py"], "/idgenerator/forms.py": ["/idgenerator/models.py"], "/cfdns/tasks.py": ["/cfdns/models.py"], "/idgenerator/urls.py": ["/idgenerator/views.py"]}
|
15,317,484
|
ToTHXaT/SysProgMacro
|
refs/heads/master
|
/src/lineparser.py
|
from shlex import shlex
from typing import *
directives = [
'byte',
'word',
'start',
'end',
'extref',
'extdef',
'csect'
]
registers = [f"r{i}" for i in range(16)]
def yield_lines(src: str) -> Generator[Tuple[int, str], None, None]:
for i, line in enumerate(src.split('\n'), start=1):
sc = line.rfind(';')
l1 = line.rfind("'")
l2 = line.rfind('"')
l = max(l1, l2)
if sc > l:
line = " ".join(line.rsplit(';', 1)[0].split())
if line:
yield i, line
class Command(NamedTuple):
label: str
cmd: str
args: List[str]
class Directive(NamedTuple):
label: str
dir: str
args: List[str]
def handle_string(line: str, tko: TKO, i: int):
i_of_1 = line.find('"')
i_of_2 = line.find("'")
if i_of_1 >= 0 and i_of_2 >= 0:
lind = min(i_of_1, i_of_2)
elif i_of_1 >= 0 > i_of_2:
lind = i_of_1
elif i_of_1 < 0 <= i_of_2:
lind = i_of_2
else:
raise Exception("lineparser.check_string")
ch = line[lind]
rind = line.rfind(ch)
if rind == -1 or rind == lind: raise Exception(f"[{i}]: No closing quotation")
if line[rind + 1:] != "":
raise Exception(f'[{i}]: Invalid string format')
prm = line[lind:rind + 1]
line = line[:lind] + line[rind + 1:]
if ',' in line:
raise Exception(f'[{i}]: Multiple arguments prohibited when defining strings')
pl = parse_line(line, tko, i)
# print(pl, prm, ch, lind, rind, line)
directive = Directive(pl.label, pl.dir, [prm])
if directive.dir != 'byte' and directive.dir != 'word':
raise Exception(f'[{i}]: Invalid usage for string')
return directive
def parse_line(line: str, tko: TKO, i: int) -> Union[Command, Directive]:
if "'" in line or '"' in line:
return handle_string(line, tko, i)
try:
line = line.replace(',', ' , ').strip()
shl = shlex(line, posix=False)
shl.whitespace += ','
shl.wordchars += '-+?~!@#$%^&*'
sp = list(shl)
except Exception as e:
raise Exception(e)
length = len(sp)
if length == 0:
pass
elif length == 1:
cmd = sp[0]
if is_cmd(cmd, tko):
return Command(None, cmd, [])
elif is_dir(cmd):
return Directive(None, cmd.lower(), [])
else:
raise Exception(f'[{i}]: {cmd} is not an operation')
else:
label, cmd, *args = sp
if is_cmd(cmd, tko):
return Command(label, cmd, args)
elif is_dir(cmd):
return Directive(label, cmd.lower(), args)
cmd, *args = sp
if is_cmd(cmd, tko):
return Command(None, cmd, args)
elif is_dir(cmd):
return Directive(None, cmd.lower(), args)
raise Exception(f'[{i}]: Invalid line. `{args[0]}` is neither operation nor directive.')
|
{"/src/handlers.py": ["/src/ui/main_w.py", "/src/FPass.py", "/src/SPass.py", "/src/exceptions.py"], "/src/SPass.py": ["/src/FPass.py", "/src/LineParser.py", "/src/MyNum.py"], "/src/LineParser.py": ["/src/exceptions.py", "/src/lists.py"], "/src/FPass.py": ["/src/exceptions.py", "/src/LineParser.py", "/src/lists.py"], "/src/MyNum.py": ["/src/exceptions.py"], "/main.py": ["/src/ui/main_w.py", "/src/handlers.py"]}
|
15,380,034
|
termicoder/termicoder
|
refs/heads/develop
|
/termicoder/cli/config/init.py
|
import click
import os
import termicoder.data.config as config_data
import shutil
from ...utils.logging import logger
from ...utils.config import get_config_path
@click.command()
def main():
"""
Initialize the config directory.
"""
config_path = get_config_path()
logger.info("Setting up configuration at '{config_dest}'".format(
config_dest=config_path))
if(os.path.exists(config_path)):
click.confirm("Directory already exists. Overwrite?",
default=True, abort=True)
shutil.rmtree(config_path)
else:
click.confirm("Continue", default=True, abort=True)
# copy the config files into the path
shutil.copytree(
os.path.dirname(config_data.__file__), config_path,
ignore=shutil.ignore_patterns('__init__.py', '__pycache__'))
|
{"/termicoder/cli/config/man.py": ["/termicoder/utils/exceptions.py"], "/termicoder/cli/config/init.py": ["/termicoder/utils/logging.py", "/termicoder/utils/config.py"], "/termicoder/judges/codechef/models/__init__.py": ["/termicoder/judges/codechef/models/Contest.py", "/termicoder/judges/codechef/models/Problem.py", "/termicoder/judges/codechef/models/Testcase.py"], "/termicoder/cli/config/edit.py": ["/termicoder/utils/config.py"], "/termicoder/utils/yaml.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/debug.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/utils/exceptions.py": ["/termicoder/utils/logging.py"], "/termicoder/judges/codechef/models/Testcase.py": ["/termicoder/models/__init__.py"], "/termicoder/judges/codechef/utils/get_data.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/view/contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/utils/testcases.py": ["/termicoder/judges/codechef/models/Testcase.py", "/termicoder/utils/logging.py"], "/termicoder/judges/codechef/utils/login_oauth.py": ["/termicoder/utils/logging.py"], "/termicoder/utils/view.py": ["/termicoder/utils/logging.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/models/Problem.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/judges/codechef/utils/testcases.py"], "/termicoder/cli/ls/contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/config/man/__init__.py": ["/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py"], "/termicoder/utils/setup.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/yaml.py"], "/termicoder/cli/ls/running.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/submit.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/models/__init__.py", "/termicoder/utils/load.py"], "/termicoder/cli/view/folder.py": ["/termicoder/utils/exceptions.py"], "/termicoder/models/__init__.py": ["/termicoder/models/Contest.py", "/termicoder/models/Judge.py", "/termicoder/models/JudgeFactory.py", "/termicoder/models/Testcase.py", "/termicoder/models/Problem.py", "/termicoder/models/User.py"], "/termicoder/cli/ls/folder.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/load.py", "/termicoder/models/__init__.py"], "/termicoder/models/JudgeFactory.py": ["/termicoder/models/__init__.py", "/termicoder/utils/Errors/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/config/remove.py": ["/termicoder/utils/config.py", "/termicoder/utils/logging.py"], "/termicoder/cli/clip.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/load.py"], "/termicoder/cli/setup/__init__.py": ["/termicoder/models/__init__.py", "/termicoder/utils/setup.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py"], "/termicoder/utils/config.py": ["/termicoder/utils/logging.py"], "/termicoder/judges/codechef/utils/__init__.py": ["/termicoder/judges/codechef/utils/login_oauth.py"], "/termicoder/utils/test.py": ["/termicoder/utils/logging.py", "/termicoder/utils/load.py"], "/termicoder/cli/config/autocomplete/show.py": ["/termicoder/cli/config/autocomplete/__init__.py"], "/termicoder/cli/code.py": ["/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py", "/termicoder/utils/launch.py", "/termicoder/utils/load.py"], "/termicoder/utils/launch.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/config/autocomplete/install.py": ["/termicoder/cli/config/autocomplete/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/__init__.py": ["/termicoder/utils/logging.py", "/termicoder/utils/config.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/ls/__init__.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/repl.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/view/running.py": ["/termicoder/models/__init__.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/models/Contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/test.py": ["/termicoder/utils/exceptions.py", "/termicoder/models/__init__.py"], "/termicoder/cli/view/problem.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"]}
|
15,380,035
|
termicoder/termicoder
|
refs/heads/develop
|
/termicoder/judges/codechef/models/__init__.py
|
from .Contest import CodechefContest as Contest
from .Problem import CodechefProblem as Problem
from .Testcase import CodechefTestcase as Testcase
__all__ = ['Contest', 'Problem', 'Testcase']
|
{"/termicoder/cli/config/man.py": ["/termicoder/utils/exceptions.py"], "/termicoder/cli/config/init.py": ["/termicoder/utils/logging.py", "/termicoder/utils/config.py"], "/termicoder/judges/codechef/models/__init__.py": ["/termicoder/judges/codechef/models/Contest.py", "/termicoder/judges/codechef/models/Problem.py", "/termicoder/judges/codechef/models/Testcase.py"], "/termicoder/cli/config/edit.py": ["/termicoder/utils/config.py"], "/termicoder/utils/yaml.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/debug.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/utils/exceptions.py": ["/termicoder/utils/logging.py"], "/termicoder/judges/codechef/models/Testcase.py": ["/termicoder/models/__init__.py"], "/termicoder/judges/codechef/utils/get_data.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/view/contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/utils/testcases.py": ["/termicoder/judges/codechef/models/Testcase.py", "/termicoder/utils/logging.py"], "/termicoder/judges/codechef/utils/login_oauth.py": ["/termicoder/utils/logging.py"], "/termicoder/utils/view.py": ["/termicoder/utils/logging.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/models/Problem.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/judges/codechef/utils/testcases.py"], "/termicoder/cli/ls/contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/config/man/__init__.py": ["/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py"], "/termicoder/utils/setup.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/yaml.py"], "/termicoder/cli/ls/running.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/submit.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/models/__init__.py", "/termicoder/utils/load.py"], "/termicoder/cli/view/folder.py": ["/termicoder/utils/exceptions.py"], "/termicoder/models/__init__.py": ["/termicoder/models/Contest.py", "/termicoder/models/Judge.py", "/termicoder/models/JudgeFactory.py", "/termicoder/models/Testcase.py", "/termicoder/models/Problem.py", "/termicoder/models/User.py"], "/termicoder/cli/ls/folder.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/load.py", "/termicoder/models/__init__.py"], "/termicoder/models/JudgeFactory.py": ["/termicoder/models/__init__.py", "/termicoder/utils/Errors/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/config/remove.py": ["/termicoder/utils/config.py", "/termicoder/utils/logging.py"], "/termicoder/cli/clip.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/load.py"], "/termicoder/cli/setup/__init__.py": ["/termicoder/models/__init__.py", "/termicoder/utils/setup.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py"], "/termicoder/utils/config.py": ["/termicoder/utils/logging.py"], "/termicoder/judges/codechef/utils/__init__.py": ["/termicoder/judges/codechef/utils/login_oauth.py"], "/termicoder/utils/test.py": ["/termicoder/utils/logging.py", "/termicoder/utils/load.py"], "/termicoder/cli/config/autocomplete/show.py": ["/termicoder/cli/config/autocomplete/__init__.py"], "/termicoder/cli/code.py": ["/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py", "/termicoder/utils/launch.py", "/termicoder/utils/load.py"], "/termicoder/utils/launch.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/config/autocomplete/install.py": ["/termicoder/cli/config/autocomplete/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/__init__.py": ["/termicoder/utils/logging.py", "/termicoder/utils/config.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/ls/__init__.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/repl.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/view/running.py": ["/termicoder/models/__init__.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/models/Contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/test.py": ["/termicoder/utils/exceptions.py", "/termicoder/models/__init__.py"], "/termicoder/cli/view/problem.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"]}
|
15,380,036
|
termicoder/termicoder
|
refs/heads/develop
|
/termicoder/cli/config/edit.py
|
import click
from ...utils.config import get_config_path
@click.command()
def main():
"""
Edit the configuration.
Launches the config folder for modifying settings.
"""
config_path = get_config_path(ensure_exists=True)
click.launch(config_path)
|
{"/termicoder/cli/config/man.py": ["/termicoder/utils/exceptions.py"], "/termicoder/cli/config/init.py": ["/termicoder/utils/logging.py", "/termicoder/utils/config.py"], "/termicoder/judges/codechef/models/__init__.py": ["/termicoder/judges/codechef/models/Contest.py", "/termicoder/judges/codechef/models/Problem.py", "/termicoder/judges/codechef/models/Testcase.py"], "/termicoder/cli/config/edit.py": ["/termicoder/utils/config.py"], "/termicoder/utils/yaml.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/debug.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/utils/exceptions.py": ["/termicoder/utils/logging.py"], "/termicoder/judges/codechef/models/Testcase.py": ["/termicoder/models/__init__.py"], "/termicoder/judges/codechef/utils/get_data.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/view/contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/utils/testcases.py": ["/termicoder/judges/codechef/models/Testcase.py", "/termicoder/utils/logging.py"], "/termicoder/judges/codechef/utils/login_oauth.py": ["/termicoder/utils/logging.py"], "/termicoder/utils/view.py": ["/termicoder/utils/logging.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/models/Problem.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/judges/codechef/utils/testcases.py"], "/termicoder/cli/ls/contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/config/man/__init__.py": ["/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py"], "/termicoder/utils/setup.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/yaml.py"], "/termicoder/cli/ls/running.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/submit.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/models/__init__.py", "/termicoder/utils/load.py"], "/termicoder/cli/view/folder.py": ["/termicoder/utils/exceptions.py"], "/termicoder/models/__init__.py": ["/termicoder/models/Contest.py", "/termicoder/models/Judge.py", "/termicoder/models/JudgeFactory.py", "/termicoder/models/Testcase.py", "/termicoder/models/Problem.py", "/termicoder/models/User.py"], "/termicoder/cli/ls/folder.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/load.py", "/termicoder/models/__init__.py"], "/termicoder/models/JudgeFactory.py": ["/termicoder/models/__init__.py", "/termicoder/utils/Errors/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/config/remove.py": ["/termicoder/utils/config.py", "/termicoder/utils/logging.py"], "/termicoder/cli/clip.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/load.py"], "/termicoder/cli/setup/__init__.py": ["/termicoder/models/__init__.py", "/termicoder/utils/setup.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py"], "/termicoder/utils/config.py": ["/termicoder/utils/logging.py"], "/termicoder/judges/codechef/utils/__init__.py": ["/termicoder/judges/codechef/utils/login_oauth.py"], "/termicoder/utils/test.py": ["/termicoder/utils/logging.py", "/termicoder/utils/load.py"], "/termicoder/cli/config/autocomplete/show.py": ["/termicoder/cli/config/autocomplete/__init__.py"], "/termicoder/cli/code.py": ["/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py", "/termicoder/utils/launch.py", "/termicoder/utils/load.py"], "/termicoder/utils/launch.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/config/autocomplete/install.py": ["/termicoder/cli/config/autocomplete/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/__init__.py": ["/termicoder/utils/logging.py", "/termicoder/utils/config.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/ls/__init__.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/repl.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/view/running.py": ["/termicoder/models/__init__.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/models/Contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/test.py": ["/termicoder/utils/exceptions.py", "/termicoder/models/__init__.py"], "/termicoder/cli/view/problem.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"]}
|
15,380,037
|
termicoder/termicoder
|
refs/heads/develop
|
/termicoder/utils/yaml.py
|
import click
import os
import yaml
try:
from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
from yaml import Loader, Dumper
from .logging import logger
def read(file_path, key=None, safe=False):
if(not os.path.exists(file_path)):
return None
data_file = click.open_file(file_path)
value = None
try:
data = yaml.load(data_file, Loader=Loader)
data_file.close()
logger.debug("read data from file %s" % file_path)
logger.debug(data)
logger.debug(key)
if key is None:
value = data
else:
value = data[key]
except yaml.YAMLError as e:
logger.error("yaml error" + str(e))
except KeyError as e:
logger.debug("KeyError key %s does not exist" % key)
except TypeError as e:
logger.debug("Type Error" + str(e))
return value
def write(file_path, key, value):
existing_data = read(file_path, None)
if existing_data is None:
existing_data = {}
if key is not None:
existing_data[key] = value
else:
existing_data = value
data_file = click.open_file(file_path, 'w')
try:
logger.debug("writing data to file %s" % file_path)
logger.debug(existing_data)
yaml.dump(data=existing_data, stream=data_file, Dumper=Dumper)
except yaml.YAMLError:
raise
|
{"/termicoder/cli/config/man.py": ["/termicoder/utils/exceptions.py"], "/termicoder/cli/config/init.py": ["/termicoder/utils/logging.py", "/termicoder/utils/config.py"], "/termicoder/judges/codechef/models/__init__.py": ["/termicoder/judges/codechef/models/Contest.py", "/termicoder/judges/codechef/models/Problem.py", "/termicoder/judges/codechef/models/Testcase.py"], "/termicoder/cli/config/edit.py": ["/termicoder/utils/config.py"], "/termicoder/utils/yaml.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/debug.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/utils/exceptions.py": ["/termicoder/utils/logging.py"], "/termicoder/judges/codechef/models/Testcase.py": ["/termicoder/models/__init__.py"], "/termicoder/judges/codechef/utils/get_data.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/view/contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/utils/testcases.py": ["/termicoder/judges/codechef/models/Testcase.py", "/termicoder/utils/logging.py"], "/termicoder/judges/codechef/utils/login_oauth.py": ["/termicoder/utils/logging.py"], "/termicoder/utils/view.py": ["/termicoder/utils/logging.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/models/Problem.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/judges/codechef/utils/testcases.py"], "/termicoder/cli/ls/contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/config/man/__init__.py": ["/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py"], "/termicoder/utils/setup.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/yaml.py"], "/termicoder/cli/ls/running.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/submit.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/models/__init__.py", "/termicoder/utils/load.py"], "/termicoder/cli/view/folder.py": ["/termicoder/utils/exceptions.py"], "/termicoder/models/__init__.py": ["/termicoder/models/Contest.py", "/termicoder/models/Judge.py", "/termicoder/models/JudgeFactory.py", "/termicoder/models/Testcase.py", "/termicoder/models/Problem.py", "/termicoder/models/User.py"], "/termicoder/cli/ls/folder.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/load.py", "/termicoder/models/__init__.py"], "/termicoder/models/JudgeFactory.py": ["/termicoder/models/__init__.py", "/termicoder/utils/Errors/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/config/remove.py": ["/termicoder/utils/config.py", "/termicoder/utils/logging.py"], "/termicoder/cli/clip.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/load.py"], "/termicoder/cli/setup/__init__.py": ["/termicoder/models/__init__.py", "/termicoder/utils/setup.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py"], "/termicoder/utils/config.py": ["/termicoder/utils/logging.py"], "/termicoder/judges/codechef/utils/__init__.py": ["/termicoder/judges/codechef/utils/login_oauth.py"], "/termicoder/utils/test.py": ["/termicoder/utils/logging.py", "/termicoder/utils/load.py"], "/termicoder/cli/config/autocomplete/show.py": ["/termicoder/cli/config/autocomplete/__init__.py"], "/termicoder/cli/code.py": ["/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py", "/termicoder/utils/launch.py", "/termicoder/utils/load.py"], "/termicoder/utils/launch.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/config/autocomplete/install.py": ["/termicoder/cli/config/autocomplete/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/__init__.py": ["/termicoder/utils/logging.py", "/termicoder/utils/config.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/ls/__init__.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/repl.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/view/running.py": ["/termicoder/models/__init__.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/models/Contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/test.py": ["/termicoder/utils/exceptions.py", "/termicoder/models/__init__.py"], "/termicoder/cli/view/problem.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"]}
|
15,380,038
|
termicoder/termicoder
|
refs/heads/develop
|
/termicoder/cli/debug.py
|
import click
from ..utils.logging import logger
from ..utils.exceptions import handle_exceptions
@click.command()
@handle_exceptions(BaseException)
def main():
'''
Launches custom debug interface.
Here you can use testcase generator,
launch debugger for the particular language
and visualize the output.
NOTE:
This functionality is not implemented in this version.
This option is only included for compatibility purposes.
If you want to contribute to its development visit:
https://github.com/termicoder/termicoder
'''
logger.info(
'This functionality is not implemented in this version\n' +
'The command is only kept for compatibility with future versions\n' +
'If you want to contribute to its development visit:\n' +
'https://github.com/termicoder/termicoder')
|
{"/termicoder/cli/config/man.py": ["/termicoder/utils/exceptions.py"], "/termicoder/cli/config/init.py": ["/termicoder/utils/logging.py", "/termicoder/utils/config.py"], "/termicoder/judges/codechef/models/__init__.py": ["/termicoder/judges/codechef/models/Contest.py", "/termicoder/judges/codechef/models/Problem.py", "/termicoder/judges/codechef/models/Testcase.py"], "/termicoder/cli/config/edit.py": ["/termicoder/utils/config.py"], "/termicoder/utils/yaml.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/debug.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/utils/exceptions.py": ["/termicoder/utils/logging.py"], "/termicoder/judges/codechef/models/Testcase.py": ["/termicoder/models/__init__.py"], "/termicoder/judges/codechef/utils/get_data.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/view/contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/utils/testcases.py": ["/termicoder/judges/codechef/models/Testcase.py", "/termicoder/utils/logging.py"], "/termicoder/judges/codechef/utils/login_oauth.py": ["/termicoder/utils/logging.py"], "/termicoder/utils/view.py": ["/termicoder/utils/logging.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/models/Problem.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/judges/codechef/utils/testcases.py"], "/termicoder/cli/ls/contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/config/man/__init__.py": ["/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py"], "/termicoder/utils/setup.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/yaml.py"], "/termicoder/cli/ls/running.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/submit.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/models/__init__.py", "/termicoder/utils/load.py"], "/termicoder/cli/view/folder.py": ["/termicoder/utils/exceptions.py"], "/termicoder/models/__init__.py": ["/termicoder/models/Contest.py", "/termicoder/models/Judge.py", "/termicoder/models/JudgeFactory.py", "/termicoder/models/Testcase.py", "/termicoder/models/Problem.py", "/termicoder/models/User.py"], "/termicoder/cli/ls/folder.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/load.py", "/termicoder/models/__init__.py"], "/termicoder/models/JudgeFactory.py": ["/termicoder/models/__init__.py", "/termicoder/utils/Errors/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/config/remove.py": ["/termicoder/utils/config.py", "/termicoder/utils/logging.py"], "/termicoder/cli/clip.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/load.py"], "/termicoder/cli/setup/__init__.py": ["/termicoder/models/__init__.py", "/termicoder/utils/setup.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py"], "/termicoder/utils/config.py": ["/termicoder/utils/logging.py"], "/termicoder/judges/codechef/utils/__init__.py": ["/termicoder/judges/codechef/utils/login_oauth.py"], "/termicoder/utils/test.py": ["/termicoder/utils/logging.py", "/termicoder/utils/load.py"], "/termicoder/cli/config/autocomplete/show.py": ["/termicoder/cli/config/autocomplete/__init__.py"], "/termicoder/cli/code.py": ["/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py", "/termicoder/utils/launch.py", "/termicoder/utils/load.py"], "/termicoder/utils/launch.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/config/autocomplete/install.py": ["/termicoder/cli/config/autocomplete/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/__init__.py": ["/termicoder/utils/logging.py", "/termicoder/utils/config.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/ls/__init__.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/repl.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/view/running.py": ["/termicoder/models/__init__.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/models/Contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/test.py": ["/termicoder/utils/exceptions.py", "/termicoder/models/__init__.py"], "/termicoder/cli/view/problem.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"]}
|
15,380,039
|
termicoder/termicoder
|
refs/heads/develop
|
/setup.py
|
from setuptools import setup, find_packages
def readme():
try:
with open('README.md') as f:
return f.read()
except BaseException:
pass
setup(
name='termicoder',
version='0.3.1',
url='https://github.com/termicoder/termicoder',
author='Divesh Uttamchandani',
author_email='diveshuttamchandani@gmail.com',
license='MIT',
description='CLI to view, code & submit problems directly from terminal',
long_description=readme(),
long_description_content_type='text/markdown',
keywords='competitive codechef oj',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Education',
'Topic :: Education',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
],
packages=find_packages(),
include_package_data=True,
install_requires=[
'Click',
'requests',
'beautifulsoup4',
'click-default-group',
'click-repl',
'click_completion',
'requests_oauthlib',
'pyyaml',
'click-log',
'pyperclip',
'beautifultable',
'Markdown',
'Tomd',
'mdv'
],
entry_points='''
[console_scripts]
termicoder=termicoder.cli:main
[termicoder.judge_plugins]
codechef=termicoder.judges:Codechef
''',
project_urls={
'Bug Reports': 'https://github.com/termicoder/termicoder/issues',
'Say Thanks!': 'https://saythanks.io/to/diveshuttam',
'Source': 'https://github.com/termicoder/termicoder/',
}
)
|
{"/termicoder/cli/config/man.py": ["/termicoder/utils/exceptions.py"], "/termicoder/cli/config/init.py": ["/termicoder/utils/logging.py", "/termicoder/utils/config.py"], "/termicoder/judges/codechef/models/__init__.py": ["/termicoder/judges/codechef/models/Contest.py", "/termicoder/judges/codechef/models/Problem.py", "/termicoder/judges/codechef/models/Testcase.py"], "/termicoder/cli/config/edit.py": ["/termicoder/utils/config.py"], "/termicoder/utils/yaml.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/debug.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/utils/exceptions.py": ["/termicoder/utils/logging.py"], "/termicoder/judges/codechef/models/Testcase.py": ["/termicoder/models/__init__.py"], "/termicoder/judges/codechef/utils/get_data.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/view/contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/utils/testcases.py": ["/termicoder/judges/codechef/models/Testcase.py", "/termicoder/utils/logging.py"], "/termicoder/judges/codechef/utils/login_oauth.py": ["/termicoder/utils/logging.py"], "/termicoder/utils/view.py": ["/termicoder/utils/logging.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/models/Problem.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/judges/codechef/utils/testcases.py"], "/termicoder/cli/ls/contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/config/man/__init__.py": ["/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py"], "/termicoder/utils/setup.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/yaml.py"], "/termicoder/cli/ls/running.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/submit.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/models/__init__.py", "/termicoder/utils/load.py"], "/termicoder/cli/view/folder.py": ["/termicoder/utils/exceptions.py"], "/termicoder/models/__init__.py": ["/termicoder/models/Contest.py", "/termicoder/models/Judge.py", "/termicoder/models/JudgeFactory.py", "/termicoder/models/Testcase.py", "/termicoder/models/Problem.py", "/termicoder/models/User.py"], "/termicoder/cli/ls/folder.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/load.py", "/termicoder/models/__init__.py"], "/termicoder/models/JudgeFactory.py": ["/termicoder/models/__init__.py", "/termicoder/utils/Errors/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/config/remove.py": ["/termicoder/utils/config.py", "/termicoder/utils/logging.py"], "/termicoder/cli/clip.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/load.py"], "/termicoder/cli/setup/__init__.py": ["/termicoder/models/__init__.py", "/termicoder/utils/setup.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py"], "/termicoder/utils/config.py": ["/termicoder/utils/logging.py"], "/termicoder/judges/codechef/utils/__init__.py": ["/termicoder/judges/codechef/utils/login_oauth.py"], "/termicoder/utils/test.py": ["/termicoder/utils/logging.py", "/termicoder/utils/load.py"], "/termicoder/cli/config/autocomplete/show.py": ["/termicoder/cli/config/autocomplete/__init__.py"], "/termicoder/cli/code.py": ["/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py", "/termicoder/utils/launch.py", "/termicoder/utils/load.py"], "/termicoder/utils/launch.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/config/autocomplete/install.py": ["/termicoder/cli/config/autocomplete/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/__init__.py": ["/termicoder/utils/logging.py", "/termicoder/utils/config.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/ls/__init__.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/repl.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/view/running.py": ["/termicoder/models/__init__.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/models/Contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/test.py": ["/termicoder/utils/exceptions.py", "/termicoder/models/__init__.py"], "/termicoder/cli/view/problem.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"]}
|
15,380,040
|
termicoder/termicoder
|
refs/heads/develop
|
/termicoder/utils/exceptions.py
|
import click
from .logging import logger
import sys
def handle_exceptions(*exceptions):
"""
Used as a decorator.
Takes exceptions and a function,
returns function warpped with try except and debug functionality
"""
# TODO correct the line number
def wrapper(function):
def customized_function(*args, **kwargs):
logger.debug(
"calling function %s" % sys.modules[function.__module__])
try:
function(*args, **kwargs)
except (exceptions) as e:
if(logger.level == 10 or isinstance(e, click.Abort)):
raise
else:
logger.error("in module %s:function %s:line %s" % (
sys.modules[function.__module__].__file__,
function.__name__, e.__traceback__.tb_lineno))
logger.error("%s %s" % (e.__class__.__name__, e))
raise click.Abort
customized_function.__wrapped__ = True
customized_function.__doc__ = function.__doc__
return customized_function
return wrapper
|
{"/termicoder/cli/config/man.py": ["/termicoder/utils/exceptions.py"], "/termicoder/cli/config/init.py": ["/termicoder/utils/logging.py", "/termicoder/utils/config.py"], "/termicoder/judges/codechef/models/__init__.py": ["/termicoder/judges/codechef/models/Contest.py", "/termicoder/judges/codechef/models/Problem.py", "/termicoder/judges/codechef/models/Testcase.py"], "/termicoder/cli/config/edit.py": ["/termicoder/utils/config.py"], "/termicoder/utils/yaml.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/debug.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/utils/exceptions.py": ["/termicoder/utils/logging.py"], "/termicoder/judges/codechef/models/Testcase.py": ["/termicoder/models/__init__.py"], "/termicoder/judges/codechef/utils/get_data.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/view/contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/utils/testcases.py": ["/termicoder/judges/codechef/models/Testcase.py", "/termicoder/utils/logging.py"], "/termicoder/judges/codechef/utils/login_oauth.py": ["/termicoder/utils/logging.py"], "/termicoder/utils/view.py": ["/termicoder/utils/logging.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/models/Problem.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/judges/codechef/utils/testcases.py"], "/termicoder/cli/ls/contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/config/man/__init__.py": ["/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py"], "/termicoder/utils/setup.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/yaml.py"], "/termicoder/cli/ls/running.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/submit.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/models/__init__.py", "/termicoder/utils/load.py"], "/termicoder/cli/view/folder.py": ["/termicoder/utils/exceptions.py"], "/termicoder/models/__init__.py": ["/termicoder/models/Contest.py", "/termicoder/models/Judge.py", "/termicoder/models/JudgeFactory.py", "/termicoder/models/Testcase.py", "/termicoder/models/Problem.py", "/termicoder/models/User.py"], "/termicoder/cli/ls/folder.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/load.py", "/termicoder/models/__init__.py"], "/termicoder/models/JudgeFactory.py": ["/termicoder/models/__init__.py", "/termicoder/utils/Errors/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/config/remove.py": ["/termicoder/utils/config.py", "/termicoder/utils/logging.py"], "/termicoder/cli/clip.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/load.py"], "/termicoder/cli/setup/__init__.py": ["/termicoder/models/__init__.py", "/termicoder/utils/setup.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py"], "/termicoder/utils/config.py": ["/termicoder/utils/logging.py"], "/termicoder/judges/codechef/utils/__init__.py": ["/termicoder/judges/codechef/utils/login_oauth.py"], "/termicoder/utils/test.py": ["/termicoder/utils/logging.py", "/termicoder/utils/load.py"], "/termicoder/cli/config/autocomplete/show.py": ["/termicoder/cli/config/autocomplete/__init__.py"], "/termicoder/cli/code.py": ["/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py", "/termicoder/utils/launch.py", "/termicoder/utils/load.py"], "/termicoder/utils/launch.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/config/autocomplete/install.py": ["/termicoder/cli/config/autocomplete/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/__init__.py": ["/termicoder/utils/logging.py", "/termicoder/utils/config.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/ls/__init__.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/repl.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/view/running.py": ["/termicoder/models/__init__.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/models/Contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/test.py": ["/termicoder/utils/exceptions.py", "/termicoder/models/__init__.py"], "/termicoder/cli/view/problem.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"]}
|
15,380,041
|
termicoder/termicoder
|
refs/heads/develop
|
/termicoder/judges/codechef/models/Testcase.py
|
from termicoder.models import Testcase
class CodechefTestcase(Testcase):
def __init__(self, inp, ans, code):
self.inp = inp # input
self.ans = ans # answer
self.code = code # code/number for testcase
|
{"/termicoder/cli/config/man.py": ["/termicoder/utils/exceptions.py"], "/termicoder/cli/config/init.py": ["/termicoder/utils/logging.py", "/termicoder/utils/config.py"], "/termicoder/judges/codechef/models/__init__.py": ["/termicoder/judges/codechef/models/Contest.py", "/termicoder/judges/codechef/models/Problem.py", "/termicoder/judges/codechef/models/Testcase.py"], "/termicoder/cli/config/edit.py": ["/termicoder/utils/config.py"], "/termicoder/utils/yaml.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/debug.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/utils/exceptions.py": ["/termicoder/utils/logging.py"], "/termicoder/judges/codechef/models/Testcase.py": ["/termicoder/models/__init__.py"], "/termicoder/judges/codechef/utils/get_data.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/view/contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/utils/testcases.py": ["/termicoder/judges/codechef/models/Testcase.py", "/termicoder/utils/logging.py"], "/termicoder/judges/codechef/utils/login_oauth.py": ["/termicoder/utils/logging.py"], "/termicoder/utils/view.py": ["/termicoder/utils/logging.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/models/Problem.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/judges/codechef/utils/testcases.py"], "/termicoder/cli/ls/contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/config/man/__init__.py": ["/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py"], "/termicoder/utils/setup.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/yaml.py"], "/termicoder/cli/ls/running.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/submit.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/models/__init__.py", "/termicoder/utils/load.py"], "/termicoder/cli/view/folder.py": ["/termicoder/utils/exceptions.py"], "/termicoder/models/__init__.py": ["/termicoder/models/Contest.py", "/termicoder/models/Judge.py", "/termicoder/models/JudgeFactory.py", "/termicoder/models/Testcase.py", "/termicoder/models/Problem.py", "/termicoder/models/User.py"], "/termicoder/cli/ls/folder.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/load.py", "/termicoder/models/__init__.py"], "/termicoder/models/JudgeFactory.py": ["/termicoder/models/__init__.py", "/termicoder/utils/Errors/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/config/remove.py": ["/termicoder/utils/config.py", "/termicoder/utils/logging.py"], "/termicoder/cli/clip.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/load.py"], "/termicoder/cli/setup/__init__.py": ["/termicoder/models/__init__.py", "/termicoder/utils/setup.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py"], "/termicoder/utils/config.py": ["/termicoder/utils/logging.py"], "/termicoder/judges/codechef/utils/__init__.py": ["/termicoder/judges/codechef/utils/login_oauth.py"], "/termicoder/utils/test.py": ["/termicoder/utils/logging.py", "/termicoder/utils/load.py"], "/termicoder/cli/config/autocomplete/show.py": ["/termicoder/cli/config/autocomplete/__init__.py"], "/termicoder/cli/code.py": ["/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py", "/termicoder/utils/launch.py", "/termicoder/utils/load.py"], "/termicoder/utils/launch.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/config/autocomplete/install.py": ["/termicoder/cli/config/autocomplete/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/__init__.py": ["/termicoder/utils/logging.py", "/termicoder/utils/config.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/ls/__init__.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/repl.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/view/running.py": ["/termicoder/models/__init__.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/models/Contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/test.py": ["/termicoder/utils/exceptions.py", "/termicoder/models/__init__.py"], "/termicoder/cli/view/problem.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"]}
|
15,380,042
|
termicoder/termicoder
|
refs/heads/develop
|
/termicoder/judges/codechef/utils/get_data.py
|
from datetime import datetime
from ....utils.logging import logger
def transpose_running_oauth(x):
return {
'code': x['code'],
'endDate': datetime.strptime(x['endDate'], '%Y-%m-%d %H:%M:%S'),
'startDate': datetime.strptime(x['endDate'], '%Y-%m-%d %H:%M:%S'),
'name': x['name']
}
def running_contests(self):
path = 'contests'
url = self._make_url(self.api_url, path)
r = self._request_api(url)
data = r['result']['data']['content']
contest_list = map(transpose_running_oauth, data['contestList'])
current_time = datetime.fromtimestamp(data['currentTime'])
def check_current(contest):
contest_time = contest['endDate']
return contest_time >= current_time
running = list(filter(check_current, contest_list))
logger.debug("got running")
return running
|
{"/termicoder/cli/config/man.py": ["/termicoder/utils/exceptions.py"], "/termicoder/cli/config/init.py": ["/termicoder/utils/logging.py", "/termicoder/utils/config.py"], "/termicoder/judges/codechef/models/__init__.py": ["/termicoder/judges/codechef/models/Contest.py", "/termicoder/judges/codechef/models/Problem.py", "/termicoder/judges/codechef/models/Testcase.py"], "/termicoder/cli/config/edit.py": ["/termicoder/utils/config.py"], "/termicoder/utils/yaml.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/debug.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/utils/exceptions.py": ["/termicoder/utils/logging.py"], "/termicoder/judges/codechef/models/Testcase.py": ["/termicoder/models/__init__.py"], "/termicoder/judges/codechef/utils/get_data.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/view/contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/utils/testcases.py": ["/termicoder/judges/codechef/models/Testcase.py", "/termicoder/utils/logging.py"], "/termicoder/judges/codechef/utils/login_oauth.py": ["/termicoder/utils/logging.py"], "/termicoder/utils/view.py": ["/termicoder/utils/logging.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/models/Problem.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/judges/codechef/utils/testcases.py"], "/termicoder/cli/ls/contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/config/man/__init__.py": ["/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py"], "/termicoder/utils/setup.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/yaml.py"], "/termicoder/cli/ls/running.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/submit.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/models/__init__.py", "/termicoder/utils/load.py"], "/termicoder/cli/view/folder.py": ["/termicoder/utils/exceptions.py"], "/termicoder/models/__init__.py": ["/termicoder/models/Contest.py", "/termicoder/models/Judge.py", "/termicoder/models/JudgeFactory.py", "/termicoder/models/Testcase.py", "/termicoder/models/Problem.py", "/termicoder/models/User.py"], "/termicoder/cli/ls/folder.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/load.py", "/termicoder/models/__init__.py"], "/termicoder/models/JudgeFactory.py": ["/termicoder/models/__init__.py", "/termicoder/utils/Errors/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/config/remove.py": ["/termicoder/utils/config.py", "/termicoder/utils/logging.py"], "/termicoder/cli/clip.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/load.py"], "/termicoder/cli/setup/__init__.py": ["/termicoder/models/__init__.py", "/termicoder/utils/setup.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py"], "/termicoder/utils/config.py": ["/termicoder/utils/logging.py"], "/termicoder/judges/codechef/utils/__init__.py": ["/termicoder/judges/codechef/utils/login_oauth.py"], "/termicoder/utils/test.py": ["/termicoder/utils/logging.py", "/termicoder/utils/load.py"], "/termicoder/cli/config/autocomplete/show.py": ["/termicoder/cli/config/autocomplete/__init__.py"], "/termicoder/cli/code.py": ["/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py", "/termicoder/utils/launch.py", "/termicoder/utils/load.py"], "/termicoder/utils/launch.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/config/autocomplete/install.py": ["/termicoder/cli/config/autocomplete/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/__init__.py": ["/termicoder/utils/logging.py", "/termicoder/utils/config.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/ls/__init__.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/repl.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/view/running.py": ["/termicoder/models/__init__.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/models/Contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/test.py": ["/termicoder/utils/exceptions.py", "/termicoder/models/__init__.py"], "/termicoder/cli/view/problem.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"]}
|
15,380,043
|
termicoder/termicoder
|
refs/heads/develop
|
/termicoder/cli/view/contest.py
|
import click
from ...models import JudgeFactory
from ...utils.constants import default_judge
from ...utils.logging import logger
from ...utils.exceptions import handle_exceptions
from ...utils import config
from ...utils.launch import launch, substitute
judge_factory = JudgeFactory()
OJs = judge_factory.available_judges
@click.command(short_help="Display a particular contest")
@click.option('-j', '--judge', 'judge_name', type=click.Choice(OJs),
prompt="Please provide a judge("+'|'.join(OJs)+")",
default=default_judge)
@click.option("--browser", help='Browser to launch',
default=config.read('settings.yml', 'browser_online'))
@click.argument('CONTEST_CODE', required=False)
@handle_exceptions(BaseException)
def main(judge_name, contest_code, browser):
'''
View a contest from the judge (online).
Launches the contest in browser.
'''
judge = judge_factory.get_judge(judge_name)
contest_url = judge.get_contest_url(contest_code=contest_code)
keymap = {
"URL": contest_url
}
logger.debug('launching %s' % contest_url)
status, browser = substitute(browser, keymap)
if status is True:
contest_url = ''
launch(browser, contest_url)
|
{"/termicoder/cli/config/man.py": ["/termicoder/utils/exceptions.py"], "/termicoder/cli/config/init.py": ["/termicoder/utils/logging.py", "/termicoder/utils/config.py"], "/termicoder/judges/codechef/models/__init__.py": ["/termicoder/judges/codechef/models/Contest.py", "/termicoder/judges/codechef/models/Problem.py", "/termicoder/judges/codechef/models/Testcase.py"], "/termicoder/cli/config/edit.py": ["/termicoder/utils/config.py"], "/termicoder/utils/yaml.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/debug.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/utils/exceptions.py": ["/termicoder/utils/logging.py"], "/termicoder/judges/codechef/models/Testcase.py": ["/termicoder/models/__init__.py"], "/termicoder/judges/codechef/utils/get_data.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/view/contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/utils/testcases.py": ["/termicoder/judges/codechef/models/Testcase.py", "/termicoder/utils/logging.py"], "/termicoder/judges/codechef/utils/login_oauth.py": ["/termicoder/utils/logging.py"], "/termicoder/utils/view.py": ["/termicoder/utils/logging.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/models/Problem.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/judges/codechef/utils/testcases.py"], "/termicoder/cli/ls/contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/config/man/__init__.py": ["/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py"], "/termicoder/utils/setup.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/yaml.py"], "/termicoder/cli/ls/running.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/submit.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/models/__init__.py", "/termicoder/utils/load.py"], "/termicoder/cli/view/folder.py": ["/termicoder/utils/exceptions.py"], "/termicoder/models/__init__.py": ["/termicoder/models/Contest.py", "/termicoder/models/Judge.py", "/termicoder/models/JudgeFactory.py", "/termicoder/models/Testcase.py", "/termicoder/models/Problem.py", "/termicoder/models/User.py"], "/termicoder/cli/ls/folder.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/load.py", "/termicoder/models/__init__.py"], "/termicoder/models/JudgeFactory.py": ["/termicoder/models/__init__.py", "/termicoder/utils/Errors/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/config/remove.py": ["/termicoder/utils/config.py", "/termicoder/utils/logging.py"], "/termicoder/cli/clip.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/load.py"], "/termicoder/cli/setup/__init__.py": ["/termicoder/models/__init__.py", "/termicoder/utils/setup.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py"], "/termicoder/utils/config.py": ["/termicoder/utils/logging.py"], "/termicoder/judges/codechef/utils/__init__.py": ["/termicoder/judges/codechef/utils/login_oauth.py"], "/termicoder/utils/test.py": ["/termicoder/utils/logging.py", "/termicoder/utils/load.py"], "/termicoder/cli/config/autocomplete/show.py": ["/termicoder/cli/config/autocomplete/__init__.py"], "/termicoder/cli/code.py": ["/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py", "/termicoder/utils/launch.py", "/termicoder/utils/load.py"], "/termicoder/utils/launch.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/config/autocomplete/install.py": ["/termicoder/cli/config/autocomplete/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/__init__.py": ["/termicoder/utils/logging.py", "/termicoder/utils/config.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/ls/__init__.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/repl.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/view/running.py": ["/termicoder/models/__init__.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/models/Contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/test.py": ["/termicoder/utils/exceptions.py", "/termicoder/models/__init__.py"], "/termicoder/cli/view/problem.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"]}
|
15,380,044
|
termicoder/termicoder
|
refs/heads/develop
|
/termicoder/judges/codechef/utils/testcases.py
|
from ..models.Testcase import CodechefTestcase as Testcase
from bs4 import BeautifulSoup
from termicoder.utils.logging import logger
# Many corner cases are being handled in extracting testcases
# maybe we can implement our own parser here instead of using
# beautiful soup. Most type of problems should be extracted
def extract(html):
logger.debug("extract is being called")
soup = BeautifulSoup(html, "html.parser")
testcases = []
pre_tag_elements = soup.find_all('pre')
try:
io = _extract_io(pre_tag_elements)
logger.debug(io)
except BaseException:
logger.error("Extraction of testcase for the problem failed")
return []
if(len(pre_tag_elements) >= 1):
for i in range(len(io[0])):
inp = io[0][i]
ans = io[1][i]
testcases.append(Testcase(inp=inp, ans=ans, code=i))
logger.debug("inp\n" + inp + "\n\n")
logger.debug("ans\n" + ans + "\n\n")
return testcases
else:
logger.error("Extraction of testcase for the problem failed")
def _sanitize(io):
"""
removes ":" "1:" etc if any in front of the io
"""
# trim begining and ending spaces
io = io.strip()
# if Output: Input: etc.
if(io[0] == ":"):
io = io[1:]
# if Output1: Input1: etc
elif(len(io) > 1 and io[1] == ":"):
io = io[2:]
return io.strip()+"\n"
def _extract_io(pre_tag_elements):
"""
extracts all input and output from pre tags and returns as tuple
"""
sample_inputs = []
sample_outputs = []
for sample_io in pre_tag_elements:
# finding heading / previous sibling of pre
sibling = sample_io.previous_sibling
while(not str(sibling).strip()):
sibling = sibling.previous_sibling
# converting sample_io to text
if sibling is None:
sibling = sample_io.parent.previous_sibling
while(not str(sibling).strip()):
sibling = sibling.previous_sibling
iotext = str(sample_io.text)
# standard codechef problems with input and output in same pre tag
# OR sometimes input just above pre tag and output in pretag
if(("input" in iotext.lower() or "input" in str(sibling).lower()) and
"output" in iotext.lower()):
in_index, out_index = iotext.lower().find(
"input"), iotext.lower().find("output")
ki = 1 if (in_index == -1) else 5
sample_input = _sanitize(iotext[in_index+ki: out_index])
sample_output = _sanitize(iotext[out_index + 6:])
if(len(sample_inputs) != len(sample_outputs)):
sample_inputs = []
sample_outputs = []
sample_inputs.append(sample_input)
sample_outputs.append(sample_output)
# problem with input only like challenge problems
# or input and output in separate pre tags
elif("input" in str(sample_io.text).lower() or
"input" in str(sibling).lower()):
in_index = iotext.lower().find("input")
ki = 1 if (in_index == -1) else 5
sample_input = _sanitize(iotext[in_index+ki:])
sample_input = _sanitize(sample_input)
sample_inputs.append(sample_input)
# problem with output only like printing 100! etc
# or input and output in separate pre tags
elif("output" in str(sample_io.text).lower() or
"output" in str(sibling).lower()):
out_index = iotext.lower().find("output")
ko = 1 if (out_index == -1) else 6
sample_output = _sanitize(iotext[out_index+ko:])
sample_output = _sanitize(sample_output)
sample_outputs.append(sample_output)
return sample_inputs, sample_outputs
|
{"/termicoder/cli/config/man.py": ["/termicoder/utils/exceptions.py"], "/termicoder/cli/config/init.py": ["/termicoder/utils/logging.py", "/termicoder/utils/config.py"], "/termicoder/judges/codechef/models/__init__.py": ["/termicoder/judges/codechef/models/Contest.py", "/termicoder/judges/codechef/models/Problem.py", "/termicoder/judges/codechef/models/Testcase.py"], "/termicoder/cli/config/edit.py": ["/termicoder/utils/config.py"], "/termicoder/utils/yaml.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/debug.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/utils/exceptions.py": ["/termicoder/utils/logging.py"], "/termicoder/judges/codechef/models/Testcase.py": ["/termicoder/models/__init__.py"], "/termicoder/judges/codechef/utils/get_data.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/view/contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/utils/testcases.py": ["/termicoder/judges/codechef/models/Testcase.py", "/termicoder/utils/logging.py"], "/termicoder/judges/codechef/utils/login_oauth.py": ["/termicoder/utils/logging.py"], "/termicoder/utils/view.py": ["/termicoder/utils/logging.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/models/Problem.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/judges/codechef/utils/testcases.py"], "/termicoder/cli/ls/contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/config/man/__init__.py": ["/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py"], "/termicoder/utils/setup.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/yaml.py"], "/termicoder/cli/ls/running.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/submit.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/models/__init__.py", "/termicoder/utils/load.py"], "/termicoder/cli/view/folder.py": ["/termicoder/utils/exceptions.py"], "/termicoder/models/__init__.py": ["/termicoder/models/Contest.py", "/termicoder/models/Judge.py", "/termicoder/models/JudgeFactory.py", "/termicoder/models/Testcase.py", "/termicoder/models/Problem.py", "/termicoder/models/User.py"], "/termicoder/cli/ls/folder.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/load.py", "/termicoder/models/__init__.py"], "/termicoder/models/JudgeFactory.py": ["/termicoder/models/__init__.py", "/termicoder/utils/Errors/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/config/remove.py": ["/termicoder/utils/config.py", "/termicoder/utils/logging.py"], "/termicoder/cli/clip.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/load.py"], "/termicoder/cli/setup/__init__.py": ["/termicoder/models/__init__.py", "/termicoder/utils/setup.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py"], "/termicoder/utils/config.py": ["/termicoder/utils/logging.py"], "/termicoder/judges/codechef/utils/__init__.py": ["/termicoder/judges/codechef/utils/login_oauth.py"], "/termicoder/utils/test.py": ["/termicoder/utils/logging.py", "/termicoder/utils/load.py"], "/termicoder/cli/config/autocomplete/show.py": ["/termicoder/cli/config/autocomplete/__init__.py"], "/termicoder/cli/code.py": ["/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py", "/termicoder/utils/launch.py", "/termicoder/utils/load.py"], "/termicoder/utils/launch.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/config/autocomplete/install.py": ["/termicoder/cli/config/autocomplete/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/__init__.py": ["/termicoder/utils/logging.py", "/termicoder/utils/config.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/ls/__init__.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/repl.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/view/running.py": ["/termicoder/models/__init__.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/models/Contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/test.py": ["/termicoder/utils/exceptions.py", "/termicoder/models/__init__.py"], "/termicoder/cli/view/problem.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"]}
|
15,380,045
|
termicoder/termicoder
|
refs/heads/develop
|
/termicoder/cli/config/autocomplete/__init__.py
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
import click
import click_completion
import click_completion.core
from . import install
from . import show
def custom_startswith(string, incomplete):
"""A custom completion matching that supports case insensitive matching"""
if os.environ.get('_CLICK_COMPLETION_COMMAND_CASE_INSENSITIVE_COMPLETE'):
string = string.lower()
incomplete = incomplete.lower()
return string.startswith(incomplete)
click_completion.core.startswith = custom_startswith
click_completion.init()
cmd_help = """Shell completion for termicoder.
Available shell types:
\b
%s
Default type: auto
""" % "\n ".join('{:<12} {}'.format(k,
click_completion.core.shells[k]) for k in sorted(
click_completion.core.shells.keys()))
@click.group(help=cmd_help)
def main():
pass
sub_commands = [
{
"cmd": install.main,
"name": "install"
},
{
"cmd": show.main,
"name": "show"
}
]
for command in sub_commands:
main.add_command(**command)
__all__ = ['main']
|
{"/termicoder/cli/config/man.py": ["/termicoder/utils/exceptions.py"], "/termicoder/cli/config/init.py": ["/termicoder/utils/logging.py", "/termicoder/utils/config.py"], "/termicoder/judges/codechef/models/__init__.py": ["/termicoder/judges/codechef/models/Contest.py", "/termicoder/judges/codechef/models/Problem.py", "/termicoder/judges/codechef/models/Testcase.py"], "/termicoder/cli/config/edit.py": ["/termicoder/utils/config.py"], "/termicoder/utils/yaml.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/debug.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/utils/exceptions.py": ["/termicoder/utils/logging.py"], "/termicoder/judges/codechef/models/Testcase.py": ["/termicoder/models/__init__.py"], "/termicoder/judges/codechef/utils/get_data.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/view/contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/utils/testcases.py": ["/termicoder/judges/codechef/models/Testcase.py", "/termicoder/utils/logging.py"], "/termicoder/judges/codechef/utils/login_oauth.py": ["/termicoder/utils/logging.py"], "/termicoder/utils/view.py": ["/termicoder/utils/logging.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/models/Problem.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/judges/codechef/utils/testcases.py"], "/termicoder/cli/ls/contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/config/man/__init__.py": ["/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py"], "/termicoder/utils/setup.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/yaml.py"], "/termicoder/cli/ls/running.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/submit.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/models/__init__.py", "/termicoder/utils/load.py"], "/termicoder/cli/view/folder.py": ["/termicoder/utils/exceptions.py"], "/termicoder/models/__init__.py": ["/termicoder/models/Contest.py", "/termicoder/models/Judge.py", "/termicoder/models/JudgeFactory.py", "/termicoder/models/Testcase.py", "/termicoder/models/Problem.py", "/termicoder/models/User.py"], "/termicoder/cli/ls/folder.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/load.py", "/termicoder/models/__init__.py"], "/termicoder/models/JudgeFactory.py": ["/termicoder/models/__init__.py", "/termicoder/utils/Errors/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/config/remove.py": ["/termicoder/utils/config.py", "/termicoder/utils/logging.py"], "/termicoder/cli/clip.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/load.py"], "/termicoder/cli/setup/__init__.py": ["/termicoder/models/__init__.py", "/termicoder/utils/setup.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py"], "/termicoder/utils/config.py": ["/termicoder/utils/logging.py"], "/termicoder/judges/codechef/utils/__init__.py": ["/termicoder/judges/codechef/utils/login_oauth.py"], "/termicoder/utils/test.py": ["/termicoder/utils/logging.py", "/termicoder/utils/load.py"], "/termicoder/cli/config/autocomplete/show.py": ["/termicoder/cli/config/autocomplete/__init__.py"], "/termicoder/cli/code.py": ["/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py", "/termicoder/utils/launch.py", "/termicoder/utils/load.py"], "/termicoder/utils/launch.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/config/autocomplete/install.py": ["/termicoder/cli/config/autocomplete/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/__init__.py": ["/termicoder/utils/logging.py", "/termicoder/utils/config.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/ls/__init__.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/repl.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/view/running.py": ["/termicoder/models/__init__.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/models/Contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/test.py": ["/termicoder/utils/exceptions.py", "/termicoder/models/__init__.py"], "/termicoder/cli/view/problem.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"]}
|
15,380,046
|
termicoder/termicoder
|
refs/heads/develop
|
/termicoder/utils/style.py
|
import click
def _style_decorator(fg, bg=None, underline=None, bold=None):
def decorated_function(*args, **kwargs):
return click.style(*args, **kwargs, fg=fg,
bg=bg, bold=bold, underline=underline)
return decorated_function
# TODO add option for changing colors from config file
error = _style_decorator('red')
message = _style_decorator('white')
url = _style_decorator('cyan', underline=True)
ac = _style_decorator('green')
partial_ac = _style_decorator('yellow')
wrong = _style_decorator('red')
headers = _style_decorator('blue')
__all__ = ['error', 'message', 'url', 'ac', 'partial_ac', 'wrong', 'headers']
|
{"/termicoder/cli/config/man.py": ["/termicoder/utils/exceptions.py"], "/termicoder/cli/config/init.py": ["/termicoder/utils/logging.py", "/termicoder/utils/config.py"], "/termicoder/judges/codechef/models/__init__.py": ["/termicoder/judges/codechef/models/Contest.py", "/termicoder/judges/codechef/models/Problem.py", "/termicoder/judges/codechef/models/Testcase.py"], "/termicoder/cli/config/edit.py": ["/termicoder/utils/config.py"], "/termicoder/utils/yaml.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/debug.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/utils/exceptions.py": ["/termicoder/utils/logging.py"], "/termicoder/judges/codechef/models/Testcase.py": ["/termicoder/models/__init__.py"], "/termicoder/judges/codechef/utils/get_data.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/view/contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/utils/testcases.py": ["/termicoder/judges/codechef/models/Testcase.py", "/termicoder/utils/logging.py"], "/termicoder/judges/codechef/utils/login_oauth.py": ["/termicoder/utils/logging.py"], "/termicoder/utils/view.py": ["/termicoder/utils/logging.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/models/Problem.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/judges/codechef/utils/testcases.py"], "/termicoder/cli/ls/contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/config/man/__init__.py": ["/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py"], "/termicoder/utils/setup.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/yaml.py"], "/termicoder/cli/ls/running.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/submit.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/models/__init__.py", "/termicoder/utils/load.py"], "/termicoder/cli/view/folder.py": ["/termicoder/utils/exceptions.py"], "/termicoder/models/__init__.py": ["/termicoder/models/Contest.py", "/termicoder/models/Judge.py", "/termicoder/models/JudgeFactory.py", "/termicoder/models/Testcase.py", "/termicoder/models/Problem.py", "/termicoder/models/User.py"], "/termicoder/cli/ls/folder.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/load.py", "/termicoder/models/__init__.py"], "/termicoder/models/JudgeFactory.py": ["/termicoder/models/__init__.py", "/termicoder/utils/Errors/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/config/remove.py": ["/termicoder/utils/config.py", "/termicoder/utils/logging.py"], "/termicoder/cli/clip.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/load.py"], "/termicoder/cli/setup/__init__.py": ["/termicoder/models/__init__.py", "/termicoder/utils/setup.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py"], "/termicoder/utils/config.py": ["/termicoder/utils/logging.py"], "/termicoder/judges/codechef/utils/__init__.py": ["/termicoder/judges/codechef/utils/login_oauth.py"], "/termicoder/utils/test.py": ["/termicoder/utils/logging.py", "/termicoder/utils/load.py"], "/termicoder/cli/config/autocomplete/show.py": ["/termicoder/cli/config/autocomplete/__init__.py"], "/termicoder/cli/code.py": ["/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py", "/termicoder/utils/launch.py", "/termicoder/utils/load.py"], "/termicoder/utils/launch.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/config/autocomplete/install.py": ["/termicoder/cli/config/autocomplete/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/__init__.py": ["/termicoder/utils/logging.py", "/termicoder/utils/config.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/ls/__init__.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/repl.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/view/running.py": ["/termicoder/models/__init__.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/models/Contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/test.py": ["/termicoder/utils/exceptions.py", "/termicoder/models/__init__.py"], "/termicoder/cli/view/problem.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"]}
|
15,380,047
|
termicoder/termicoder
|
refs/heads/develop
|
/termicoder/judges/codechef/models/Tags.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
class Tags:
def __init__(self):
self.id = None
self.display_name = None
self.synonyms = None
|
{"/termicoder/cli/config/man.py": ["/termicoder/utils/exceptions.py"], "/termicoder/cli/config/init.py": ["/termicoder/utils/logging.py", "/termicoder/utils/config.py"], "/termicoder/judges/codechef/models/__init__.py": ["/termicoder/judges/codechef/models/Contest.py", "/termicoder/judges/codechef/models/Problem.py", "/termicoder/judges/codechef/models/Testcase.py"], "/termicoder/cli/config/edit.py": ["/termicoder/utils/config.py"], "/termicoder/utils/yaml.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/debug.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/utils/exceptions.py": ["/termicoder/utils/logging.py"], "/termicoder/judges/codechef/models/Testcase.py": ["/termicoder/models/__init__.py"], "/termicoder/judges/codechef/utils/get_data.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/view/contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/utils/testcases.py": ["/termicoder/judges/codechef/models/Testcase.py", "/termicoder/utils/logging.py"], "/termicoder/judges/codechef/utils/login_oauth.py": ["/termicoder/utils/logging.py"], "/termicoder/utils/view.py": ["/termicoder/utils/logging.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/models/Problem.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/judges/codechef/utils/testcases.py"], "/termicoder/cli/ls/contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/config/man/__init__.py": ["/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py"], "/termicoder/utils/setup.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/yaml.py"], "/termicoder/cli/ls/running.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/submit.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/models/__init__.py", "/termicoder/utils/load.py"], "/termicoder/cli/view/folder.py": ["/termicoder/utils/exceptions.py"], "/termicoder/models/__init__.py": ["/termicoder/models/Contest.py", "/termicoder/models/Judge.py", "/termicoder/models/JudgeFactory.py", "/termicoder/models/Testcase.py", "/termicoder/models/Problem.py", "/termicoder/models/User.py"], "/termicoder/cli/ls/folder.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/load.py", "/termicoder/models/__init__.py"], "/termicoder/models/JudgeFactory.py": ["/termicoder/models/__init__.py", "/termicoder/utils/Errors/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/config/remove.py": ["/termicoder/utils/config.py", "/termicoder/utils/logging.py"], "/termicoder/cli/clip.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/load.py"], "/termicoder/cli/setup/__init__.py": ["/termicoder/models/__init__.py", "/termicoder/utils/setup.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py"], "/termicoder/utils/config.py": ["/termicoder/utils/logging.py"], "/termicoder/judges/codechef/utils/__init__.py": ["/termicoder/judges/codechef/utils/login_oauth.py"], "/termicoder/utils/test.py": ["/termicoder/utils/logging.py", "/termicoder/utils/load.py"], "/termicoder/cli/config/autocomplete/show.py": ["/termicoder/cli/config/autocomplete/__init__.py"], "/termicoder/cli/code.py": ["/termicoder/utils/exceptions.py", "/termicoder/utils/logging.py", "/termicoder/utils/launch.py", "/termicoder/utils/load.py"], "/termicoder/utils/launch.py": ["/termicoder/utils/logging.py"], "/termicoder/cli/config/autocomplete/install.py": ["/termicoder/cli/config/autocomplete/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/__init__.py": ["/termicoder/utils/logging.py", "/termicoder/utils/config.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/ls/__init__.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/repl.py": ["/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py"], "/termicoder/cli/view/running.py": ["/termicoder/models/__init__.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"], "/termicoder/judges/codechef/models/Contest.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py"], "/termicoder/cli/test.py": ["/termicoder/utils/exceptions.py", "/termicoder/models/__init__.py"], "/termicoder/cli/view/problem.py": ["/termicoder/models/__init__.py", "/termicoder/utils/logging.py", "/termicoder/utils/exceptions.py", "/termicoder/utils/launch.py"]}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.