index
int64 | repo_name
string | branch_name
string | path
string | content
string | import_graph
string |
|---|---|---|---|---|---|
45,396,821
|
lea98/search_books
|
refs/heads/main
|
/views/add_oglas.py
|
import os
from flask import Blueprint, render_template, current_app, url_for
from flask_login import login_required, current_user
from flask_wtf import FlaskForm
from flask_wtf.file import FileRequired
from werkzeug.utils import redirect, secure_filename
from datetime import datetime
from wtforms import StringField, TextAreaField, FileField
from wtforms.validators import InputRequired, Length
from helpers.models import db, Oglasi
bp = Blueprint("add_oglas", __name__)
class OglasForm(FlaskForm):
title = StringField("Title", validators=[InputRequired(), Length(min=1, max=20)])
body = TextAreaField("Text", validators=[InputRequired(), Length(min=1, max=200)])
img_url = FileField(
"",
validators=[
FileRequired(),
],
)
price = StringField("Price", validators=[InputRequired(), Length(min=1, max=10)])
@bp.route("/add_oglas", methods=["GET", "POST"])
@login_required
def add_oglas():
form = OglasForm()
if form.validate_on_submit():
f = form.img_url.data
filename = secure_filename(form.img_url.data.filename)
filename = datetime.strftime(datetime.now(), "%M%S") + filename
f.save(os.path.join(current_app.config["UPLOADED_IMAGES_DEST"], filename))
title = form.title.data
body = form.body.data
price = form.price.data
new_oglas = Oglasi(
title=title,
body=body,
user_id=current_user.id,
date_created=datetime.now().replace(microsecond=0),
price=price,
img_url=filename,
)
db.session.add(new_oglas)
db.session.commit()
return redirect(url_for("dashboard.dashboard"))
return render_template("dashboard.html", form=form)
|
{"/app.py": ["/beautifulsoup_bookstores/znanje.py", "/helpers/general.py", "/selenium_bookstores/knjiga.py", "/views/__init__.py", "/helpers/models.py"], "/views/edit_oglas.py": ["/helpers/models.py"], "/views/register.py": ["/helpers/models.py"], "/views/dashboard.py": ["/helpers/models.py", "/views/add_oglas.py"], "/views/oglasnik.py": ["/helpers/models.py"], "/views/delete_oglas.py": ["/helpers/models.py"], "/views/login.py": ["/helpers/models.py"], "/views/handle_data.py": ["/helpers/database.py"], "/helpers/database.py": ["/beautifulsoup_bookstores/znanje.py", "/helpers/general.py", "/helpers/models.py", "/selenium_bookstores/knjiga.py", "/selenium_bookstores/mozaik.py"], "/views/add_oglas.py": ["/helpers/models.py"]}
|
45,396,822
|
lea98/search_books
|
refs/heads/main
|
/views/logout.py
|
from flask import Blueprint, url_for
from flask_login import login_required, logout_user
from werkzeug.utils import redirect
bp = Blueprint("logout", __name__)
@bp.route("/logout")
@login_required
def logout():
logout_user()
return redirect(url_for("landing.index"))
|
{"/app.py": ["/beautifulsoup_bookstores/znanje.py", "/helpers/general.py", "/selenium_bookstores/knjiga.py", "/views/__init__.py", "/helpers/models.py"], "/views/edit_oglas.py": ["/helpers/models.py"], "/views/register.py": ["/helpers/models.py"], "/views/dashboard.py": ["/helpers/models.py", "/views/add_oglas.py"], "/views/oglasnik.py": ["/helpers/models.py"], "/views/delete_oglas.py": ["/helpers/models.py"], "/views/login.py": ["/helpers/models.py"], "/views/handle_data.py": ["/helpers/database.py"], "/helpers/database.py": ["/beautifulsoup_bookstores/znanje.py", "/helpers/general.py", "/helpers/models.py", "/selenium_bookstores/knjiga.py", "/selenium_bookstores/mozaik.py"], "/views/add_oglas.py": ["/helpers/models.py"]}
|
45,396,823
|
lea98/search_books
|
refs/heads/main
|
/views/__init__.py
|
from views import (
landing,
add_oglas,
dashboard,
delete_oglas,
edit_oglas,
handle_data,
login,
logout,
oglasnik,
register,
scraper,
)
blueprints = (
landing,
add_oglas,
dashboard,
delete_oglas,
edit_oglas,
handle_data,
login,
logout,
oglasnik,
register,
scraper,
)
|
{"/app.py": ["/beautifulsoup_bookstores/znanje.py", "/helpers/general.py", "/selenium_bookstores/knjiga.py", "/views/__init__.py", "/helpers/models.py"], "/views/edit_oglas.py": ["/helpers/models.py"], "/views/register.py": ["/helpers/models.py"], "/views/dashboard.py": ["/helpers/models.py", "/views/add_oglas.py"], "/views/oglasnik.py": ["/helpers/models.py"], "/views/delete_oglas.py": ["/helpers/models.py"], "/views/login.py": ["/helpers/models.py"], "/views/handle_data.py": ["/helpers/database.py"], "/helpers/database.py": ["/beautifulsoup_bookstores/znanje.py", "/helpers/general.py", "/helpers/models.py", "/selenium_bookstores/knjiga.py", "/selenium_bookstores/mozaik.py"], "/views/add_oglas.py": ["/helpers/models.py"]}
|
45,396,824
|
lea98/search_books
|
refs/heads/main
|
/views/landing.py
|
from flask import Blueprint, render_template
bp = Blueprint("landing", __name__)
@bp.route("/", methods=["GET", "POST"])
def index():
return render_template("landing.html")
|
{"/app.py": ["/beautifulsoup_bookstores/znanje.py", "/helpers/general.py", "/selenium_bookstores/knjiga.py", "/views/__init__.py", "/helpers/models.py"], "/views/edit_oglas.py": ["/helpers/models.py"], "/views/register.py": ["/helpers/models.py"], "/views/dashboard.py": ["/helpers/models.py", "/views/add_oglas.py"], "/views/oglasnik.py": ["/helpers/models.py"], "/views/delete_oglas.py": ["/helpers/models.py"], "/views/login.py": ["/helpers/models.py"], "/views/handle_data.py": ["/helpers/database.py"], "/helpers/database.py": ["/beautifulsoup_bookstores/znanje.py", "/helpers/general.py", "/helpers/models.py", "/selenium_bookstores/knjiga.py", "/selenium_bookstores/mozaik.py"], "/views/add_oglas.py": ["/helpers/models.py"]}
|
45,409,860
|
CadeSummers/Cryptocurrency_Analysis
|
refs/heads/main
|
/crypto_analysis.py
|
from bs4 import BeautifulSoup as bs
from urllib.request import urlopen
###Project Start: 6/14/21
###Project Last Updated: 6/21/21
####### Functions #######
#TODO this function does not work properly, but the for loop below does -- figure out why
#parsing top ten cryptocurrencies and other crypto currencies slightly different per website design -- This function grabs the top ten cryptocurrencies and their prices more easily. Similar to body of main.
def grab_top_ten():
names2 = []
prices2 = []
#for loop iterating through all elements of toptendata
for element in toptendata:
#convert element of type bs4 tag, to string
element = str(element)
#the index of the string which contains the name variable occurs following the "/currencies/" text in the html of the website
name_start = element.find("/currencies/")
#the index of the end of the string follows this piece of text: ""><div class=\"sc-16r8icm-0\"
name_end = element.find("/markets/")
#find the dollar sign value
price_start = element.find("$")
#find the decimal (cents) value and add 3 to account for the cents value we want to grab
price_end = element.find(".") + 3
names2.append(element[name_start:name_end])
prices2.append(element[price_start:price_end])
if len(names2) == len(prices2):
top_ten_key_info = zip(names2, prices2)
for item in top_ten_key_info:
item[0].strip("/currencies")
print(item)
return top_ten_key_info
####### Globals & Initialization #######
#initialization of the project, gaining info we need
url = "https://coinmarketcap.com/"
page = urlopen(url)
html = page.read().decode("utf-8")
soup = bs(html, "html.parser") #lxml or html.parser
text = soup.prettify()
######## TOTAL DATA GRAB ########
#grabs table row data from coinmarketcap.com and saves to variable named data
data = soup.find_all("tr")
#initialization of two lists to store the price and name of each cryptocurrency
names = []
prices = []
#for loop iterating through all elements of data
for element in data:
#convert element of type bs4 tag, to string
element = str(element)
#the index of the string which contains the name variable occurs following the "/currencies/" text in the html of the website
name_start = element.find("/currencies/")
#the index of the end of the string follows this piece of text: ""><div class=\"sc-16r8icm-0\"
name_end = element.find("><div class=\"sc-16r8icm-0\"")
#find the dollar sign value
price_start = element.find("$")
#find the decimal (cents) value and add 3 to account for the cents value we want to grab
price_end = element.find(".") + 3
names.append(element[name_start:name_end])
prices.append(element[price_start:price_end])
if len(names) == len(prices):
key_info = zip(names, prices)
for item in key_info:
item[0].strip("/currencies")
#print(item)
######## TOP TEN DATA GRAB ########
#grabs the data for the top ten cryptocurrencies
toptendata = soup.find_all("div", {"class" : "price___3rj7O"})
names2 = []
prices2 = []
#for loop iterating through all elements of toptendata
for element in toptendata:
#convert element of type bs4 tag, to string
element = str(element)
#the index of the string which contains the name variable occurs following the "/currencies/" text in the html of the website
name_start = element.find("/currencies/")
#the index of the end of the string follows this piece of text: ""><div class=\"sc-16r8icm-0\"
name_end = element.find("/markets/")
#find the dollar sign value
price_start = element.find("$")
#find the decimal (cents) value and add 3 to account for the cents value we want to grab
price_end = element.find(".") + 3
names2.append(element[name_start:name_end])
prices2.append(element[price_start:price_end])
if len(names2) == len(prices2):
top_ten_key_info = zip(names2, prices2)
for item in top_ten_key_info:
item[0].strip("/currencies")
print(item)
|
{"/merge_coin_dicts.py": ["/grab_others.py", "/toptendatagrab.py"], "/export_coin_info.py": ["/merge_coin_dicts.py"], "/export_to_database.py": ["/merge_coin_dicts.py"]}
|
45,459,557
|
xfluo2014/Priority-aware-LND-simulator
|
refs/heads/main
|
/p_mailbox.py
|
import random
import time
from pq import MyPriorityQueue
from multiprocessing import Process,Manager
from multiprocessing.managers import SyncManager
from channels import channel
import datetime
class MyManager(SyncManager):
pass
MyManager.register("PriorityQueue", MyPriorityQueue) # Register a shared PriorityQueue
def Manager():
m = MyManager()
m.start()
return m
class Prioritize:
def __init__(self, priority, item):
self.priority = priority
self.item = item
def __eq__(self, other):
return self.priority == other.priority
def __lt__(self, other):
return self.priority < other.priority
class Mailbox:
def __init__(self,p_id,chan,peerObjs,process_rate,num_priorities,queue_size,accelerate,fee_policy):
self.accelerate_mb = accelerate
self.peer_id = p_id
self.num_of_priorities = num_priorities
#htlc id and time stemp in each queue
self.queue_size = queue_size
self.m = Manager()
self.p_queue = self.m.PriorityQueue(queue_size)
#forwarding fee of each queue
self.p_fee = [x for x in fee_policy]
#processing rate 100 payments/s
self.processing_rate = process_rate
self.forward = Process(target=self.htlc_out,args=(chan,peerObjs))
#insert pay_hash of htlc and its rest priorities set (p_set) to corresponding queue (p).
#msg{create time, payment hash, rest hops, priorities set}
#msg = [payer, pay_hash, r_hop, p_set]
def htlc_in(self,msg):
#get the priority of payment for this peer
current_priority = msg['p_set'][0]
#remove current priority from list
msg['p_set'].pop(0)
in_queue = Prioritize(current_priority,msg)
#print('To priority queue:',in_queue)
self.p_queue.put(in_queue)
def htlc_out(self,chan,peerObjs):
while True:
current_time = datetime.datetime.now()
data_re = self.p_queue.remove(current_time)
while len(data_re)>0:
payer_id,p_hash = data_re.pop()
del peerObjs[payer_id].created_htlc[p_hash]
out_queue = self.p_queue.get(block=True)
msg = out_queue.item
#simulate the processing time
time.sleep(self.accelerate_mb/self.processing_rate)
#find target channel
#current_hop = msg['r_hop'][0]
current_time = datetime.datetime.now()
msg['trace'][str(chan.hop)] = current_time
chan.htlc_queue.put(msg)
'''
if current_hop[0]>current_hop[1]:
current_hop = tuple(reversed(list(current_hop)))
chan_str = 'channel'+str(current_hop[0])+str(current_hop[1])
target_chanID = hash(chan_str)
#send msg
for chan in ChanObjs:
if chan.channelID == target_chanID:
#insert the forwarding htlc msg into channel queue
msg['trace'][str(chan.hop)] = datetime.datetime.now()
chan.htlc_queue.put(msg)
break
chan = channel(1,(1,2))
mailbox = Mailbox(1,chan)
mailbox.p_queue.join()
msgs = [{'p_set':[1,1],'time':1,'r_hop':[(1,2),(2,3)]},{'p_set':[1,1],'time':2,'r_hop':[(1,2),(2,3)]}]
for msg in msgs:
mailbox.htlc_in(msg)
while mailbox.p_queue.empty() == False:
msg0 = mailbox.p_queue.get()
print(msg0.item)
'''
|
{"/simulation_lnd.py": ["/channels.py", "/p_peers.py", "/payments.py", "/a_core.py"], "/p_mailbox.py": ["/pq.py", "/channels.py"], "/a_core.py": ["/a_env.py", "/utilities.py"], "/p_peers.py": ["/p_mailbox.py", "/payments.py", "/a_core.py"]}
|
45,459,558
|
xfluo2014/Priority-aware-LND-simulator
|
refs/heads/main
|
/pq.py
|
import queue,heapq
from heapq import heappush, heappop
class MyPriorityQueue(queue.Queue):
def _init(self,maxsize):
self.queue = []
def _qsize(self):
return len(self.queue)
def _put(self,entry):
heappush(self.queue,entry)
def remove(self,t):
idx_list = [i for i,value in enumerate(self.queue) if value.item['expiry'] <= t]
data = []
while len(idx_list) > 0:
idx = idx_list.pop()
msg = self.queue[idx]
self.queue[idx] = self.queue[-1]
self.queue.pop()
heapq.heapify(self.queue)
data.append([msg.item['payer'],msg.item['pay_hash']])
return data
def _get(self):
return heappop(self.queue)
|
{"/simulation_lnd.py": ["/channels.py", "/p_peers.py", "/payments.py", "/a_core.py"], "/p_mailbox.py": ["/pq.py", "/channels.py"], "/a_core.py": ["/a_env.py", "/utilities.py"], "/p_peers.py": ["/p_mailbox.py", "/payments.py", "/a_core.py"]}
|
45,471,747
|
lucascplusmart/Django
|
refs/heads/master
|
/blog_dj/app_blog/migrations/0003_auto_20210105_1546.py
|
# Generated by Django 3.1.4 on 2021-01-05 18:46
from django.db import migrations, models
import django.db.models.manager
class Migration(migrations.Migration):
dependencies = [
('app_blog', '0002_auto_20210102_1603'),
]
operations = [
migrations.AlterModelManagers(
name='post',
managers=[
('publishedManager', django.db.models.manager.Manager()),
],
),
migrations.AlterField(
model_name='post',
name='slug',
field=models.SlugField(max_length=250),
),
]
|
{"/e_shop/product/admin.py": ["/e_shop/product/models.py"], "/blog_dj/app_blog/admin.py": ["/blog_dj/app_blog/models.py"], "/app_enquetes/polls/views.py": ["/app_enquetes/polls/models.py"], "/app_enquetes/polls/admin.py": ["/app_enquetes/polls/models.py"], "/blog_dj/app_blog/forms.py": ["/blog_dj/app_blog/models.py"], "/app_enquetes/polls/tests.py": ["/app_enquetes/polls/models.py"], "/blog_dj/accounts/views.py": ["/blog_dj/accounts/forms.py"]}
|
45,471,748
|
lucascplusmart/Django
|
refs/heads/master
|
/blog_dj/accounts/forms.py
|
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class UserCreationFormWithEmail(UserCreationForm):
email = forms.EmailField(required=True, help_text="Obrigatorio digite um e-mail valido")
class Meta:
model = User
fields = ('username', 'email')
def clean_email(self):
email = self.cleaned_data.get("email")
if User.objects.filter(email=email).exists():
raise forms.ValidationError("Este e-mail, já está cadastrado")
return email
|
{"/e_shop/product/admin.py": ["/e_shop/product/models.py"], "/blog_dj/app_blog/admin.py": ["/blog_dj/app_blog/models.py"], "/app_enquetes/polls/views.py": ["/app_enquetes/polls/models.py"], "/app_enquetes/polls/admin.py": ["/app_enquetes/polls/models.py"], "/blog_dj/app_blog/forms.py": ["/blog_dj/app_blog/models.py"], "/app_enquetes/polls/tests.py": ["/app_enquetes/polls/models.py"], "/blog_dj/accounts/views.py": ["/blog_dj/accounts/forms.py"]}
|
45,471,749
|
lucascplusmart/Django
|
refs/heads/master
|
/blog_dj/app_blog/admin.py
|
from django.contrib import admin
from .models import Post, Category
# Register your models here.
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
list_display = ('title','slug','author','published','status')
search_fields = ('title','content')
list_filter = ('status','created','published','author')
raw_id_fields = ('author', )
prepopulated_fields = {'slug':('title',)}
date_hierarchy = 'published'
readonly_fields = ('visualizar_imagem',)
def visualizar_imagem(self,obj):
return obj.view_image
visualizar_imagem.short_description = "Imagem cadastrada"
@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
list_display = ('name','created','published')
search_fields = ('name',)
list_filter = ('name','created','published')
date_hierarchy = 'published'
|
{"/e_shop/product/admin.py": ["/e_shop/product/models.py"], "/blog_dj/app_blog/admin.py": ["/blog_dj/app_blog/models.py"], "/app_enquetes/polls/views.py": ["/app_enquetes/polls/models.py"], "/app_enquetes/polls/admin.py": ["/app_enquetes/polls/models.py"], "/blog_dj/app_blog/forms.py": ["/blog_dj/app_blog/models.py"], "/app_enquetes/polls/tests.py": ["/app_enquetes/polls/models.py"], "/blog_dj/accounts/views.py": ["/blog_dj/accounts/forms.py"]}
|
45,471,750
|
lucascplusmart/Django
|
refs/heads/master
|
/app_enquetes/polls/views.py
|
# Create your views here.
'''
Uma view é um “tipo” de página Web em sua aplicação Django que em geral serve a uma função específica e tem um template específico.
Por exemplo,
=> em uma aplicação de blog, você deve ter as seguintes views:
-Página inicial do blog - exibe os artigos mais recentes.
-Página de “detalhes” - página de vínculo estático permanente para um único artigo.
-Página de arquivo por ano - exibe todos os meses com artigos para um determinado ano.
-Página de arquivo por mês - exibe todos os dias com artigos para um determinado mês.
-Página de arquivo por dia - exibe todos os artigos de um determinado dia.
-Ação de comentários - controla o envio de comentários para um artigo.
-Em nossa aplicação de enquetes, nós teremos as seguintes views:
Página de “índice” de enquetes - exibe as enquetes mais recente.
Question “detail” page – displays a question text, with no results but with a form to vote.
Página de “resultados” de perguntas - exibe os resultados de uma pergunta em particular.
Ação de voto - gerencia a votação para uma escolha particular em uma enquete em particular.'''
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.views import generic
from .models import Question, Choice
from django.utils import timezone
#from django.template import loader
#from django.http import Http404
# views genéricas: Menos código é melhor
"""
Nas partes anteriores deste tutorial, os templates tem sido fornecidos com um contexto que contém as variáveis question e latest_question_list. Para a DetailView a variavel question é fornecida automaticamente – já que estamos usando um modelo Django (Question), Django é capaz de determinar um nome apropriado para a variável de contexto. Contudo, para ListView, a variável de contexto gerada automaticamente é question_list. Para sobrescrever nós fornecemos o atributo context_object_name, especificando que queremos usar latest_question_list no lugar. Como uma abordagem alternativa, você poderia mudar seus templates para casar o novo padrão das variáveis de contexto – mas é muito fácil dizer para o Django usar a variável que você quer.
"""
class IndexView(generic.ListView):
template_name = 'polls/home.html'
context_object_name = 'latest_question_list'
'''
def get_queryset(self):
"""Return the last five published questions."""
return Question.objects.order_by('-pub_date')[:5]'''
def get_queryset(self):
return Question.objects.filter(
pub_date__lte=timezone.now()
).order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
model = Question
template_name = 'polls/detail.html'
def get_queryset(self):
"""
Excludes any questions that aren't published yet.
"""
return Question.objects.filter(pub_date__lte=timezone.now())
class ResultsView(generic.DetailView):
model = Question
template_name = 'polls/results.html'
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the question voting form.
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
'''
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
template = loader.get_template('polls/index.html')
context = {
'latest_question_list': latest_question_list,
}
return HttpResponse(template.render(context, request))
=> isto é equivalente a função index acima
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {'latest_question_list': latest_question_list}
return render(request, 'polls/index.html', context
'''
'''
def detail(request, question_id): # cada função é uma pagina web
return HttpResponse("You're looking at question %s." % question_id)'''
'''
def detail(request, question_id):
try:
question = Question.objects.get(pk=question_id)
except Question.DoesNotExist:
raise Http404("Question does not exist")
return render(request, 'polls/detail.html', {'question': question})'''
#=> metodo paythonic de levnatar as erro 404
'''
def detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/detail.html', {'question': question}) '''
'''
def results(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/results.html', {'question': question}) '''
'''
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
#Esta é a view mais simples possível no Django. Para chamar a view, nós temos que mapear a URL
# - e para isto nós precisamos de uma URLconf.
#Para criar uma URLconf no diretório polls, crie um arquivo chamado urls.py'''
|
{"/e_shop/product/admin.py": ["/e_shop/product/models.py"], "/blog_dj/app_blog/admin.py": ["/blog_dj/app_blog/models.py"], "/app_enquetes/polls/views.py": ["/app_enquetes/polls/models.py"], "/app_enquetes/polls/admin.py": ["/app_enquetes/polls/models.py"], "/blog_dj/app_blog/forms.py": ["/blog_dj/app_blog/models.py"], "/app_enquetes/polls/tests.py": ["/app_enquetes/polls/models.py"], "/blog_dj/accounts/views.py": ["/blog_dj/accounts/forms.py"]}
|
45,471,751
|
lucascplusmart/Django
|
refs/heads/master
|
/app_enquetes/polls/admin.py
|
from django.contrib import admin
# Register your models here.
from .models import Question, Choice
'''
=> admin.site.register(Question)
=> admin.site.register(Choice)
Ao registrarmos o modelo de Question através da linha admin.site.register(Question),
o Django constrói um formulário padrão para representá-lo. Comumente, você desejará
personalizar a apresentação e o funcionamento dos formulários do site de administração
do Django. Para isto, você precisará informar ao Django as opções que você quer utilizar
ao registrar o seu modelo.
'''
'''
Você seguirá este padrão – crie uma classe de “model admin”,
em seguida, passe-a como o segundo argumento para o admin.site.register()
– todas as vezes que precisar alterar as opções administrativas para um modelo.
'''
#=> com o codigo abaixo, é posso escolher qual campo aprece primeiro
'''
class QuestionAdmin(admin.ModelAdmin):
fields = ['pub_date', 'question_text']
admin.site.register(Question, QuestionAdmin)'''
#=> com o codigo abaixo, você pode querer dividir o formulário em grupos
# O primeiro elemento de cada tupla em fieldsets é o título do grupo. Aqui está como o nosso formulário se parece agora:
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date']}),
]
list_display = ('question_text', 'pub_date', 'was_published_recently')
list_filter = ['pub_date'] # O tipo do filtro apresentado depende do tipo do campo pelo qual você está filtrando
search_fields = ['question_text']
admin.site.register(Question, QuestionAdmin)
# => Com o TabularInline (em vez de StackedInline),
# os objetos relacionados são exibidos de uma maneira mais compacta, formatada em tabela:
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 3
|
{"/e_shop/product/admin.py": ["/e_shop/product/models.py"], "/blog_dj/app_blog/admin.py": ["/blog_dj/app_blog/models.py"], "/app_enquetes/polls/views.py": ["/app_enquetes/polls/models.py"], "/app_enquetes/polls/admin.py": ["/app_enquetes/polls/models.py"], "/blog_dj/app_blog/forms.py": ["/blog_dj/app_blog/models.py"], "/app_enquetes/polls/tests.py": ["/app_enquetes/polls/models.py"], "/blog_dj/accounts/views.py": ["/blog_dj/accounts/forms.py"]}
|
45,471,752
|
lucascplusmart/Django
|
refs/heads/master
|
/app_enquetes/polls/urls.py
|
from django.urls import path
from . import views
#A função path() são passado quatro argumentos, dois obrigatórios: route e view,
#e dois opcionais: kwargs, e name. Neste ponto, vale a pena revisar para o que estes argumentos servem.
'''
app_name = 'polls'
urlpatterns = [
# ex: /polls/
path('', views.index, name='index'),
# ex: /polls/5/
path('<int:question_id>/', views.detail, name='detail'),
# ex: /polls/5/results/
path('<int:question_id>/results/', views.results, name='results'),
# ex: /polls/5/vote/
path('<int:question_id>/vote/', views.vote, name='vote'),
]'''
app_name = 'polls'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
]
#O próximo passo é apontar na raiz da URLconf para o módulo polls.urls.
#No arquivo mysite/urls.py, adicione uma importação de django.urls.include e insira um include() na lista urlpatterns
|
{"/e_shop/product/admin.py": ["/e_shop/product/models.py"], "/blog_dj/app_blog/admin.py": ["/blog_dj/app_blog/models.py"], "/app_enquetes/polls/views.py": ["/app_enquetes/polls/models.py"], "/app_enquetes/polls/admin.py": ["/app_enquetes/polls/models.py"], "/blog_dj/app_blog/forms.py": ["/blog_dj/app_blog/models.py"], "/app_enquetes/polls/tests.py": ["/app_enquetes/polls/models.py"], "/blog_dj/accounts/views.py": ["/blog_dj/accounts/forms.py"]}
|
45,471,753
|
lucascplusmart/Django
|
refs/heads/master
|
/blog_dj/app_blog/forms.py
|
from ckeditor.widgets import CKEditorWidget
from .models import Post
from django import forms
class PostForm(forms.ModelForm):
#title = forms.CharField(max_length=100)
content = forms.CharField(widget=CKEditorWidget())
class Meta:
model = Post
fields = fields = ('title','content','image','status','category')
|
{"/e_shop/product/admin.py": ["/e_shop/product/models.py"], "/blog_dj/app_blog/admin.py": ["/blog_dj/app_blog/models.py"], "/app_enquetes/polls/views.py": ["/app_enquetes/polls/models.py"], "/app_enquetes/polls/admin.py": ["/app_enquetes/polls/models.py"], "/blog_dj/app_blog/forms.py": ["/blog_dj/app_blog/models.py"], "/app_enquetes/polls/tests.py": ["/app_enquetes/polls/models.py"], "/blog_dj/accounts/views.py": ["/blog_dj/accounts/forms.py"]}
|
45,471,754
|
lucascplusmart/Django
|
refs/heads/master
|
/app_enquetes/polls/tests.py
|
# Create your tests here.
import datetime
from django.test import TestCase
from django.utils import timezone
from .models import Question
class QuestionModelTests(TestCase):
def test_was_published_recently_with_future_question(self):
"""
was_published_recently() returns False for questions whose pub_date
is in the future.
"""
time = timezone.now() + datetime.timedelta(days=30)
future_question = Question(pub_date=time)
self.assertIs(future_question.was_published_recently(), False)
def test_was_published_recently_with_recent_question(self):
"""
was_published_recently() returns True for questions whose pub_date
is within the last day.
"""
time = timezone.now() - datetime.timedelta(hours=23, minutes=59, seconds=59)
recent_question = Question(pub_date=time)
self.assertIs(recent_question.was_published_recently(), True)
def create_question(question_text, days):
"""
Create a question with the given `question_text` and published the
given number of `days` offset to now (negative for questions published
in the past, positive for questions that have yet to be published).
"""
time = timezone.now() + datetime.timedelta(days=days)
return Question.objects.create(question_text=question_text, pub_date=time)
class QuestionIndexViewTests(TestCase):
def test_no_questions(self):
"""
If no questions exist, an appropriate message is displayed.
"""
response = self.client.get(reverse('polls:index'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, "No polls are available.")
self.assertQuerysetEqual(response.context['latest_question_list'], [])
def test_past_question(self):
"""
Questions with a pub_date in the past are displayed on the
index page.
"""
create_question(question_text="Past question.", days=-30)
response = self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context['latest_question_list'],
['<Question: Past question.>']
)
def test_future_question(self):
"""
Questions with a pub_date in the future aren't displayed on
the index page.
"""
create_question(question_text="Future question.", days=30)
response = self.client.get(reverse('polls:index'))
self.assertContains(response, "No polls are available.")
self.assertQuerysetEqual(response.context['latest_question_list'], [])
def test_future_question_and_past_question(self):
"""
Even if both past and future questions exist, only past questions
are displayed.
"""
create_question(question_text="Past question.", days=-30)
create_question(question_text="Future question.", days=30)
response = self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context['latest_question_list'],
['<Question: Past question.>']
)
def test_two_past_questions(self):
"""
The questions index page may display multiple questions.
"""
create_question(question_text="Past question 1.", days=-30)
create_question(question_text="Past question 2.", days=-5)
response = self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context['latest_question_list'],
['<Question: Past question 2.>', '<Question: Past question 1.>']
)
'''
1) manage.py test polls looked for tests in the polls application
2)ele encontrou uma subclass da classe django.test.TestCase
3)ele cria um banco de dados especial com o propósito de teste
4)ele procurou por métodos de test - aquele cujo nome começam com test
5)em test_was_published_recently_with_future_question é criado uma instância de Question na qual o campo pub_date está 30 dias no futuro
6)… e usando o método assertIs(), descobrimos que was_published_recently() retorna True, mas queremos que retorne False
O teste nos informa que teste falhou e até mesmo a linha na qual a falha ocorreu.
'''
'''
para corrigir esse problema, vá do model e adicione no modelo question a função
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now
'''
|
{"/e_shop/product/admin.py": ["/e_shop/product/models.py"], "/blog_dj/app_blog/admin.py": ["/blog_dj/app_blog/models.py"], "/app_enquetes/polls/views.py": ["/app_enquetes/polls/models.py"], "/app_enquetes/polls/admin.py": ["/app_enquetes/polls/models.py"], "/blog_dj/app_blog/forms.py": ["/blog_dj/app_blog/models.py"], "/app_enquetes/polls/tests.py": ["/app_enquetes/polls/models.py"], "/blog_dj/accounts/views.py": ["/blog_dj/accounts/forms.py"]}
|
45,471,755
|
lucascplusmart/Django
|
refs/heads/master
|
/blog_dj/app_blog/models.py
|
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
from django.utils.text import slugify
from django.db.models.signals import post_save
from django.dispatch import receiver
from ckeditor.fields import RichTextField
from django.utils.html import mark_safe
# Create your models here.
class PublishedManager(models.Manager):
def get_queryset(self):
return super(PublishedManager,self).get_queryset()\
.filter(status="publicado")
class Category(models.Model):
name = models.CharField(max_length=100)
published = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name = "Categoria"
verbose_name_plural = "Categorias"
ordering= ['-created']
def __str__(self):
return self.name
class Post(models.Model):
STATUS = (
('rascunho', 'Rascunho'),
('publicado','Publicado')
)
title = models.CharField(max_length=250, verbose_name="Título")
slug = models.SlugField(max_length=250)
author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Autor")
#content = models.TextField(verbose_name="Conteúdo")
content = RichTextField(verbose_name="Conteúdo")
published = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
changed = models.DateTimeField(auto_now=True)
status =models.CharField(max_length=10,choices=STATUS, default='rascunho')
image = models.ImageField(upload_to="blog",blank=True, null=True)
category = models.ManyToManyField(Category,related_name="get_posts" )
@property
def view_image(self):
return mark_safe('<img src="%s" width = "400px" /> ' %self.image.url)
class Meta:
ordering = ('-published',)
objects = models.Manager()
publishedManager = PublishedManager()
# url absoluta
def get_absolute_url(self):
#return reverse('detail',args=[self.pk])
return reverse('detail',args=[self.slug])
def get_absolute_update(self):
return reverse('post_edit',args=[self.slug])
#return reverse('post_edit',args=[self.pk])
def get_absolute_delete(self):
#return reverse('post_edits',args=[self.slug])
return reverse('post_delete',args=[self.pk])
def __str__(self):
return self.title
@receiver(post_save,sender=Post)
def insert_slug(sender,instance,**kwargs):
if not instance.slug:
instance.slug = slugify(instance.title)
return instance.save()
|
{"/e_shop/product/admin.py": ["/e_shop/product/models.py"], "/blog_dj/app_blog/admin.py": ["/blog_dj/app_blog/models.py"], "/app_enquetes/polls/views.py": ["/app_enquetes/polls/models.py"], "/app_enquetes/polls/admin.py": ["/app_enquetes/polls/models.py"], "/blog_dj/app_blog/forms.py": ["/blog_dj/app_blog/models.py"], "/app_enquetes/polls/tests.py": ["/app_enquetes/polls/models.py"], "/blog_dj/accounts/views.py": ["/blog_dj/accounts/forms.py"]}
|
45,471,756
|
lucascplusmart/Django
|
refs/heads/master
|
/app_enquetes/app_enquetes/urls.py
|
"""app_enquetes URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('', include('polls.urls')),
path('admin/', admin.site.urls),
]
'''
A função include() permite referenciar outras URLconfs. Qualquer lugar que o Django encontrar include(), irá recortar todas as partes da URL encontrada até aquele ponto e enviar a string restante para URLconf incluído para processamento posterior.
A idéia por trás do include() é facilitar plugar URLs. Uma vez que polls está em sua própria URLconf (polls/urls.py), ele pode ser colocado depois de “/polls/”, ou depois de “/fun_polls/”, u depois de “/content/polls/”, ou qualquer outro início de caminho, e a aplicação ainda irá funcionar
Quando usar include() Deve-se sempre usar include() quando você incluir outros padrões de URL. admin.site.urls é a única exceção a isso.
'''
|
{"/e_shop/product/admin.py": ["/e_shop/product/models.py"], "/blog_dj/app_blog/admin.py": ["/blog_dj/app_blog/models.py"], "/app_enquetes/polls/views.py": ["/app_enquetes/polls/models.py"], "/app_enquetes/polls/admin.py": ["/app_enquetes/polls/models.py"], "/blog_dj/app_blog/forms.py": ["/blog_dj/app_blog/models.py"], "/app_enquetes/polls/tests.py": ["/app_enquetes/polls/models.py"], "/blog_dj/accounts/views.py": ["/blog_dj/accounts/forms.py"]}
|
45,471,757
|
lucascplusmart/Django
|
refs/heads/master
|
/blog_dj/social/admin.py
|
from django.contrib import admin
from .models import Link
# Register your models here.
@admin.register(Link)
class LinkManager(admin.ModelAdmin):
readonly_fields = ('created','changed')
list_display = ('chave','created','changed')
|
{"/e_shop/product/admin.py": ["/e_shop/product/models.py"], "/blog_dj/app_blog/admin.py": ["/blog_dj/app_blog/models.py"], "/app_enquetes/polls/views.py": ["/app_enquetes/polls/models.py"], "/app_enquetes/polls/admin.py": ["/app_enquetes/polls/models.py"], "/blog_dj/app_blog/forms.py": ["/blog_dj/app_blog/models.py"], "/app_enquetes/polls/tests.py": ["/app_enquetes/polls/models.py"], "/blog_dj/accounts/views.py": ["/blog_dj/accounts/forms.py"]}
|
45,471,758
|
lucascplusmart/Django
|
refs/heads/master
|
/blog_dj/accounts/views.py
|
from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm
from django.urls import reverse_lazy
from django.views import generic
from .forms import UserCreationFormWithEmail
# Create your views here.
class SignUpView(generic.CreateView):
form_class = UserCreationFormWithEmail
success_url = reverse_lazy('login')
template_name = 'accounts/signup.html'
|
{"/e_shop/product/admin.py": ["/e_shop/product/models.py"], "/blog_dj/app_blog/admin.py": ["/blog_dj/app_blog/models.py"], "/app_enquetes/polls/views.py": ["/app_enquetes/polls/models.py"], "/app_enquetes/polls/admin.py": ["/app_enquetes/polls/models.py"], "/blog_dj/app_blog/forms.py": ["/blog_dj/app_blog/models.py"], "/app_enquetes/polls/tests.py": ["/app_enquetes/polls/models.py"], "/blog_dj/accounts/views.py": ["/blog_dj/accounts/forms.py"]}
|
45,471,759
|
lucascplusmart/Django
|
refs/heads/master
|
/blog_dj/contact/views.py
|
from django.shortcuts import render
from .forms import ContactForm
from django.core.mail import EmailMessage
# Create your views here.
def contact(request):
send = False
form = ContactForm(request.POST or None)
if form.is_valid():
nome = request.POST.get('nome','')
email = request.POST.get('email','')
mensagem = request.POST.get('mensagem','')
email=EmailMessage(
"Mensagem do blog django",
"de {} <{}>.Escreveu:\n\n {}".format(nome,email,mensagem),
"nao-responder@inbox.mailtrap.io",
["lucascplusmart@gmail.com"],
reply_to=[email]
)
try:
email.send()
except:
send = False
send = True
context = {
'form': form,
'success': send
}
return render(request,'contact/contact.html',context)
|
{"/e_shop/product/admin.py": ["/e_shop/product/models.py"], "/blog_dj/app_blog/admin.py": ["/blog_dj/app_blog/models.py"], "/app_enquetes/polls/views.py": ["/app_enquetes/polls/models.py"], "/app_enquetes/polls/admin.py": ["/app_enquetes/polls/models.py"], "/blog_dj/app_blog/forms.py": ["/blog_dj/app_blog/models.py"], "/app_enquetes/polls/tests.py": ["/app_enquetes/polls/models.py"], "/blog_dj/accounts/views.py": ["/blog_dj/accounts/forms.py"]}
|
45,471,760
|
lucascplusmart/Django
|
refs/heads/master
|
/app_enquetes/polls/models.py
|
# Create your models here.
from django.db import models
from django.utils import timezone
import datetime
'''
=> Um modelo é a fonte única e definitiva de dados sobre os seus dados.
Ele contém os campos e comportamentos essenciais dos dados que você está
gravando. Geralmente, cada modelo mapeia para uma única tabela no banco de dados.
O Django segue o princípio DRY. (Não repita a si mesmo), redudancia é ruim, normalizar é bom
=> O objetivo é definir seu modelo de dados em um único local e automaticamente derivar coisas(exemplo: tabela) a partir dele.
=> O básico:
1º) Cada modelo é uma classe Python que extende django.db.models.Model.
2º) Cada atributo do modelo representa uma coluna do banco de dados.
3º)Com tudo isso, o Django lhe dá uma API de acesso a banco de dados gerada automaticamente,
o que é explicado em Fazendo consultas.
'''
#exemplo:
'''
class Question(models.Model):
# são campos do modelo.
# Cada campo é especificado como um atributo de classe,
# e cada atributo é mapeado para uma coluna no banco de dados.
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
=> isso seria equivalente ao codigo PostgreSQL:
CREATE TABLE polls_question (
"id" serial NOT NULL PRIMARY KEY,
"question_text" varchar(200) NOT NULL,
"question_text" varchar(200) NOT NULL
);
O nome da tabela, myapp_person, é automaticamente derivado de alguns metadados do modelo, no entanto isto pode ser sobrescrito.
Um campo id é adicionado automaticamente, mas esse comportamento também pode ser alterado.
O comando SQL CREATE TABLE nesse exemplo é formatado usando a sintaxe do PostgreSQL,
mas é digno de nota que o Django usa o SQL adaptado ao banco de dados especificado no seu arquivo de configurações.
'''
class Question(models.Model):
# são campos do modelo.
# Cada campo é especificado como um atributo de classe,
# e cada atributo é mapeado para uma coluna no banco de dados.
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
"""
Esta função tem um problema
Se a publicação for no futuro a função retorna true.
Desde que coisas no futuro não são ‘recent’, isto é claramente um erro.
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)"""
'''
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now'''
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now
was_published_recently.admin_order_field = 'pub_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'
class Choice(models.Model):
# são campos do modelo.
# Cada campo é especificado como um atributo de classe,
# e cada atributo é mapeado para uma coluna no banco de dados.
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
'''
Finalmente, note que uma relação foi criada, usando ForeignKey(chave estrangeira).
Isso diz ao Django que cada Choice está relacionada a uma única Question, mas cada questão pode ter varias choice.
O Django oferece suporte para todos os relacionamentos comuns de um banco de dados: muitos-para-um, muitos-para-muitos e um-para-um.
[Question] 1:1 ----(relação)---- 1:N [Choice],
- toda questão há no minimo 1 altenativa e no maxmio varias alternativas
- toda alternativa está no minimo em 1 questão e no maximo em 1 questão
'''
|
{"/e_shop/product/admin.py": ["/e_shop/product/models.py"], "/blog_dj/app_blog/admin.py": ["/blog_dj/app_blog/models.py"], "/app_enquetes/polls/views.py": ["/app_enquetes/polls/models.py"], "/app_enquetes/polls/admin.py": ["/app_enquetes/polls/models.py"], "/blog_dj/app_blog/forms.py": ["/blog_dj/app_blog/models.py"], "/app_enquetes/polls/tests.py": ["/app_enquetes/polls/models.py"], "/blog_dj/accounts/views.py": ["/blog_dj/accounts/forms.py"]}
|
45,564,934
|
adrianborkowski/apod_pocket
|
refs/heads/dev
|
/request/migrations/0006_auto_20151018_1904.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import datetime
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('request', '0005_data_dat'),
]
operations = [
migrations.RemoveField(
model_name='data',
name='dat',
),
migrations.AddField(
model_name='data',
name='date_created',
field=models.DateField(default=datetime.datetime(2015, 10, 18, 17, 4, 54, 822490, tzinfo=utc)),
),
]
|
{"/request/get_json.py": ["/request/models.py"], "/request/get_older_jsons.py": ["/request/models.py"], "/request/get_newest_json.py": ["/request/models.py"], "/request/admin.py": ["/request/models.py"]}
|
45,564,935
|
adrianborkowski/apod_pocket
|
refs/heads/dev
|
/update.py
|
from apscheduler.schedulers.blocking import BlockingScheduler
sched = BlockingScheduler()
@sched.scheduled_job('interval', hours=1)
def timed_job():
from request import get_newest_json
sched.start()
|
{"/request/get_json.py": ["/request/models.py"], "/request/get_older_jsons.py": ["/request/models.py"], "/request/get_newest_json.py": ["/request/models.py"], "/request/admin.py": ["/request/models.py"]}
|
45,564,936
|
adrianborkowski/apod_pocket
|
refs/heads/dev
|
/request/get_older_jsons.py
|
from urllib.request import urlopen
from .models import Data
from datetime import date, timedelta
DATE = date(2016, 1, 8) # DATE OF BEGIN ADDING JSONS' DATA TO DB(YYYY, MM, DD)
for i in range(5): # HOW MANY DAYS ADD (SINCE DATE FROM VAR. DATE TO PAST)
past_url = 'https://api.nasa.gov/planetary/apod?concept_tags=True' \
'&date={date}' \
'&hd=True' \
'&api_key=DEMO_KEY'.format(date=DATE)
content = urlopen(past_url).read().decode("utf-8")
d = eval(content)
if 'hdurl' not in d:
hd_url = ''
else:
hd_url = d['hdurl']
Data.objects.create(title=d['title'], # ADDING DATA TO DB
url=d['url'],
hd_url=hd_url,
concepts=', '.join(d['concepts']),
explanation=d['explanation'],
media_type=d['media_type'],
created_date=DATE)
print("Successfully added {type} '{title}' from {date}.".format(type=d['media_type'], title=d['title'], date=DATE))
DATE = DATE - timedelta(days=1) # SUBTRACTING DATE, days - NUMBER OF DAYS TO SUBTRACT
|
{"/request/get_json.py": ["/request/models.py"], "/request/get_older_jsons.py": ["/request/models.py"], "/request/get_newest_json.py": ["/request/models.py"], "/request/admin.py": ["/request/models.py"]}
|
45,564,937
|
adrianborkowski/apod_pocket
|
refs/heads/dev
|
/request/get_newest_json.py
|
from urllib.request import urlopen
from .models import Data
from datetime import date
URL = 'https://api.nasa.gov/planetary/apod?concept_tags=True&hd=True&api_key=DEMO_KEY'
d = eval(urlopen(URL).read().decode("utf-8")) # CREATING DICTIONARY WHICH INCLUDE CONTENT OF URL (JSON).
qs = Data.objects.all()
if qs.filter(title=d['title']).exists(): # CHECKING IF LAST DATA TITLE IN DB IS THE SAME AS LAST JSON'S TITLE.
print("Data {type} '{title}' already exists.".format(type=d['media_type'], title=d['title']))
else:
if 'hdurl' not in d:
hd_url = ''
else:
hd_url = d['hdurl']
Data.objects.create(title=d['title'], # ADDING DATA TO DB
url=d['url'],
hd_url=hd_url,
concepts=', '.join(d['concepts']),
explanation=d['explanation'],
media_type=d['media_type'],
created_date=date.today())
print("Successfully added {type} '{title}'.".format(type=d['media_type'], title=d['title']))
|
{"/request/get_json.py": ["/request/models.py"], "/request/get_older_jsons.py": ["/request/models.py"], "/request/get_newest_json.py": ["/request/models.py"], "/request/admin.py": ["/request/models.py"]}
|
45,564,938
|
adrianborkowski/apod_pocket
|
refs/heads/dev
|
/request/migrations/0005_data_dat.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import datetime
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('request', '0004_auto_20151018_1850'),
]
operations = [
migrations.AddField(
model_name='data',
name='dat',
field=models.DateField(default=datetime.datetime(2015, 10, 18, 17, 0, 26, 35784, tzinfo=utc)),
),
]
|
{"/request/get_json.py": ["/request/models.py"], "/request/get_older_jsons.py": ["/request/models.py"], "/request/get_newest_json.py": ["/request/models.py"], "/request/admin.py": ["/request/models.py"]}
|
45,564,939
|
adrianborkowski/apod_pocket
|
refs/heads/dev
|
/request/migrations/0003_auto_20151018_1342.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('request', '0002_auto_20151018_1255'),
]
operations = [
migrations.AlterField(
model_name='data',
name='concepts',
field=models.CharField(max_length=200),
),
migrations.AlterField(
model_name='data',
name='media_type',
field=models.CharField(choices=[('image', 'Image'), ('video', 'Video')], max_length=10),
),
migrations.AlterField(
model_name='data',
name='title',
field=models.CharField(max_length=200),
),
]
|
{"/request/get_json.py": ["/request/models.py"], "/request/get_older_jsons.py": ["/request/models.py"], "/request/get_newest_json.py": ["/request/models.py"], "/request/admin.py": ["/request/models.py"]}
|
45,564,940
|
adrianborkowski/apod_pocket
|
refs/heads/dev
|
/request/admin.py
|
from django.contrib import admin
from .models import Data
class DataAdmin(admin.ModelAdmin):
search_fields = ('title', 'created_date')
list_display = ('title', 'created_date', 'media_type', 'concepts')
ordering = ['-created_date', ]
admin.site.register(Data, DataAdmin)
|
{"/request/get_json.py": ["/request/models.py"], "/request/get_older_jsons.py": ["/request/models.py"], "/request/get_newest_json.py": ["/request/models.py"], "/request/admin.py": ["/request/models.py"]}
|
45,564,941
|
adrianborkowski/apod_pocket
|
refs/heads/dev
|
/request/models.py
|
from django.db import models
MEDIA_TYPES = (
('image', 'Image'),
('video', 'Video'),
)
class Data(models.Model):
title = models.CharField(max_length=150)
created_date = models.DateField(null=True, blank=True)
url = models.URLField()
hd_url = models.URLField(null=True, blank=True)
media_type = models.CharField(max_length=10, choices=MEDIA_TYPES)
explanation = models.TextField()
concepts = models.CharField(max_length=200, blank=True)
def __str__(self):
return self.title
|
{"/request/get_json.py": ["/request/models.py"], "/request/get_older_jsons.py": ["/request/models.py"], "/request/get_newest_json.py": ["/request/models.py"], "/request/admin.py": ["/request/models.py"]}
|
45,697,272
|
animesh21/covid-vaccine-alerts
|
refs/heads/master
|
/main.py
|
from datetime import datetime
from constants import DATETIME_FORMAT
from cowin_client import CoWinClient
from twilio_client import TwilioClient
from utilities import get_active_users, get_active_district_ids, update_last_notified
def send_alerts():
district_ids = get_active_district_ids()
for district_id in district_ids:
print('Sending alerts for district_id: {}'.format(district_id))
send_district_alerts(district_id)
def send_district_alerts(district_id: int):
capacity = get_capacity(district_id)
print('Under 45 capacity: {}'.format(capacity))
# message to be send via WhatsApp
message = (f'Total {capacity} COVID-19 vaccine doses are available for the age group 18 to 44 currently. '
f'Please book your slot at {CoWinClient.home_url}')
# if capacity more than 5 then find the active users and notify them via WhatsApp
if capacity >= 5:
users = get_active_users(district_id=district_id)
recipient_phone_numbers = []
now = datetime.now()
print(f'users before filtering: {users}')
for user in users: # only the users who have not been notified in past 3 hours have to be notified
last_notified = user['last_notified'] and datetime.strptime(user['last_notified'], DATETIME_FORMAT)
if last_notified:
time_diff = now - last_notified
num_seconds_in_3_hours = 3 * 60 * 60
if time_diff.seconds > num_seconds_in_3_hours:
recipient_phone_numbers.append((user['id'], user['phone']))
else:
recipient_phone_numbers.append((user['id'], user['phone']))
# send update via WhatsApp using Twilio API
client = TwilioClient()
for user_id, to_number in recipient_phone_numbers:
res = client.send_whats_app_message(to_number, message)
if res: # update last_notified after successfully sending notification via WhatsApp
update_last_notified(user_id)
def get_capacity(district_id):
client = CoWinClient(district_id)
capacity = client.get_under_45_capacity()
# capacity = client.get_capacity_for_minimum_age(20)
return capacity
if __name__ == '__main__':
send_alerts()
|
{"/tasks.py": ["/main.py"], "/setup.py": ["/constants.py"], "/main.py": ["/constants.py", "/cowin_client.py", "/twilio_client.py", "/utilities.py"], "/utilities.py": ["/constants.py"], "/test_cowin_client.py": ["/cowin_client.py"], "/add_user.py": ["/constants.py"]}
|
45,731,651
|
yudanta/dodolbots
|
refs/heads/main
|
/config.py
|
import os
import sys
from os import path
from datetime import datetime, timedelta
APP_NAME = 'Simple Chat App'
BASEDIR = os.path.abspath(os.path.dirname(__file__))
# DEBUG
DEBUG = True
SECRET_KEY = 'ca2b84ac72a91a20cbda8be2d1f2c1fb7521'
# telegram configs
# TELEGRAM_BOT_TOKEN = '116624917:AAGVY6-uWzGQDESs-IBYX4u5v9kr18MeNEE'
TELEGRAM_BOT_TOKEN = os.getenv('TELEGRAM_BOT_TOKEN', '')
TELEGRAM_BOT_URL = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}"
|
{"/app/api/v_0_1/qa/__init__.py": ["/app/question_answering/__init__.py"], "/telegram/bot.py": ["/config.py"], "/app/__init__.py": ["/app/api/v_0_1/__init__.py"], "/run.py": ["/app/__init__.py"], "/app/tests/integrations/test_query_qa.py": ["/app/__init__.py"], "/telegram/serve.py": ["/telegram/bot.py", "/app/question_answering/__init__.py"], "/app/api/v_0_1/__init__.py": ["/app/api/v_0_1/qa/__init__.py"], "/app/question_answering/__init__.py": ["/app/__init__.py"]}
|
45,873,239
|
prakhar-ai/Hops-UI
|
refs/heads/main
|
/hops/views.py
|
from django.shortcuts import render
import requests
import json
from django.http import HttpResponse
from hops.models import OngoingJobs
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
# Create your views here.
def home_page(request):
return render(request,'base.html')
def report(request):
return render(request,'report.html')
def faqs(request):
return render(request,'faqs.html')
def login(request):
return render(request,'login.html')
def register(request):
return render(request,'register.html')
def files(request):
POST = request.POST
if POST:
typ = POST['type']
reason = POST['reason']
description = POST['description']
review = POST['review']
dicti = {
'type':typ,
'reason':reason,
'description':description,
'review':review
}
dataJSON = dumps(dicti)
return render(request,'comments.html',{'data':dataJSON})
else:
return render(request,'files.html')
def comments(request):
return render(request,'comments.html')
def vtkviewer(request):
return render(request,'vtkviewer.html')
def jobs(request):
data_dict = {}
study_ids = OngoingJobs.objects.all().values_list('studyid', flat=True)
study_ids = list(set(study_ids))
names = OngoingJobs.objects.all().values_list('name', flat=True)
id = ','.join(study_ids)
post_data = {'study_instance_ids': str(id)}
percent_completed = requests.post('http://192.168.1.196:5000/get_progress_percents', data=post_data)
percent_completed = json.loads(percent_completed.text)['status']
percent_completed = percent_completed.split(",")
status = []
for i in percent_completed:
if i=="100":
status.append('Completed')
else:
status.append('Ongoing')
headers = ['Name','Status','Percent Completed']
rows = []
for i in range(len(study_ids)):
row = []
row.append(study_ids[i])
row.append(status[i])
row.append(percent_completed[i])
row.append(names[i])
rows.append(row)
data_dict = {'headers' : headers, 'rows' : rows}
return render(request,'jobs.html',{'data_dict' : data_dict,'study_ids' : study_ids,'percent_completed': percent_completed})
@csrf_exempt
def getreport(request):
id = request.POST.get("studyid")
patient_name = request.POST.get("name")
jobs = OngoingJobs(studyid=id,name=patient_name)
jobs.save()
return JsonResponse({'result' : "Successful",'Name' : patient_name,"Study ID" : id})
def download_report(request,studyid):
"""
post_data = {'study_instance_id': str(studyid)}
response_path = requests.post('http://192.168.1.196:5000/get_report', data=post_data)
path_to_file = response_path.text """
path_to_file = r"C:\Users\Prakhar\Desktop\1.2.826.0.1.3680043.8.1678.101.10637297040685652766.532213_result.zip"
response = HttpResponse(content_type='application/zip')
with open(path_to_file, 'rb') as fh:
response = HttpResponse(fh.read(), content_type='application/zip')
response['Content-Disposition'] = 'inline; filename=' + studyid + ".zip"
return response
|
{"/hops/views.py": ["/hops/models.py"]}
|
45,914,965
|
zjustarstar/Pixelator
|
refs/heads/master
|
/pixelator_grid.py
|
import cv2
import numpy as np
def process001(img, outH, outW): #对轮廓区域进行处理
image = img
h0 = image.shape[0] # 高
w0 = image.shape[1] # 宽
if h0 == w0 and h0 % outH ==0: #正方形整除关系
Grid = h0/ outH
if Grid < 40:
pixel = Grid
h, w = int(pixel * outH), int(pixel * outW)
elif 40<= Grid <80:
pixel = int(Grid/2)
h, w = int(pixel * 2 * outH), int(pixel * 2 * outW)
elif 80<= Grid <160:
pixel = int(Grid/4)
h, w = int(pixel * 4 * outH), int(pixel * 4 * outW)
elif 160<= Grid <320:
pixel = int(Grid/8)
h, w = int(pixel * 8 * outH), int(pixel * 4 * outW)
elif h0 == w0 and h0 % outH !=0: #正方形不整除关系
Grid = int(h0 / outH) + 1 # 达到放大原图效果
if Grid < 40:
pixel = Grid
h, w = int(pixel * outH), int(pixel * outW)
elif 40 <= Grid < 80:
pixel = int(Grid / 2) +1
h, w = int(pixel * 2 * outH), int(pixel * 2 * outW)
elif 80 <= Grid < 160:
pixel = int(Grid / 4) +1
h, w = int(pixel * 4 * outH), int(pixel * 4 * outW)
elif 160 <= Grid < 320:
pixel = int(Grid / 8) +1
h, w = int(pixel * 8 * outH), int(pixel * 4 * outW)
elif h0 != w0 and h0 % outH ==0 and w0 % outW ==0: #长方形整除关系
if h0 > w0: #以短边计算Grid
Grid = w0/ outW
if Grid < 40:
pixel = Grid
h, w = int(pixel * outH), int(pixel * outW)
elif 40<= Grid <80:
pixel = int(Grid/2)
h, w = int(pixel * 2 * outH), int(pixel * 2 * outW)
elif 80<= Grid <160:
pixel = int(Grid/4)
h, w = int(pixel * 4 * outH), int(pixel * 4 * outW)
elif 160<= Grid <320:
pixel = int(Grid/8)
h, w = int(pixel * 8 * outH), int(pixel * 4 * outW)
elif h0 < w0: #以短边计算Grid
Grid = h0/ outH
if Grid < 40:
pixel = Grid
h, w = int(pixel * outH), int(pixel * outW)
elif 40<= Grid <80:
pixel = int(Grid/2)
h, w = int(pixel * 2 * outH), int(pixel * 2 * outW)
elif 80<= Grid <160:
pixel = int(Grid/4)
h, w = int(pixel * 4 * outH), int(pixel * 4 * outW)
elif 160<= Grid <320:
pixel = int(Grid/8)
h, w = int(pixel * 8 * outH), int(pixel * 4 * outW)
elif h0 != w0 and h0 % outH !=0 or w0 % outW !=0: #长方形不能整除关系
if h0 > w0: # 以短边计算Grid
Grid = int(w0 / outW) +1
if Grid < 40:
pixel = Grid
h, w = int(pixel * outH), int(pixel * outW)
elif 40 <= Grid < 80:
pixel = int(Grid / 2) +1
h, w = int(pixel * 2 * outH), int(pixel * 2 * outW)
elif 80 <= Grid < 160:
pixel = int(Grid / 4) +1
h, w = int(pixel * 4 * outH), int(pixel * 4 * outW)
elif 160 <= Grid < 320:
pixel = int(Grid / 8) +1
h, w = int(pixel * 8 * outH), int(pixel * 4 * outW)
elif h0 < w0: # 以短边计算Grid
Grid = int(h0 / outH) +1
if Grid < 40:
pixel = Grid
h, w = int(pixel * outH), int(pixel * outW)
elif 40 <= Grid < 80:
pixel = int(Grid / 2) +1
h, w = int(pixel * 2 * outH), int(pixel * 2 * outW)
elif 80 <= Grid < 160:
pixel = int(Grid / 4) +1
h, w = int(pixel * 4 * outH), int(pixel * 4 * outW)
elif 160 <= Grid < 320:
pixel = int(Grid / 8) +1
h, w = int(pixel * 8 * outH), int(pixel * 4 * outW)
reimage = cv2.resize(image, (w, h))
row = int(h / pixel)
col = int(w / pixel)
# 用于保存最终的目标像素图
final_pixelImg = np.ones([row, col], np.uint8) * 255
#以上是对原图进行格子划分,确定格子分辨率,和将原图划分为几行几列
#以下是对每个格子进行处理,主要是从图像轮廓颜色入手,通过计算格子中某颜色像素点占比而确定格子的处理放式
for i in range(row):
for j in range(col):
pixel_image = reimage[int(i * pixel) : int((i + 1) * pixel), int(j * pixel) : int((j + 1) * pixel)]
W = pixel_image.shape[0]
H = pixel_image.shape[1]
colorB = 0
colorW = 0
for row1 in range(0, H):
for col1 in range(0, W):
B = pixel_image[row1, col1, 0]
G = pixel_image[row1, col1, 1]
R = pixel_image[row1, col1, 2]
if B==G==R and R != 255 and G != 255 and B != 255:
colorB += 1
else:
colorW += 1
if colorB/(pixel*pixel) > 0.09:
pixel_image[:,:]= 0
final_pixelImg[i, j] = 0
# 转为RGB格式,方便在其它程序中使用;
final_pixelImg = cv2.cvtColor(final_pixelImg, cv2.COLOR_GRAY2BGR)
return reimage, final_pixelImg
def process002(img, outH, outW): #对非轮廓区域进行处理
image=img
h = image.shape[0] # 高
w = image.shape[1] # 宽
pixelH = int(h/outH)
pixelW = int(w/outW)
if h == w:
Pixel = pixelH
elif h > w:
Pixel = pixelW
elif h < w:
Pixel = pixelH
if Pixel<40:
pixel=Pixel
elif 40<= Pixel < 80:
pixel=int(Pixel/2)
elif 80<= Pixel < 160:
pixel=int(Pixel/4)
elif 160<= Pixel < 320:
pixel=int(Pixel/8)
row = int(h / pixel)
col = int(w / pixel)
for i in range(row):
for j in range(col):
pixel_image = image[i * pixel:(i + 1) * pixel, j * pixel:(j + 1) * pixel]
unique, counts = np.unique(pixel_image.reshape(-1, 3), axis=0, return_counts=True)
pixel_image[:, :, 0], pixel_image[:, :, 1], pixel_image[:, :, 2] = unique[np.argmax(counts)]
return image
|
{"/main.py": ["/pixel_one.py", "/pixelator_grid.py"]}
|
45,914,966
|
zjustarstar/Pixelator
|
refs/heads/master
|
/KMeans.py
|
import cv2
import numpy as np
from sklearn.cluster import KMeans
import glob
def calculate_perc(clusters):
width = 300
palette = np.zeros((50, width, 3), np.uint8)
steps = width / clusters.cluster_centers_.shape[0]
for idx, centers in enumerate(clusters.cluster_centers_):
palette[:, int(idx * steps):(int((idx + 1) * steps)), :] = centers
return palette
#K值聚类,获取30个颜色
clt = KMeans(n_clusters=30)
img = cv2.imread("D:\\project_paper\\process\\0407001\\A010.jpg")
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
clt_1 = clt.fit(img.reshape(-1, 3))
image = calculate_perc(clt_1)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
cv2.imwrite("D:\\project_paper\\process\\colors\\A010.png", image, [int(cv2.IMWRITE_PNG_COMPRESSION), 0])
|
{"/main.py": ["/pixel_one.py", "/pixelator_grid.py"]}
|
45,914,967
|
zjustarstar/Pixelator
|
refs/heads/master
|
/main.py
|
import cv2
import pixelator_grid as pl
import glob
import os
input_path = "F:\\PythonProj\\Pixelator\\testpic\\b2\\"
output_folder = "result\\"
outH = int(input('请输入目标输出高 H 的分辨率:'))
outW = int(input('请输入目标输出宽 W 的分辨率:'))
# 在当前目录自动生成用于保存的文件夹
if not os.path.exists(input_path+output_folder):
os.makedirs(input_path+output_folder)
imgfile = glob.glob(input_path + "*.png")
totalfile = len(imgfile)
i = 0
for f in imgfile:
i = i + 1
img = cv2.imread(f)
(filepath, filename) = os.path.split(f)
(shotname, extension) = os.path.splitext(filename)
print("当前正在处理 %d/%d :%s" % (i, totalfile, filename))
image01, pixel_img = pl.process001(img, outH, outW)
image02 = pl.process002(image01, outH, outW)
# 原图分辨率的像素图输出
outfile = input_path + output_folder + filename
cv2.imwrite(outfile, image01)
# 实际大小像素图输出,加分辨率后缀
h, w = pixel_img.shape[0], pixel_img.shape[1]
outfile = input_path + output_folder + shotname + "_" + str(h) + "_" + str(w) + extension
cv2.imwrite(outfile, pixel_img)
|
{"/main.py": ["/pixel_one.py", "/pixelator_grid.py"]}
|
45,914,968
|
zjustarstar/Pixelator
|
refs/heads/master
|
/pixel_one.py
|
import cv2
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from collections import Counter
import glob
def get_colors(infile): #获得图片颜色
image = Image.open(infile)
result = image.convert("P", palette=Image.ADAPTIVE)
palette = result.getpalette()
colors = list()
color_counts = sorted(result.getcolors(), reverse=True)
for i in range(len(color_counts)):
palette_index = color_counts[i][1]
dominant_color = palette[palette_index * 3: palette_index * 3 + 3]
colors.append(tuple(dominant_color))
main_colors = list()
thres = 15
for i, color in enumerate(colors):
flag = 0
if (main_colors != []):
for temp_color in main_colors:
if ((abs(color[0] - temp_color[0]) <= thres and abs(color[1] - temp_color[1]) <= thres)
or (abs(color[1] - temp_color[1]) <= thres and abs(color[2] - temp_color[2]) <= thres)
or (abs(color[0] - temp_color[0]) <= thres and abs(color[2] - temp_color[2]) <= thres)
or (abs(color[0] - temp_color[0]) <= thres and abs(color[1] - temp_color[1]) <= thres
and abs(color[2] - temp_color[2]) <= thres)):
flag = 1
if (flag == 0):
main_colors.append(color)
return main_colors
def get_colors_H(colors):#计算获得的颜色对应的色相(H值)
H=list()
for i in range(len(colors)):
r = colors[i][0]/255
g = colors[i][1]/255
b = colors[i][2]/255
Max = max(r,g,b)
Min = min(r,g,b)
C = Max - Min
if C == 0:
h = 0
elif Max == r:
if g >= b:
h= ((g-b)/C) * 60
else:
h = ((g-b)/C) * 60 + 360
elif Max == g :
h = ((b-r)/C) * 60 + 120
elif Max == b:
h = ((r-g)/C) * 60 +240
h0 = h/2
H.append(h0)
return H
def get_colors_Y(colors):#获得主要颜色对应的YUV中的Y值
Y = list()
for i in range(len(colors)):
r = colors[i][0]
g = colors[i][1]
b = colors[i][2]
y = 0.299*r + 0.587*g + 0.114*b
Y.append(y)
return Y
def get_CHY(colors,H,Y):
sorted_Y = sorted(enumerate(Y), key=lambda x: x[1])
idx_Y = [i[0] for i in sorted_Y]
Y = [i[1] for i in sorted_Y]
sorted_colors = list()
sorted_H = list()
for idx in idx_Y:
sorted_colors.append(colors[idx])
sorted_H.append(H[idx])
CHY=(sorted_colors,sorted_H,Y)
return CHY
def box_pixelation(image,CHY,outw,outh):#图片像素画处理
h0 = image.shape[0] # 高
w0 = image.shape[1] # 宽
if h0 <= w0:
for n in range(1000):
if 100 * (n - 1) <= h0 < 100 * n:
grid_h0 = n
for m in range(1000):
if 50 * (m-1)<= outh < 50*m:
grid_outh = m
grid = round((grid_h0 + grid_outh)/2)
h = grid * outh
w = grid * outw
elif h0 > w0:
for z in range(1000):
if 100 * (z - 1) <= w0 < 100 * z:
grid_w0 = z
for x in range(1000):
if 50 * (x - 1) <= outw < 50 * x:
grid_outw = x
grid = round((grid_w0 + grid_outw) / 2)
h = grid * outh
w = grid * outw
reimage = cv2.resize(image, (w, h))
row = int(h / grid)
col = int(w / grid)
for i in range(row):
for j in range(col):
grid_image = reimage[i * grid:(i + 1) * grid, j * grid:(j + 1) * grid]
row_grid = grid_image.shape[0]
col_grid = grid_image.shape[1]
Y = 256
B = 0
G = 0
R = 0
for n in range(row_grid):
for m in range(col_grid):
pixel_B = grid_image[n, m, 0]
pixel_G = grid_image[n, m, 1]
pixel_R = grid_image[n, m, 2]
pixel_Y = 0.299 * pixel_R + 0.587 * pixel_G + 0.114 * pixel_B
if pixel_Y < Y:
Y = pixel_Y
B = pixel_B
G = pixel_G
R = pixel_R
R1 = R / 255
G1 = G / 255
B1 = B / 255
Max = max(R1, G1, B1)
Min = min(R1, G1, B1)
C = Max - Min
if C == 0:
h0 = 0
elif Max == R1:
if G1 >= B1:
h0 = ((G1 - B1) / C) * 60
else:
h0 = ((G1 - B1) / C) * 60 + 360
elif Max == G:
h0 = ((B1 - R1) / C) * 60 + 120
elif Max == B:
h0 = ((R1 - G1) / C) * 60 + 240
H = h0 / 2
main_colors = CHY[0]
main_H = CHY[1]
main_Y = CHY[2]
r_c0 = abs(main_colors[0][0] - R)
g_c0 = abs(main_colors[0][1] - G)
b_c0 = abs(main_colors[0][2] - B)
r_c1 = abs(main_colors[1][0] - R)
g_c1 = abs(main_colors[1][1] - G)
b_c1 = abs(main_colors[1][2] - B)
if R==G==B<50:
M_color = (0,0,0)
elif Y<= main_Y[1]:
if (r_c0<15 and g_c0<15) or (r_c0<15 and b_c0<15) or (g_c0<15 and b_c0<15):
mcolor = main_colors[0]
# elif (r_c1<15 and g_c1<15) or (r_c1<15 and b_c1<15) or (g_c1<15 and b_c1<15):
# mcolor = main_colors[1]
elif (r_c0 < r_c1 and g_c0 < g_c1) or (r_c0 < r_c1 and b_c0 < b_c1) or (g_c0 < g_c1 and b_c0 < b_c1)\
or (r_c0 < r_c1 and g_c0 < g_c1 and b_c0 < b_c1):
mcolor = main_colors[0]
# elif (r_c0 > r_c1 and g_c0 > g_c1) or (r_c0 > r_c1 and b_c0 > b_c1) or (g_c0 > g_c1 and b_c0 > b_c1) \
# or (r_c0 > r_c1 and g_c0 > g_c1 and b_c0 > b_c1):
# mcolor = main_colors[1]
else:
continue
M_color = mcolor
# elif main_Y[0]< Y <= main_Y[1]:
# if (r_c1<15 and g_c1<15) or (r_c1<15 and b_c1<15) or (g_c1<15 and b_c1<15):
# mcolor = main_colors[1]
# elif (r_c0<15 and g_c0<15) or (r_c0<15 and b_c0<15) or (g_c0<15 and b_c0<15):
# mcolor = main_colors[0]
# elif (r_c0 < r_c1 and g_c0 < g_c1) or (r_c0 < r_c1 and b_c0 < b_c1) or (g_c0 < g_c1 and b_c0 < b_c1)\
# or (r_c0 < r_c1 and g_c0 < g_c1 and b_c0 < b_c1):
# mcolor = main_colors[0]
# elif (r_c0 > r_c1 and g_c0 > g_c1) or (r_c0 > r_c1 and b_c0 > b_c1) or (g_c0 > g_c1 and b_c0 > b_c1) \
# or (r_c0 > r_c1 and g_c0 > g_c1 and b_c0 > b_c1):
# mcolor = main_colors[1]
# else:
# continue
# M_color=mcolor
else:
continue
main_R = M_color[0]
main_G = M_color[1]
main_B = M_color[2]
grid_image[:, :, 2] = main_R
grid_image[:, :, 1] = main_G
grid_image[:, :, 0] = main_B
return reimage
# image_path = "D:\\project_paper\\process\\colors\\A010.png"
# outw = 50
# outh = 50
#
# img = cv2.imread("D:\\project_paper\\process\\0407001\\A010.jpg")
# # img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# colors = get_colors(image_path )
# H = get_colors_H(colors)
# Y = get_colors_Y(colors)
# CHY = get_CHY(colors,H,Y)
# pixel_image = box_pixelation(img,CHY,outw,outh)
#
# cv2.imwrite("D:\\project_paper\\process\\0225process\\B010.png", pixel_image, [int(cv2.IMWRITE_PNG_COMPRESSION), 0])
|
{"/main.py": ["/pixel_one.py", "/pixelator_grid.py"]}
|
45,932,593
|
carankt/FastSpeech2-1
|
refs/heads/hifi-fs2
|
/core/discriminator.py
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Discriminator(nn.Module):
def __init__(self):
super(Discriminator, self).__init__()
self.discriminator = nn.Sequential(
nn.Conv2d(1, 16, kernel_size=3, stride=1, padding = 1),
nn.LeakyReLU(0.2, inplace=True),
nn.Conv2d(16, 32, kernel_size=3, stride=1, padding = 1),
nn.LeakyReLU(0.2, inplace=True),
nn.Conv2d(32, 64, kernel_size=3, stride=1, padding = 1),
nn.LeakyReLU(0.2, inplace=True),
nn.Conv2d(64, 1, kernel_size=3, stride=1, padding = 1)
#nn.Flatten(), # add conv2d a 1 channel
#nn.Linear(46240,256)
)
def forward(self, x):
'''
we directly predict score without last sigmoid function
since we're using Least Squares GAN (https://arxiv.org/abs/1611.04076)
'''
# print(x.shape, "Input to Discriminator")
return self.discriminator(x)
def weights_init(m):
classname = m.__class__.__name__
if classname.find("Conv") != -1:
m.weight.data.normal_(0.0, 0.02)
elif classname.find("BatchNorm2d") != -1:
m.weight.data.normal_(1.0, 0.02)
m.bias.data.fill_(0)
class SFDiscriminator(nn.Module):
def __init__(self):
super().__init__()
self.disc1 = Discriminator()
self.disc2 = Discriminator()
self.disc3 = Discriminator()
self.apply(weights_init)
def forward(self, x, start):
results = []
results.append(self.disc1(x[:, :, start: start + 40, 0:40]))
results.append(self.disc2(x[:, :, start: start + 40, 20:60]))
results.append(self.disc3(x[:, :, start: start + 40, 40:80, ]))
return results
if __name__ == '__main__':
model = SFDiscriminator()
x = torch.randn(16, 1, 40, 80)
print(x.shape)
out = model(x)
print(len(out), "Shape of output")
pytorch_total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
print(pytorch_total_params)
|
{"/nvidia_preprocessing.py": ["/utils/util.py", "/dataset/audio/pitch_mod.py", "/dataset/audio/energy.py"], "/core/variance_predictor.py": ["/core/modules.py"], "/dataset/ljspeech.py": ["/utils/util.py"], "/utils/fastspeech2_script.py": ["/core/variance_predictor.py", "/utils/util.py", "/core/encoder.py", "/core/modules.py"], "/fastspeech.py": ["/core/variance_predictor.py", "/utils/util.py", "/core/encoder.py", "/core/modules.py"], "/core/encoder.py": ["/core/modules.py"], "/export_torchscript.py": ["/dataset/texts/__init__.py", "/utils/fastspeech2_script.py"], "/tests/test_fastspeech2.py": ["/dataset/texts/__init__.py", "/fastspeech.py"]}
|
45,932,594
|
carankt/FastSpeech2-1
|
refs/heads/hifi-fs2
|
/core/variance_predictor.py
|
import torch
import torch.nn.functional as F
from typing import Optional
from core.modules import LayerNorm
class VariancePredictor(torch.nn.Module):
def __init__(
self,
idim: int,
n_layers: int = 2,
n_chans: int = 256,
out: int = 1,
kernel_size: int = 3,
dropout_rate: float = 0.5,
offset: float = 1.0,
):
super(VariancePredictor, self).__init__()
self.offset = offset
self.conv = torch.nn.ModuleList()
for idx in range(n_layers):
in_chans = idim if idx == 0 else n_chans
self.conv += [
torch.nn.Sequential(
torch.nn.Conv1d(
in_chans,
n_chans,
kernel_size,
stride=1,
padding=(kernel_size - 1) // 2,
),
torch.nn.ReLU(),
LayerNorm(n_chans),
torch.nn.Dropout(dropout_rate),
)
]
self.linear = torch.nn.Linear(n_chans, out)
def _forward(
self,
xs: torch.Tensor,
is_inference: bool = False,
is_log_output: bool = False,
alpha: float = 1.0,
) -> torch.Tensor:
xs = xs.transpose(1, -1) # (B, idim, Tmax)
for f in self.conv:
xs = f(xs) # (B, C, Tmax)
# NOTE: calculate in log domain
xs = self.linear(xs.transpose(1, -1)).squeeze(-1) # (B, Tmax)
if is_inference and is_log_output:
# # NOTE: calculate in linear domain
xs = torch.clamp(
torch.round(xs.exp() - self.offset), min=0
).long() # avoid negative value
xs = xs * alpha
return xs
def forward(
self, xs: torch.Tensor, x_masks: Optional[torch.Tensor] = None
) -> torch.Tensor:
"""Calculate forward propagation.
Args:
xs (Tensor): Batch of input sequences (B, Tmax, idim).
x_masks (ByteTensor, optional): Batch of masks indicating padded part (B, Tmax).
Returns:
Tensor: Batch of predicted durations in log domain (B, Tmax).
"""
xs = self._forward(xs)
if x_masks is not None:
xs = xs.masked_fill(x_masks, 0.0)
return xs
def inference(
self, xs: torch.Tensor, is_log_output: bool = False, alpha: float = 1.0
) -> torch.Tensor:
"""Inference duration.
Args:
xs (Tensor): Batch of input sequences (B, Tmax, idim).
x_masks (ByteTensor, optional): Batch of masks indicating padded part (B, Tmax).
Returns:
LongTensor: Batch of predicted durations in linear domain (B, Tmax).
"""
return self._forward(
xs, is_inference=True, is_log_output=is_log_output, alpha=alpha
)
class EnergyPredictor(torch.nn.Module):
def __init__(
self,
idim,
n_layers=2,
n_chans=256,
kernel_size=3,
dropout_rate=0.1,
offset=1.0,
min=0,
max=0,
n_bins=256,
):
"""Initilize Energy predictor module.
Args:
idim (int): Input dimension.
n_layers (int, optional): Number of convolutional layers.
n_chans (int, optional): Number of channels of convolutional layers.
kernel_size (int, optional): Kernel size of convolutional layers.
dropout_rate (float, optional): Dropout rate.
offset (float, optional): Offset value to avoid nan in log domain.
"""
super(EnergyPredictor, self).__init__()
# self.bins = torch.linspace(min, max, n_bins - 1).cuda()
self.register_buffer("energy_bins", torch.linspace(min, max, n_bins - 1))
self.predictor = VariancePredictor(idim)
def forward(self, xs: torch.Tensor, x_masks: torch.Tensor):
"""Calculate forward propagation.
Args:
xs (Tensor): Batch of input sequences (B, Tmax, idim).
x_masks (ByteTensor, optional): Batch of masks indicating padded part (B, Tmax).
Returns:
Tensor: Batch of predicted durations in log domain (B, Tmax).
"""
return self.predictor(xs, x_masks)
def inference(self, xs: torch.Tensor, alpha: float = 1.0):
"""Inference duration.
Args:
xs (Tensor): Batch of input sequences (B, Tmax, idim).
x_masks (ByteTensor, optional): Batch of masks indicating padded part (B, Tmax).
Returns:
LongTensor: Batch of predicted durations in linear domain (B, Tmax).
"""
out = self.predictor.inference(xs, False, alpha=alpha)
return self.to_one_hot(out) # Need to do One hot code
def to_one_hot(self, x):
# e = de_norm_mean_std(e, hp.e_mean, hp.e_std)
# For pytorch > = 1.6.0
quantize = torch.bucketize(x, self.energy_bins).to(device=x.device) # .cuda()
return F.one_hot(quantize.long(), 256).float()
class PitchPredictor(torch.nn.Module):
def __init__(
self,
idim,
n_layers=2,
n_chans=384,
kernel_size=3,
dropout_rate=0.1,
offset=1.0,
min=0,
max=0,
n_bins=256,
):
"""Initilize pitch predictor module.
Args:
idim (int): Input dimension.
n_layers (int, optional): Number of convolutional layers.
n_chans (int, optional): Number of channels of convolutional layers.
kernel_size (int, optional): Kernel size of convolutional layers.
dropout_rate (float, optional): Dropout rate.
offset (float, optional): Offset value to avoid nan in log domain.
"""
super(PitchPredictor, self).__init__()
# self.bins = torch.exp(torch.linspace(torch.log(torch.tensor(min)), torch.log(torch.tensor(max)), n_bins - 1)).cuda()
self.register_buffer(
"pitch_bins",
torch.exp(
torch.linspace(
torch.log(torch.tensor(min)),
torch.log(torch.tensor(max)),
n_bins - 1,
)
),
)
self.predictor = VariancePredictor(idim)
def forward(self, xs: torch.Tensor, x_masks: torch.Tensor):
"""Calculate forward propagation.
Args:
xs (Tensor): Batch of input sequences (B, Tmax, idim).
x_masks (ByteTensor, optional): Batch of masks indicating padded part (B, Tmax).
Returns:
Tensor: Batch of predicted durations in log domain (B, Tmax).
"""
return self.predictor(xs, x_masks)
def inference(self, xs: torch.Tensor, alpha: float = 1.0):
"""Inference duration.
Args:
xs (Tensor): Batch of input sequences (B, Tmax, idim).
x_masks (ByteTensor, optional): Batch of masks indicating padded part (B, Tmax).
Returns:
LongTensor: Batch of predicted durations in linear domain (B, Tmax).
"""
out = self.predictor.inference(xs, False, alpha=alpha)
return self.to_one_hot(out)
def to_one_hot(self, x: torch.Tensor):
# e = de_norm_mean_std(e, hp.e_mean, hp.e_std)
# For pytorch > = 1.6.0
quantize = torch.bucketize(x, self.pitch_bins).to(device=x.device) # .cuda()
return F.one_hot(quantize.long(), 256).float()
class PitchPredictorLoss(torch.nn.Module):
"""Loss function module for duration predictor.
The loss value is Calculated in log domain to make it Gaussian.
"""
def __init__(self, offset=1.0):
"""Initilize duration predictor loss module.
Args:
offset (float, optional): Offset value to avoid nan in log domain.
"""
super(PitchPredictorLoss, self).__init__()
self.criterion = torch.nn.MSELoss()
self.offset = offset
def forward(self, outputs, targets):
"""Calculate forward propagation.
Args:
outputs (Tensor): Batch of prediction durations in log domain (B, T)
targets (LongTensor): Batch of groundtruth durations in linear domain (B, T)
Returns:
Tensor: Mean squared error loss value.
Note:
`outputs` is in log domain but `targets` is in linear domain.
"""
# NOTE: We convert the output in log domain low error value
# print("Output :", outputs[0])
# print("Before Output :", targets[0])
# targets = torch.log(targets.float() + self.offset)
# print("Before Output :", targets[0])
# outputs = torch.log(outputs.float() + self.offset)
loss = self.criterion(outputs, targets)
# print(loss)
return loss
class EnergyPredictorLoss(torch.nn.Module):
"""Loss function module for duration predictor.
The loss value is Calculated in log domain to make it Gaussian.
"""
def __init__(self, offset=1.0):
"""Initilize duration predictor loss module.
Args:
offset (float, optional): Offset value to avoid nan in log domain.
"""
super(EnergyPredictorLoss, self).__init__()
self.criterion = torch.nn.MSELoss()
self.offset = offset
def forward(self, outputs, targets):
"""Calculate forward propagation.
Args:
outputs (Tensor): Batch of prediction durations in log domain (B, T)
targets (LongTensor): Batch of groundtruth durations in linear domain (B, T)
Returns:
Tensor: Mean squared error loss value.
Note:
`outputs` is in log domain but `targets` is in linear domain.
"""
# NOTE: outputs is in log domain while targets in linear
# targets = torch.log(targets.float() + self.offset)
loss = self.criterion(outputs, targets)
return loss
|
{"/nvidia_preprocessing.py": ["/utils/util.py", "/dataset/audio/pitch_mod.py", "/dataset/audio/energy.py"], "/core/variance_predictor.py": ["/core/modules.py"], "/dataset/ljspeech.py": ["/utils/util.py"], "/utils/fastspeech2_script.py": ["/core/variance_predictor.py", "/utils/util.py", "/core/encoder.py", "/core/modules.py"], "/fastspeech.py": ["/core/variance_predictor.py", "/utils/util.py", "/core/encoder.py", "/core/modules.py"], "/core/encoder.py": ["/core/modules.py"], "/export_torchscript.py": ["/dataset/texts/__init__.py", "/utils/fastspeech2_script.py"], "/tests/test_fastspeech2.py": ["/dataset/texts/__init__.py", "/fastspeech.py"]}
|
45,978,032
|
vocart/Todo-App
|
refs/heads/master
|
/todo/urls.py
|
from . import views
from django.urls import path
urlpatterns = [
path('', views.home, name = 'home'),
path('delete/<todo_title>/', views.delete_todo, name = 'delete_todo')
]
|
{"/todo/views.py": ["/todo/forms.py"]}
|
45,978,033
|
vocart/Todo-App
|
refs/heads/master
|
/todo/views.py
|
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import Todo
from .forms import TodoForm
def home(request):
form = TodoForm()
todos = Todo.objects.all()
todo_data = []
for todo in todos:
todo_list = {
'name': todo.title,
'message': todo.message
}
todo_data.append(todo_list)
return render(request, 'todo/todo.html', {'todos':todos, 'todo_list':todo_list})
def delete_todo(request, todo_title):
Todo.objects.filter(title=todo_title).delete()
return redirect('home')
|
{"/todo/views.py": ["/todo/forms.py"]}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.