ArrayIndexOutOfBoundsException in LazyColumnFor (androidx.compose.foundation:foundation:1.0.0-alpha07) - android-jetpack-compose

After upgrading jetpack compose to 1.0.0-alpha07, the LazyColumnFor got array out of bound problem even in simple setup. Anyone could help ?
import androidx.compose.foundation.background
import androidx.compose.foundation.lazy.LazyColumnFor
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.ui.tooling.preview.Preview
#Preview(name = "Preview Testing")
#Composable
fun Testing() {
LazyColumnFor(
items = listOf("1", "2"),
modifier = Modifier.background(Color.White)
) { item ->
Text(text = "Item:" + item)
}
}
Error Message during Android Studio Preview rendering
java.lang.ArrayIndexOutOfBoundsException: Index 162 out of bounds for length 160
at androidx.compose.runtime.SlotTableKt.parentAnchor(SlotTable.kt:2468)
at androidx.compose.runtime.SlotTableKt.access$parentAnchor(SlotTable.kt)
at androidx.compose.runtime.SlotReader.reposition(SlotTable.kt:776)
at androidx.ui.tooling.SlotTreeKt.getGroup(SlotTree.kt:453)
at androidx.ui.tooling.SlotTreeKt.getGroup(SlotTree.kt:457)
at androidx.ui.tooling.SlotTreeKt.getGroup(SlotTree.kt:457)
at androidx.ui.tooling.SlotTreeKt.getGroup(SlotTree.kt:457)
at androidx.ui.tooling.SlotTreeKt.getGroup(SlotTree.kt:457)
at androidx.ui.tooling.SlotTreeKt.getGroup(SlotTree.kt:457)
at androidx.ui.tooling.SlotTreeKt.getGroup(SlotTree.kt:457)
at androidx.ui.tooling.SlotTreeKt.getGroup(SlotTree.kt:457)
at androidx.ui.tooling.SlotTreeKt.getGroup(SlotTree.kt:457)
at androidx.ui.tooling.SlotTreeKt.getGroup(SlotTree.kt:457)
at androidx.ui.tooling.SlotTreeKt.getGroup(SlotTree.kt:457)
at androidx.ui.tooling.SlotTreeKt.getGroup(SlotTree.kt:457)
at androidx.ui.tooling.SlotTreeKt.asTree(SlotTree.kt:520)
at androidx.ui.tooling.preview.ComposeViewAdapter.onLayout_Original(ComposeViewAdapter.kt:224)
at androidx.ui.tooling.preview.ComposeViewAdapter.onLayout(ComposeViewAdapter.kt)
at android.view.View.layout_Original(View.java:22844)
at android.view.View_Delegate.layout(View_Delegate.java:91)
at android.view.View.layout(View.java:22830)
at android.view.ViewGroup.layout(ViewGroup.java:6389)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:332)
at android.widget.FrameLayout.onLayout(FrameLayout.java:270)
at android.view.View.layout_Original(View.java:22844)
at android.view.View_Delegate.layout(View_Delegate.java:91)
at android.view.View.layout(View.java:22830)
at android.view.ViewGroup.layout(ViewGroup.java:6389)
at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1103)
at android.view.View.layout_Original(View.java:22844)
at android.view.View_Delegate.layout(View_Delegate.java:91)
at android.view.View.layout(View.java:22830)
at android.view.ViewGroup.layout(ViewGroup.java:6389)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:332)
at android.widget.FrameLayout.onLayout(FrameLayout.java:270)
at android.view.View.layout_Original(View.java:22844)
at android.view.View_Delegate.layout(View_Delegate.java:91)
at android.view.View.layout(View.java:22830)
at android.view.ViewGroup.layout(ViewGroup.java:6389)
at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:366)
at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:435)
at com.android.tools.idea.layoutlib.LayoutLibrary.createSession(LayoutLibrary.java:141)
at com.android.tools.idea.rendering.RenderTask.createRenderSession(RenderTask.java:710)
at com.android.tools.idea.rendering.RenderTask.lambda$inflate$6(RenderTask.java:865)
at com.android.tools.idea.rendering.RenderExecutor$runAsyncActionWithTimeout$2.run(RenderExecutor.kt:174)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
Here is the screenshot of Android Studio Preview

It seems to be an issue the the Preview, try updating it to alpha08 and also check if when running on a device it works.
If it's not fixed in alpha08, open an issue for it here: https://issuetracker.google.com/issues/new?component=612128&template=1253476.

Related

Recording multiple meshcat visualizers

