I'm trying to make a app similar a menu. I already did scrollview with gridLayout, but I don't know how to show this separate, for instance, in the left column names, and in the right column age, in this way the app may have variable number of rows (infinity). I hope I have been less confusing as possible, the same for my english. Thanks everybody, I didn't post my code here because I think it isn't necessary. Bye, have a good day.
Ass is important I post my code here, I'm going to try to post. I'm sorry for the mistakes like indent.
.py
class PrimeiroScreen(Screen):
def __init__(self, **kwargs):
self.name = 'home'
super(Screen,self).__init__(**kwargs)
class SegundoScreen(Screen):
text = StringProperty('')
def __init__(self, **kwargs):
self.name = 'dois'
super(Screen,self).__init__(**kwargs)
class RootScreen(ScreenManager):
pass
class scrollmanageApp(App):
def build(self):
return RootScreen()
if __name__ == '__main__':
appVar = scrollmanageApp()
scrollmanageApp().run()
.kv
<RootScreen>:
PrimeiroScreen:
SegundoScreen:
<PrimeiroScreen>:
BoxLayout:
size_hint: (.3,.15)
pos_hint:{'x': .35, 'y': .84}
Label:
text: "Teste de uniĆ£o scrollview com screenmanage"
font_size: '30dp'
GridLayout:
cols: 1
rows: 2
size_hint: (.20,.10)
pos_hint:{'x': .25, 'y': .64}
Button:
text: "Scrollview!"
font_size: '30dp'
text_size: self.size
on_press: root.manager.current = 'dois'
<SegundoScreen>:
text: 'This is just a test ' * 50
ScrollView:
size_hint: 1, 1
pos_hint:{'x': .0, 'y': .0}
size: 100, 100
GridLayout:
cols: 2
#rows:
padding: 10
spacing: 10
size_hint: None, None
width: 500
height: self.minimum_height
Label:
text: root.text
font_size: 50
text_size: self.width, None
size_hint_y: None
height: self.texture_size[1]
Button:
text: "Voltar!"
size_hint: .1, .1
pos_hint:{'x': .9, 'y': .0}
text_size: self.width, None
on_press: root.manager.current = 'home'
I hope I had sucess in this time(post my code).Very thanks!
Related
i have a label that prints out data and it needs to be scrollable.
so it scrolls now but it does not have a scroll bar and the text bounces back to top once you release it.I have tried adding bar_width: 10 changed nothing.
from kivy.lang import Builder
from kivymd.uix.scrollview import MDScrollView
from kivy.properties import StringProperty, ObjectProperty
from kivymd.uix.pickers import MDDatePicker
from kivymd.app import MDApp
import json
KV = '''
MDScreenManager:
MDScreen:
name: "main"
MDGridLayout:
cols: 1
MDRaisedButton:
font_size: "32sp"
text: "Enter payments"
pos_hint: {"y": .2, "center_x" : .5}
size_hint: 1, 1
on_release:
root.current = "enter"
MDRaisedButton:
font_size: "32sp"
text: "Check payments"
pos_hint: {"y": .6, "center_x" : .5}
size_hint: 1, 1
on_release:
root.current = "view"
MDScreen:
#----------------------------------------------------------------------------------------------------------------------
name: "enter"
MDFloatLayout:
MDLabel:
text: "Date"
pos_hint: {"x" : 0, "center_y" : .9}
size_hint: None, None
MDIconButton:
icon: "calendar"
pos_hint: {"center_x": .3, "center_y": .9}
on_release: app.show_date_picker()
MDTextField:
id: date
helper_text: "Enter a valid date yyyy/mm/dd "
date_format: 'yyyy/mm/dd'
validator: "date"
hint_text: "Enter date"
pos_hint: {"center_x" : 0.9, "center_y" : .9}
text: ""
MDLabel:
text: "Case id"
pos_hint: {"x": 0, "center_y": .8}
MDTextField:
id: case_id
hint_text: "Enter case id"
pos_hint: {"center_x": .9, "center_y": .8}
MDLabel:
text: "Payment type"
size_hint: 1, None
pos_hint: {"x": 0, "center_y": .7}
MDTextField:
id: payment_type
hint_text: "Payment type"
pos_hint: {"center_x": .9, "center_y": .7}
MDLabel:
text: "Amount"
pos_hint: {"x" : 0, "center_y": .6}
MDSwitch:
pos_hint: {"center_y" : 0.6, "center_x" : 0.3}
on_active: app.on_checkbox_active(*args)
MDTextField:
id: amount
hint_text: "Enter amount"
pos_hint: {"center_x": .9, "center_y": .6}
MDRaisedButton:
text: "Submit"
pos_hint: {"y": .2, "center_x" : .5}
size_hint: 1, 0.3
on_release: app.add_payment()
MDRaisedButton:
text: "Go back"
pos_hint: {"y": 0, "center_x" : .5}
size_hint: 1, 0.25
on_release:
root.current = "main"
#---------------------------------------------------------------------------------------------------------------
MDScreen:
name: "view"
MDFloatLayout:
MDScrollView:
do_scroll_x: False
padding: 10, 10
scroll_type: ['content', 'bars' ]
bar_width: 20
MDLabel:
id: print_date
text: "Nothing to display"
pos_hint: {"center_x" : 0, "y" : .6}
size_hint: .4, None
text_size: self.width, None
height: self.texture_size[1]
halign: "left"
MDTextField:
id: show_date
mode: "rectangle"
pos_hint: {"x" : .5, "y" : .7}
MDIconButton:
icon: "calendar"
pos_hint: {"center_x": .7, "center_y": .9}
size_hint: None, None
on_release: app.show_date_picker_1()
MDRaisedButton:
text: "Check payments"
pos_hint: {"y" : .2}
size_hint: 1, 0.1
on_release:
app.view_payment()
MDRaisedButton:
text: "Total"
pos_hint: {"y" : .1}
size_hint: 1, 0.1
on_release:
app.total()
MDRaisedButton:
text: "Go back"
pos_hint: {"y" : 0}
size_hint: 1, 0.1
on_release:
root.current = "main"
'''
payments = {}
file = "work.json"
class Test(MDApp):
def build(self):
self.theme_cls.theme_style = "Dark"
self.theme_cls.primary_palette = "Orange"
return Builder.load_string(KV)
def on_save(self, instance, value, date_range):
'''sets the date in Add payment'''
self.root.ids.date.text = str(value.strftime("%Y/%m/%d"))
print(value)
def on_save_1(self, instance, value, date_range):
'''sets the date in view payment'''
self.root.ids.show_date.text = str(value.strftime("%Y/%m/%d"))
def on_cancel(self, instance, value):
'''Events called when the "CANCEL" dialog box button is clicked.'''
def show_date_picker(self):
'''calls the date picker in add payment window'''
date_dialog = MDDatePicker()
date_dialog.bind(on_save=self.on_save, on_cancel=self.on_cancel)
date_dialog.open()
def show_date_picker_1(self):
'''calls the date picker in view window'''
date_dialog = MDDatePicker()
date_dialog.bind(on_save=self.on_save_1, on_cancel=self.on_cancel)
date_dialog.open()
def on_checkbox_active(self, checkbox, value):
if value:
payment_amount = float(self.root.ids.amount.text) * 1.5
else:
payment_amount = float(self.root.ids.amount.text) / 1.5
self.root.ids.amount.text = str(payment_amount)
##########################################
def add_payment(self):
"""creates dictionary entry and saves it."""
# sets date as user input in date field
date = self.root.ids.date.text
# sets case_id as user input in case_id field
case_id = self.root.ids.case_id.text
# sets amount as user input in amount field
amount = self.root.ids.amount.text
# sets payment_type as user input in payment_type field
payment_type = self.root.ids.payment_type.text
try:
self._extracted_from_add_payment_11(date, case_id, payment_type, amount)
except ValueError as Error:
self._extracted_from_add_payment_11(date, case_id, payment_type, amount)
# TODO Rename this here and in `add_payment`
def _extracted_from_add_payment_11(self, date, case_id, payment_type, amount):
# checks if json file exists if it doesnt creates it if it does it dumps payments in it
try:
with open(file, 'x') as f:
payments = {}
j = json.dump(payments, f)
except FileExistsError:
with open(file, 'r') as f:
payments = json.load(f)
#creates entry in dictionary if date exists appends it if not creates an entry
if date not in payments:
payments[date] = []
payments[date].append(
{
"Case id" : case_id,
"Payment type" : payment_type,
"Amount" : amount
})
#resets the input fields to empty
self.root.ids.case_id.text = ''
self.root.ids.amount.text = ''
self.root.ids.payment_type.text = ''
#dumps data in json
with open(file, 'w') as f:
j = json.dump(payments, f)
def view_payment(self):
"""finds entry in dictionary and puts all matches to a label"""
#sets date as input from date field
date = self.root.ids.show_date.text
#sets print_date label to empty
self.root.ids.print_date.text = ""
#loads data from json
with open(file, 'r') as f:
payments = json.load(f)
#if it finds entry puts it in a label if not sets label text as date does not exist
try:
for b, i in enumerate(payments.get(date, None), start=0):
self.root.ids.print_date.text += f"{b+1}. Case id:{payments[date][b].get('Case id')}, Payment type:{payments[date][b].get('Payment type')}, Amount:{payments[date][b].get('Amount')}.\n"
except (KeyError, TypeError) as error: # handle file not found on first launch
date = self.root.ids.show_date.text
self.root.ids.print_date.text = "No payments or wrong date"
def total(self):
"""finds entrys in specific date and sums them up"""
#sets date as input from show_date field
date = self.root.ids.show_date.text
#resets print_date label to empty
self.root.ids.print_date.text = ''
total1 = 0
# finds required dates amount entrys and sums them
try:
with open(file, 'r') as f:
payments = json.load(f)
for i in payments[date]:
# if there is no value it skips it and look for other entry
if amount := i.get('Amount'):
total1 += float(amount)
self.root.ids.print_date.text += str(total1)
except (KeyError,ValueError) as Error:
self.root.ids.print_date.text = 'Date does not exist'
Test().run()
the only thing i noticed it says that MDScrollView import is not being accessed.
any help would be greatly appreciated
I have created the above ternary plot using the code below:
import plotly.figure_factory as ff
fig = ff.create_ternary_contour(np.stack((prob0,prob1,prob2)),some_calc_val,
pole_labels=[r'$\text{AxesA}$', r'$\text{AxesB}$', r'$\text{AxesC}$'],
interp_mode='cartesian',
ncontours=50,
colorscale='Jet',
showscale=True,
title=r'$\text{Plot}$')
fig.update_ternaries(
aaxis = dict(
tickmode = 'array',
ticklen = 10,
tickvals = [0.2, 0.4, 0.6, 0.8],
ticktext = [r'$0.2$', r'$0.4$', r'$0.6$', r'$0.8$']
),
baxis = dict(
tickmode = 'array',
ticklen = 10,
tickvals = [0.2, 0.4, 0.6, 0.8],
ticktext = [r'$0.2$', r'$0.4$', r'$0.6$', r'$0.8$']
),
caxis = dict(
tickmode = 'array',
ticklen = 10,
tickvals = [0.2, 0.4, 0.6, 0.8],
ticktext = [r'$0.2$', r'$0.4$', r'$0.6$', r'$0.8$']
)
)
fig.update_layout(width=600, height=600)
fig.show()
Data for refrence
prob0=[9.99960940e-01 6.03061907e-04 9.10372544e-12 9.99952169e-01
2.81419593e-04 2.17084140e-18 9.99882767e-01 5.63535132e-11
1.86320179e-25]
prob1=[3.90598546e-05 9.99396859e-01 6.40065936e-01 4.78313969e-05
5.71105924e-01 1.86904565e-07 5.85691843e-05 1.40045638e-07
1.96443635e-14]
prob2=[4.32181700e-19 7.88323607e-08 3.59934064e-01 5.03536073e-12
4.28612656e-01 9.99999813e-01 5.86636024e-05 9.99999860e-01
1.00000000e+00]
some_calc_val=[3.90598546e-05 6.03140740e-04 3.59934064e-01 4.78314019e-05
4.28894076e-01 1.86904565e-07 1.17232787e-04 1.40101991e-07
1.95399252e-14]
Questions:
I would like to Latexify the ticks for the color bar on the right, I have looked around in the layout but did not find any such color bar which I could update the ticks for
Is it possible to add a little space between the ternary plot and the color bar, the name of the AxesC falls right under the color bar which is not ideal for my use case.
Also is there a way to add labels similar to what is used in go.Countour() which has a showlabels key
Let me know if separate questions need to be posted for each of the above.
References before posting:
https://community.plotly.com/t/how-to-get-the-axis-ticks-of-a-scatter-plot-to-be-shown-in-latex-using-python-python-latex-representation/61302
https://community.plotly.com/t/format-ticks-add-km-at-the-end/60932
I want to adjust the width of columns in Dash table (created from Pandas Dataframe). There are 3 columns in table :
Path
Scenario
Step
I want to set the column width of first column (Path) to 10% and the second column (Scenario) to 40% and the last column (Step) to 50%.
I am running below code, but the column width changes are not working as expected. "Path" column is taking more than 50% of width and "Steps" column around 20%.
Dataframe name is dfSteps
columns=[{"name": i, "id": i} for i in dfSteps.columns],
data=dfSteps.to_dict('records'),
style_header={
'backgroundColor': 'rgb(230, 230, 230)',
'fontWeight': 'bold'
},
style_table={
'maxWidth': '2000px',
'overflowX': 'scroll',
'border': 'thin lightgrey solid'
},
style_cell={
'font_family': 'cursive',
'font_size': '16px',
'border': '1px solid grey',
'minWidth': '1px', 'width': 'fixed', 'maxWidth': '1000px',
'textAlign': 'left', 'whiteSpace': 'normal'
},
style_cell_conditional=[
{'if': {'column_id': 'Path'},
'width': '10%'},
{'if': {'column_id': 'Scenario'},
'width': '40%'},
{'if': {'column_id': 'Path'},
'width': '50%'},
],
),
Just redefine your table as they suggest in the documentation
https://plotly.com/python/table/
fig = go.Figure(data=[go.Table(
columnorder = [1,2],
columnwidth = [80,400],
header = dict(
values = [['<b>EXPENSES</b><br>as of July 2017'],
['<b>DESCRIPTION</b>']],
line_color='darkslategray',
fill_color='royalblue',
align=['left','center'],
font=dict(color='white', size=12),
height=40
),
cells=dict(
values=values,
line_color='darkslategray',
fill=dict(color=['paleturquoise', 'white']),
align=['left', 'center'],
font_size=12,
height=30)
)
])
fig.show()
Qt 5.9.2
The following QML code:
ApplicationWindow
{
visible: true
width: 585
height: 113
title: qsTr("test")
Rectangle
{
width: 585
height: 113
color: "black"
x: 0
y: 0
}
Image
{
source: "balloon.png"
x: 0
y: 0
}
}
produces the expected result:
When I add scale: 0.5 to Image element, I get this:
But I expected it to look like this:
Can somebody please explain me why 0.5 scaled image is not located at (0,0) coordinates as it explicitly set in its properties and can something be done here for the scaled image to be located at (0,0) coordinates?
As mentioned in the documentation for scale, scaling is applied from the transformOrigin, and the default origin is Item.Center, so you need to specify Item.TopLeft:
import QtQuick 2.7
import QtQuick.Controls 2.0
ApplicationWindow {
visible: true
width: 585
height: 113
title: qsTr("test")
Rectangle {
width: 585
height: 113
color: "black"
x: 0
y: 0
}
Image {
source: "balloon.png"
x: 0
y: 0
scale: 0.5
transformOrigin: Item.TopLeft
}
}
The x and y properties only affect an item's position, not its scaling origins. Note that there's also the transform property if you need to do more advanced transformations.
Using the commits from breznak for the encoders (I wasn't able to figure out "git checkout ..." with GitHub, so I just carefully copied over the three files - base.py, multi.py, and multi_test.py).
I ran multi_test.py without any problems.
Then I adjusted my model parameters (MODEL_PARAMS), so that the encoders portion of 'sensorParams' looks like this:
'encoders': {
'frequency': {
'fieldname': u'frequency',
'type': 'SimpleVector',
'length': 5,
'minVal': 0,
'maxVal': 210
}
},
I also adjusted the modelInput portion of my code, so it looked like this:
model = ModelFactory.create(model_params.MODEL_PARAMS)
model.enableInference({'predictedField': 'frequency'})
y = [1,2,3,4,5]
modelInput = {"frequency": y}
result = model.run(modelInput)
But I get the final error, regardless if I instantiate 'y' as a list or a numpy.ndarray
File "nta/eng/lib/python2.7/site-packages/nupic/encoders/base.py", line 183, in _getInputValue
return getattr(obj, fieldname)
AttributeError: 'list' object has no attribute 'idx0'
I also tried initializing a SimpleVector encoder inline with my modelInput, directly encoding my array, then passing it through modelInput. That violated the input parameters of my SimpleVector, because I was now double encoding. So I removed the encoders portion of my model parameters dictionary. That caused a spit up, because some part of my model was looking for that portion of the dictionary.
Any suggestions on what I should do next?
Edit: Here're the files I'm using with the OPF.
sendAnArray.py
import numpy
from nupic.frameworks.opf.modelfactory import ModelFactory
import model_params
class sendAnArray():
def __init__(self):
self.model = ModelFactory.create(model_params.MODEL_PARAMS)
self.model.enableInference({'predictedField': 'frequency'})
for i in range(100):
self.run()
def run(self):
y = [1,2,3,4,5]
modelInput = {"frequency": y}
result = self.model.run(modelInput)
anomalyScore = result.inferences['anomalyScore']
print y, anomalyScore
sAA = sendAnArray()
model_params.py
MODEL_PARAMS = {
'model': "CLA",
'version': 1,
'predictAheadTime': None,
'modelParams': {
'inferenceType': 'TemporalAnomaly',
'sensorParams': {
'verbosity' : 0,
'encoders': {
'frequency': {
'fieldname': u'frequency',
'type': 'SimpleVector',
'length': 5,
'minVal': 0,
'maxVal': 210
}
},
'sensorAutoReset' : None,
},
'spEnable': True,
'spParams': {
'spVerbosity' : 0,
'globalInhibition': 1,
'columnCount': 2048,
'inputWidth': 5,
'numActivePerInhArea': 60,
'seed': 1956,
'coincInputPoolPct': 0.5,
'synPermConnected': 0.1,
'synPermActiveInc': 0.1,
'synPermInactiveDec': 0.01,
},
'tpEnable' : True,
'tpParams': {
'verbosity': 0,
'columnCount': 2048,
'cellsPerColumn': 32,
'inputWidth': 2048,
'seed': 1960,
'temporalImp': 'cpp',
'newSynapseCount': 20,
'maxSynapsesPerSegment': 32,
'maxSegmentsPerCell': 128,
'initialPerm': 0.21,
'permanenceInc': 0.1,
'permanenceDec' : 0.1,
'globalDecay': 0.0,
'maxAge': 0,
'minThreshold': 12,
'activationThreshold': 16,
'outputType': 'normal',
'pamLength': 1,
},
'clParams': {
'regionName' : 'CLAClassifierRegion',
'clVerbosity' : 0,
'alpha': 0.0001,
'steps': '5',
},
'anomalyParams': {
u'anomalyCacheRecords': None,
u'autoDetectThreshold': None,
u'autoDetectWaitRecords': 2184
},
'trainSPNetOnlyIfRequested': False,
},
}
The problem seems to be that the SimpleVector class is accepting an array instead of a dict as its input, and then reconstructs that internally as {'list': {'idx0': 1, 'idx1': 2, ...}} (ie as if this dict had been the input). This is fine if it is done consistently, but your error shows that it's broken down somewhere. Have a word with #breznak about this.
Working through the OPF was difficult. I wanted to input an array of indices into the temporal pooler, so I opted to interface directly with the algorithms (I relied heavy on hello_tp.py). I ignored SimpleVector all together, and instead worked through the BitmapArray encoder.
Subutai has a useful email on the nupic-discuss listserve, where he breaks down the three main areas of the NuPIC API: algorithms, networks/regions, & the OPF. That helped me understand my options better.