I want two content type like:
# in content_type_a.py
from content_type_b import IContentTypeB
class IContentTypeA(model.Schema):
content_type_bs = RelationList(
default=[],
value_type=RelationChoice(
source=ObjPathSourceBinder(
object_provides=IContentTypeB.__identifier__
),
),
required=False,
)
# in content_type_b.py
from content_type_a import IContentTypeA
class IContentTypeB(model.Schema):
content_type_as = RelationList(
default=[],
value_type=RelationChoice(
source=ObjPathSourceBinder(
object_provides=IContentTypeA.__identifier__
),
),
required=False,
)
But have error: ImportError: cannot import name IContentTypeA
any idea for me?
Thank you so much!
Related
from jupyter_plotly_dash import JupyterDash
import dash
import dash_leaflet as dl
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import dash_table
from dash.dependencies import Input, Output
import base64
import os
import numpy as np
import pandas as pd
from pymongo import MongoClient
from Module import AnimalShelter
username = "username"
password = "password"
animal = AnimalShelter(username, password)
df = pd.DataFrame.from_records(animal.readAll({}))
#########################
# Dashboard Layout / View
#########################
app = JupyterDash('Dash DataTable Only')
image_filename = 'Grazioso Salvare Logo.png' # customer image
encoded_image = base64.b64encode(open(image_filename, 'rb').read())
app.layout = html.Div([
html.Center(html.Img(src='data:image/png;base64,{}'.format(encoded_image.decode()))),
html.Center(html.B(html.H1('Kristopher Collis'))),
html.Hr(),
html.Div(
#Radio Items to select the rescue filter options
dcc.RadioItems(
id='filter-type',
),
),
html.Hr(),
dash_table.DataTable(
id='datatable-id',
columns=[
{"name": i, "id": i, "deletable": False, "selectable": True} for i in df.columns
],
data=df.to_dict('records'),
editable=False,
filter_action="native",
sort_action="native",
sort_mode="multi",
column_selectable=False,
row_selectable="multi",
row_deletable=False,
selected_columns=[],
selected_rows=[],
page_action="native",
page_current= 0,
page_size= 10,
),
html.Hr(),
html.Div(className='row',
style={'display' : 'flex'},
children =[
html.Div(
id='graph-id',
className='col s12 m6'
),
html.Div(
id = 'map-id',
className='col s12 m6'
),
]
),
html.Br(),
html.Hr(),
])
#############################################
# Interaction Between Components / Controller
#############################################
# #callback for Piechart
#app.callback(
Output('graph-id', "children"),
[Input('datatable-id', "derived_viewport_data")])
#fucntion for update_graph
def update_graphs(viewData):
dff = pd.DataFrame.from_dict(viewData)
names = dff['breed'].value_counts().keys().tolist()
values = dff['breed'].value_counts().tolist()
return[
dcc.Graph(
id = 'graph-id',
fig = px.pie(data_frame = dff,values = values,names = names,
color_discrete_sequence = px.colors.sequential.RdBu,width = 800,height = 500
)
)
]
#callback for update_map
#app.callback(
Output('map-id', "children"),
[Input('datatable-id', "derived_viewport_data"),
Input('datatable-id', 'selected_rows'),
Input('datatable-id', 'selected_columns')])
#update_function with variables
def update_map(viewData, selected_rows, selected_columns):
dff = pd.DataFrame.from_dict(viewData)
#width, height of map, center of map, and how much zoom do you want for map
return [dl.Map(style = {'width': '1000px', 'height': '500px'}, center = [30.75,-97.48], zoom = 7,
children = [dl.TileLayer(id = "base-layer-id"),
#marker with tool tip and popup
dl.Marker(position=[(dff.iloc[selected_rows[0],13]), (dff.iloc[selected_rows[0],14])], children=[
dl.Tooltip(dff.iloc[selected_rows[0],4]),
dl.Popup([
html.H4("Animal Name"),
html.P(dff.iloc[selected_rows[0],9]),
])
])
])
]
app
When I run the program, the geoloction map populates but not the graph. I was able to populate the graph a couple of times finding information on plotly, and other documentation. I have spent a while trying to figure out why the graph will not display again. I did attempt to use fig.show() at the bottom of the update_graphs function. I am not sure if that was what made it work, but I am stumped. I am respectfully requesting help finding the error in the def update_graphs function.
import requests
import telegram
import json
from telegram.ext import Updater, CommandHandler
import time
import sys
import pandas as pd
from apscheduler.schedulers.background import BlockingScheduler
from apscheduler.jobstores.base import JobLookupError
dt = requests.get('https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD,EUR')
print(dt.text)
price_now = dt.json()
bot_token = "5668522544:AAFqNFcgd5wDBtQbJBhRayfPx9VpVPVjcyQ"
Cointimeline = telegram.Bot(token=bot_token)
updates = Cointimeline.getUpdates()
for i in updates:
print(i.message)
class Chatbot:
def __init__(self, token):
self.core = telegram.Bot(token)
self.updater = Updater(token)
self.id = 5734902861
def sendmsg(self, text):
self.core.sendmsg(chat_id=self.id, text=text)
def stop(self):
self.updater.stop()
class Alert(Chatbot):
def __init__(self):
self.token = '5668522544:AAFqNFcgd5wDBtQbJBhRayfPx9VpVPVjcyQ'
Chatbot.__init__(self, self.token)
self.updater.stop()
def controller(self, cmd, func):
self.updater.dispatcher.controller(CommandHandler(smd, func))
def start(self):
self.sendMessage('')
aps = BlockingScheduler()
def push():
dt = requests.get("https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD,EUR")
ALERTBOT = Alert()
ALERTBOT.sendmsg(dt.text)a
price_now = pd.DataFrame({"USD": {list(dt.json().values())[0]}, "EUR": [list(dt.json().values())[1]]})
data = pd.read_csv("ALERTBOT.csv")
data = data.append(price_now, sort=True)
data = data.loc[:, 'USD':'EUR']
data.to_csv("ALERTBOT.csv")
aps.add_job(push, 'interval', seconds=60)
aps.start()
The error continues to occur.
PytzUsageWarning: The zone attribute is specific to pytz's interface; please migrate to a new time zone provider. For more details on how to do so, see https://pytz-deprecation-shim.readthedocs.io/en/latest/migration.html
if obj.zone == 'local':
The error is caused by the pytz library being out of date. You can solve the problem by updating the library:
pip install --upgrade pytz
I'm trying to perform a count vectorization using this function I've created however, I keep having an error returned stating "column not iterable" which I cannot figure out why and how to resolve it.
(dfNew is the data frame with just two of the columns, both of StringType)
import string
import re
import nltk
from nltk.stem import PorterStemmer
from sklearn.feature_extraction.text import CountVectorizer
ps = PorterStemmer()
dfNew = df.select(F.col('Description'), F.col('ID'))
def clean_description(text):
text = "".join([word.lower() for word in text if word not in string.punctuation])
text = re.sub('[\n\r]+', ' ', text).lower()
Description = re.split('\W+', text)
text = [ps.stem(word) for word in Description if word not in nltk.corpus.stopwords.words('english')]
more_stop_words = ['please', 'search', 'submitted', 'thank', 'search', 'com', 'url', 'https', 'via', 'www']
text = [ps.stem(word) for word in Description if word not in more_stop_words]
return text
count_vectorize = CountVectorizer(analyzer=clean_description)
vectorized = count_vectorize.fit_transform(dfNew['Description'])
What am I doing wrong, and how can this be resolved?
I have the following form classes:
class FieldsRequiredForm(FlaskForm):
class Meta:
def render_field(self, field, render_kw):
render_kw.setdefault('required', True)
return super().render_field(field, render_kw)
class SingleStringFieldForm(FieldsRequiredForm):
def __init__(self, field_label=None, question_id=None,
submit_label='Submit'):
super().__init__()
SingleStringFieldForm.answer = StringField(field_label)
SingleStringFieldForm.question_id = HiddenField(default=question_id)
SingleStringFieldForm.submit = SubmitField(submit_label)
class SingleRadioFieldForm(FieldsRequiredForm):
def __init__(self, field_label=None, question_id=None,
submit_label='Submit', choices=None):
super().__init__()
SingleRadioFieldForm.answer = RadioField(field_label, choices=choices)
SingleRadioFieldForm.question_id = HiddenField(default=question_id)
SingleRadioFieldForm.submit = SubmitField(submit_label)
The function that's using these forms looks like this:
#bp.route('/survey/<string:slug>', methods=['GET', 'POST'])
def question(slug):
survey = Survey.query.filter_by(slug=slug).first_or_404()
questions = survey.questions
question_ids = [question.id for question in questions]
if 'answers' not in session:
session['answers'] = json.dumps({id: None for id in question_ids})
answers = json.loads(session['answers'])
if request.method == 'POST':
record_submitted_answer()
answers = json.loads(session['answers'])
if None in answers.values():
question = get_next_question()
if question.category == 'word':
form = SingleStringFieldForm(field_label=question.question,
question_id=question.id)
elif question.category == 'likert':
form = SingleRadioFieldForm(field_label=question.question,
question_id=question.id,
choices=tuple(likert().items()))
else:
form = SingleStringFieldForm()
if form.validate_on_submit():
if None not in answers.values():
write_answers_to_database(survey=survey)
with open('app/static/ty.txt', 'r') as f:
ty = [x.strip() for x in f.readlines()]
return render_template('ty.html', ty=ty)
return redirect(url_for('survey.question', slug=slug))
return render_template('survey.html', form=form, answers=answers)
The first time I load the page after clearing the session, the form doesn't show up, and when I'm stepping through with a debugger when that happens, the debugger reports that form.answer has a value of:
<UnboundField(RadioField, ('Question 1',), {'choices': (('1', 'Strongly Agree'),
('2', 'Agree'), ('3', 'Neutral'), ('4', 'Disagree'), ('5', 'Strongly Disagree'))})>
If I reload the page, it has this value:
<app.survey.forms.SingleRadioFieldForm object at 0x110788d30>
I don't notice anything else different in the state of the program between the two page loads.
What is causing this the first time and how can I fix it?
While I still don't know why the original function wasn't working on first page load, but did on a reload, I went about this in another way and solved the problem. Instead of setting the fields within __init__, I subclassed within the function and edited the class directly.
#bp.route('/survey/<string:slug>', methods=['GET', 'POST'])
def survey(slug):
class F(FieldsRequiredForm):
pass
...
if None in answers.values():
question = get_next_question()
F.question_id = HiddenField(default=question.id)
if question.category == 'word':
F.answer = StringField(question.question)
elif question.category == 'likert':
F.answer = RadioField(question.question, choices=tuple(likert().items()))
F.submit = SubmitField('Submit')
else:
F.answer = StringField()
form = F()
...
I'm getting this error while trying to access a WS using SUDS in Python.
Any idea of what am I doing wrong? (Yes, I'm quite new to Python)
Python Code
# -*- coding: utf-8 -*-
from suds.client import Client
from apscheduler.scheduler import Scheduler
import datetime
import logging
from email.header import Header
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from smtplib import SMTP_SSL
from colorlog import ColoredFormatter
# Configurações do Log
logging.basicConfig(format='%(asctime)s - %(message)s', datefmt='%d/%m/%Y %H:%M:%S', filename='ConfirmarPedidoSmsBroker-Test.log',level=logging.INFO)
logging.getLogger().addHandler(logging.StreamHandler())
now = datetime.datetime.now()
#Informações para o consumo do WS
WSDL_URL = "http://123.168.1.132:8084/abc-ws-provider/AbcBrokerBSv1.0?wsdl"
#Criações dos tipos para gerar o objeto complexo
class Evale(object):
codigoDeAutorizacao = 1234567
class Cliente (object):
identificacaoDoCliente = 12345
codigoDoCliente = 101010
razaoSocial = "None"
class Telefone (object):
ddd = 21
numero = 1234-5678
class Contato (object):
telefone = Telefone()
class HorariosDeAtendimento (object):
diaDaSemana = "Sunday"
horaInicial = "07:30:00"
horaFinal = "20:00:00"
class TipoDeAtendimentoRealizado (object):
horariosDeAtendimento = HorariosDeAtendimento()
class Revenda (object):
cliente = Cliente()
identificacaoDoEndereco = 987654
codigoDoEndereco = 8765567
numeroDoDocumento = "2312341"
filialDoDocumento = 0009
digitoDoDocumento = 32
class RevendaPrincipal(object):
revenda = Revenda()
class RevendaAlternativa(object):
revenda = Revenda()
class EnderecoDoSolicitante(object):
logradouro = "Street Test"
numeroDoEndereco = 80
complemento = "Penth"
municipio = "New York"
bairro = "Brooklin"
cep = "74123"
estado = "NY"
class PedidoSms(object):
identificacaoDaTransacao = 1010
evale = Evale()
revendaPrincipal = RevendaPrincipal()
revendaAlternativa = RevendaAlternativa()
enderecoDoSolicitante = EnderecoDoSolicitante()
latitudeDoEnderecoDoSolicitante = -92.123443
longitudeDoEnderecoDoSolicitante = -81.98765
class ConfirmarPedidoSmsBrokerRequest(object):
pedidoSms = PedidoSms()
class ConfirmarPedidoSmsBroker_InputVariable (object):
confirmarPedidoSmsBrokerRequest = ConfirmarPedidoSmsBrokerRequest()
class Input (object):
confirmarPedidoSmsBroker_InputVariable = ConfirmarPedidoSmsBroker_InputVariable()
# Método que chama o serviço
def sendRequestToService():
confPedido = Input()
logging.info("ConfirmarPedidoSmsBroker-Test at " + str(now))
logging.info("WSDL_URL " + WSDL_URL)
logging.info("Passing URL to Client")
client = Client(WSDL_URL)
logging.info("Trying to access the service")
response = client.service.confirmarPedidoSmsBroker(confPedido)
logginf.info(response)
if __name__ == '__main__':
sendRequestToService()
And this is the error that I get whenever I try to run it.
06/02/2014 17:06:17 - ConfirmarPedidoSmsBroker-Test at 2014-02-06 17:06:17.443663
06/02/2014 17:06:17 - WSDL_URL http://111.168.1.132:8084/abc-ws-provider/AbcBrokerBSv1.0?wsdl
06/02/2014 17:06:17 - Passing URL to Client
06/02/2014 17:06:17 - Import:0x10ab61d10, imported schema (http://www.abcdef.com.br/Abab/BO/v3) at (http://123.168.1.132:8084/../../../../../Abc/Def/Somethingv3.xsd), failed
Traceback (most recent call last):
File "build/bdist.macosx-10.9-intel/egg/suds/xsd/sxbasic.py", line 560, in download
d = reader.open(url)
File "build/bdist.macosx-10.9-intel/egg/suds/reader.py", line 79, in open
d = self.download(url)
File "build/bdist.macosx-10.9-intel/egg/suds/reader.py", line 95, in download
fp = self.options.transport.open(Request(url))
File "build/bdist.macosx-10.9-intel/egg/suds/transport/https.py", line 60, in open
return HttpTransport.open(self, request)
File "build/bdist.macosx-10.9-intel/egg/suds/transport/http.py", line 64, in open
raise TransportError(str(e), e.code, e.fp)
TransportError: HTTP Error 400: Bad Request
It seems your WSDL service is responding with a 400 error for the request you passed (perhaps it's missing required arguments, etc..) please try to add debug logging like so:
import logging
logging.basicConfig(level=logging.DEBUG)
logging.getLogger('suds.client').setLevel(logging.DEBUG)
After doing that, give it another go (you can just open the interactive python shell and paste in your code, enable logging and invoke the sendRequestToService function.
Please revise your question with updates and I will revise my answer as appropriate.