I would like to record multiple meshcat visualizers with different prefix ids so I can eventually save them to an HTML file that I can interact with later. I would like the different visualizations to play on top of each other and to be able to select/unselect different visualizations.
Here is a minimal replication of the problem. I expect there to be two cartpole visualizations that are on top of each other. However, I only end up seeing one of them being recorded. The other cartpole seems stuck at the end position when I play back the recording
import meshcat
from pydrake.common import FindResourceOrThrow
​
from pydrake.multibody.plant import (
AddMultibodyPlantSceneGraph)
from pydrake.multibody.parsing import Parser
from pydrake.systems.analysis import Simulator
from pydrake.systems.framework import DiagramBuilder
from pydrake.systems.meshcat_visualizer import (
ConnectMeshcatVisualizer,
)
​
v = meshcat.Visualizer()
file_name = FindResourceOrThrow(
"drake/examples/multibody/cart_pole/cart_pole.sdf")
builder = DiagramBuilder()
cart_pole, scene_graph = AddMultibodyPlantSceneGraph(builder, 0.0)
Parser(plant=cart_pole).AddModelFromFile(file_name)
cart_pole.Finalize()
​
vis = ConnectMeshcatVisualizer(builder=builder,
prefix="vis",
scene_graph=scene_graph,
open_browser=False)
​
vis2 = ConnectMeshcatVisualizer(
builder=builder,
prefix="vis2",
scene_graph=scene_graph,
open_browser=False)
vis2.set_name("vis2")
​
diagram = builder.Build()
diagram_context = diagram.CreateDefaultContext()
​
cart_pole_context = diagram.GetMutableSubsystemContext(
cart_pole, diagram_context)
cart_pole.get_actuation_input_port().FixValue(cart_pole_context, .02)
​
simulator = Simulator(diagram, diagram_context)
simulator.set_publish_every_time_step(False)
vis.start_recording()
vis2.start_recording()
simulator.AdvanceTo(100)
vis.stop_recording()
vis2.stop_recording()
​
vis.publish_recording()
vis2.publish_recording()
​
# f = open("saved.html", "w")
# f.write(v.static_html())
# f.close()
Here is one solution. I don't love it, but it accomplishes the stated goal. Note the changes:
saving and publishing only one animation
naming the model in the MultibodyPlant with a distinct name for each sim
setting delete_prefix_on_load=False so it doesn't clear the old geometry
import meshcat
from pydrake.common import FindResourceOrThrow
from pydrake.multibody.plant import (AddMultibodyPlantSceneGraph)
from pydrake.multibody.parsing import Parser
from pydrake.systems.analysis import Simulator
from pydrake.systems.framework import DiagramBuilder
from pydrake.systems.meshcat_visualizer import (
ConnectMeshcatVisualizer,
)
animation = None
for i in range(3):
file_name = FindResourceOrThrow(
"drake/examples/multibody/cart_pole/cart_pole.sdf")
builder = DiagramBuilder()
cart_pole, scene_graph = AddMultibodyPlantSceneGraph(builder, 0.0)
Parser(plant=cart_pole).AddModelFromFile(file_name, f"plant{i}")
cart_pole.Finalize()
vis = ConnectMeshcatVisualizer(builder=builder,
scene_graph=scene_graph,
delete_prefix_on_load=False,
open_browser=False)
if animation:
vis._animation = animation
diagram = builder.Build()
diagram_context = diagram.CreateDefaultContext()
cart_pole_context = diagram.GetMutableSubsystemContext(
cart_pole, diagram_context)
cart_pole.get_actuation_input_port().FixValue(cart_pole_context, .02)
simulator = Simulator(diagram, diagram_context)
simulator.set_publish_every_time_step(False)
vis.start_recording()
simulator.AdvanceTo(10)
vis.stop_recording()
animation = vis._animation
vis.publish_recording()

NameError: name 'FileCheckpointManager' is not defined while saving model

after simulating this code of federated learning for image classification, I would like to save my model so I add this two lines
ckpt_manager = FileCheckpointManager("model.h5")
ckpt_manager.save_checkpoint(ServerState.from_anon_tuple(state), round_num=2)
So here is all my code:
import collections
import time
import tensorflow as tf
tf.compat.v1.enable_v2_behavior()
import tensorflow_federated as tff
source, _ = tff.simulation.datasets.emnist.load_data()
def map_fn(example):
return collections.OrderedDict(
x=tf.reshape(example['pixels'], [-1, 784]), y=example['label'])
def client_data(n):
ds = source.create_tf_dataset_for_client(source.client_ids[n])
return ds.repeat(10).shuffle(500).batch(20).map(map_fn)
train_data = [client_data(n) for n in range(10)]
element_spec = train_data[0].element_spec
def model_fn():
model = tf.keras.models.Sequential([
tf.keras.layers.Input(shape=(784,)),
tf.keras.layers.Dense(units=10, kernel_initializer='zeros'),
tf.keras.layers.Softmax(),
])
return tff.learning.from_keras_model(
model,
input_spec=element_spec,
loss=tf.keras.losses.SparseCategoricalCrossentropy(),
metrics=[tf.keras.metrics.SparseCategoricalAccuracy()])
trainer = tff.learning.build_federated_averaging_process(
model_fn, client_optimizer_fn=lambda: tf.keras.optimizers.SGD(0.02))
....
NUM_ROUNDS = 11
for round_num in range(2, NUM_ROUNDS):
state, metrics = trainer.next(state, federated_train_data)
print('round {:2d}, metrics={}'.format(round_num, metrics))
ckpt_manager = FileCheckpointManager("model.h5")
ckpt_manager.save_checkpoint(ServerState.from_anon_tuple(state), round_num=9)
But this error does appear:
NameError: name 'FileCheckpointManager' is not defined
I will appreciate it if you told me how I solve this problem
Looks like the code is missing an import for the module with the checkpoint manager.
FileCheckpointManger is defined in the checkpoint_manager module here: tensorflow_federated/python/research/utils/checkpoint_manager.py.
Try adding an import at the top of the file like this (the following example assumes the tensorflow federated github repo is in the import search path):
from tensorflow_federated.python.research.utils import checkpoint_manager
# ...
ckpt_manager = checkpoint_manager.FileCheckpointManager("model.h5")

Jodatime LenientChronology parser double counting

The following Scala code returns 121,000ms instead of the expected 61,000ms. This applies to other fields (e.g. hour of day) as well, and seems to be caused by double-counting the out-of-range value twice. The documentation and tests for LenientChronology don't seem to throw any light on this behaviour, so was wondering if anyone know of or could provide an explaination for this behaviour.
import org.joda.time.chrono.{ISOChronology, LenientChronology}
import org.joda.time.format.DateTimeFormatterBuilder
val secondNumber = "61"
val lenientChronology = LenientChronology.getInstance(ISOChronology.getInstanceUTC)
val lenientParser = new DateTimeFormatterBuilder()
.appendSecondOfMinute(1).toFormatter.withChronology(lenientChronology)
lenientParser.parseMillis(secondNumber)
We can also use PeriodFormatterBuilder instead:
import org.joda.time.format.PeriodFormatterBuilder
val hoursMinutes =
new PeriodFormatterBuilder().appendHours().appendLiteral(":").appendMinutes().appendLiteral(":").appendSeconds().toFormatter
val duration = hoursMinutes.parsePeriod("40:50:23").toStandardDuration
duration.getMillis
It handles LenientChronology on the fly

How to define a non lambda args_converter function?

In the docs it's shown that an args_converter can be written as a regular function or as a lambda function, but i can't seem to get it to work with a non lambda one, and all examples i see are lambdas.
Here's a piece of my code:
def groupArgsConv(index, item):
res = {'text': item['title'],
'size_hint_y': None,
'heigth': '25dp'}
return res
self.ids.grouplist.adapter = ListAdapter(args_converter=groupArgsConv,
data=self.groups,
cls=ListItemLabel)
This doesn't work, but this does:
list_item_args_converter = lambda index, item: {'text': item['title'],
'size_hint_y': None,
'height': '25dp'}
self.ids.grouplist.adapter = ListAdapter(args_converter=list_item_args_converter,
data=self.groups,
cls=ListItemLabel)
Why? How do i get the 1st example to work?
This code works for me:
from kivy.adapters.listadapter import ListAdapter
from kivy.uix.listview import ListItemLabel, ListView
from kivy.base import runTouchApp
data = [{'title': str(i)} for i in range(100)]
def groupArgsConv(index, item):
res = {'text': item['title'],
'size_hint_y': None,
'height': '25dp'}
return res
list_adapter = ListAdapter(
data=data,
args_converter=groupArgsConv,
cls=ListItemLabel)
if __name__ == '__main__':
runTouchApp(ListView(adapter=list_adapter))
What do you mean by "doesn't work"? Do you have some kind of an exception or strange output in the log?

Code does nothing when i run it (ROS, opencv)

So here's my problem. I'm using ROS and opencv, trying to create a depth map using two cameras. However, the code that i wrote, does not seem to do anything and im a little confused about why. (previous codes that i've been running had the same structure)
#!/usr/bin/env python
from __future__ import print_function
import roslib
roslib.load_manifest('test_cam')
import sys
import rospy
import cv2
from std_msgs.msg import String
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
import message_filters
class image_converter:
def __init__(self):
self.bridge = CvBridge()
self.image_sub_1 = message_filters.Subscriber("/cameras/left_hand_camera/image",Image)
self.image_sub_2 = message_filters.Subscriber("/cameras/head_camera/image",Image)
self.ts = message_filters.TimeSynchronizer([self.image_sub_1, self.image_sub_2], 10)
self.ts.registerCallback(self.callback)
def callback(self,Image):
try:
cv_image_1 = self.bridge.imgmsg_to_cv2(Image, "bgr8")
cv_image_2 = self.bridge.imgmsg_to_cv2(Image, "bgr8")
except CvBridgeError as e:
print(e)
stereo = cv2.StereoBM_create(numDisparities=16, blockSize=15)
disparity = stereo.compute(cv_image_1,cv_image_2)
plt.imshow(disparity,'gray')
plt.show()
plt.waitKey(1)
def main(args):
ic = image_converter()
rospy.init_node('image_converter', anonymous=True)
try:
rospy.spin()
except KeyboardInterrupt:
print("Shutting down")
cv2.destroyAllWindows()
if __name__ == '__main__':
main(sys.argv)
You must execute rospy.init before subscribing to any topic.

Resources