Frame not appearing when it is supposed to... (ROBLOX GUI) - user-interface

I am making an Os module that lets you create remote Operating systems but when the background frame loads in a new window just an random window loads in but it just basically gets "overwritten" by the background frame.
I have a post on scriptinghelpers: https://scriptinghelpers.org/questions/116285/instancenew-but-not-working-as-expected-module
but it seems that no one wants no one on the website knows how to do it
my code for the main Os module:
local module = {}
function module.__Version__()
local ROS = '1.00'
local ROS = tostring(ROS)
print('Version: '..ROS)
end
function module.create_environment(master)
local main = Instance.new('ScreenGui',master)
main.Name = ("ROS")
return(main)
end
function module.create_background(env)
local Frame = Instance.new('Frame',env)
Frame.Name = ('Background')
Frame.Size = UDim2.new(2,0,2,0)
Frame.Position = UDim2.new(0, 0,-0.5, 0)
Frame.BackgroundColor3 = Color3.new(0.337255, 0.290196, 1)
return(Frame)
end
function module.create_taskbar(env)
local main = Instance.new("Frame",env)
main.BackgroundColor3 = Color3.new(0, 0, 0)
main.Size = UDim2.new(2, 0,0, 45)
main.Position = UDim2.new(-0.5, 0,1, -45)
return(main)
end
function module.create_app_button(icon,env,X,Y)
local Btn = Instance.new('ImageButton',env)
Btn.Image = (tostring(icon))
Btn.Size = UDim2.new(0, 49,0, 49)
Btn.Position = UDim2.new(0, tonumber(X), 0, tonumber(Y))
return(Btn)
end
function module.create_clone_env(env)
local coloned_env = env:Clone()
coloned_env.Parent = env.Parent
end
function module.create_time_gui(env)
local main = Instance.new('TextLabel',env)
main.Size = UDim2.new(0, 115,0, 41)
main.Position = UDim2.new(1, -145,1, -44)
main.TextColor3 = Color3.new(1, 1, 1)
main.BackgroundTransparency = 1
main.TextScaled = true
main.Font = Enum.Font.Ubuntu
local assetId = 5990705305
local InsertService = game:GetService("InsertService")
local model = InsertService:LoadAsset(assetId)
model.Time_Manager.Parent = main
return(main)
end
function module.create_start_button(env)
local main_button = Instance.new('TextButton',env)
main_button.Size = UDim2.new(0, 146,0, 45)
main_button.Position = UDim2.new(0, 0,1, -44)
main_button.TextColor3 = Color3.new(0, 0, 0)
main_button.Text = "Start"
main_button.TextSize = 25
main_button.Font = Enum.Font.Arial
main_button.BorderSizePixel = 0
return(main_button)
end
function module.create_app(env)
local frame = Instance.new('Frame',env)
local round = Instance.new("UICorner",frame)
local top_frame = Instance.new('Frame',frame)
local exit_button = Instance.new('TextButton',top_frame)
local assetId = 5995055509
local InsertService = game:GetService("InsertService")
local model = InsertService:LoadAsset(assetId)
round.CornerRadius = UDim.new(0,20)
frame.Size = UDim2.new(0, 1084,0, 673)
frame.Position = UDim2.new(0.5, -542,0.5, -336)
frame.BackgroundColor3 = Color3.new(1, 1, 1)
top_frame.Size = UDim2.new(1, 0,0.003, 28)
top_frame.Position = UDim2.new(0, 0,0, 0)
top_frame.BackgroundColor3 = Color3.new(0.611765, 0.611765, 0.611765)
top_frame.BorderSizePixel = 0
exit_button.Size = UDim2.new(0, 74,0, 30)
exit_button.Position = UDim2.new(1, -74,0.5, -15)
exit_button.Text = ("X")
exit_button.BorderSizePixel = 0
exit_button.TextColor3 = Color3.new(1, 1, 1)
exit_button.BackgroundColor3 = Color3.new(1, 0, 0)
exit_button.TextStrokeTransparency = 0
exit_button.TextSize = 17
model.LocalScript.Parent = exit_button
model:Destroy()
return(frame)
end
return module
Everything works; create_taskbar(),create_time_gui(),create_start_button()
But its just the create_app()
This is what my Os-module made:
This is the OS my Os-module made:
As i said the background overwrites my create_app() is there a way to prevent this?

If maintaining the element hierarchy is important, try adjusting the ZIndex of the background frame and the app so that the two aren't fighting for which one appears on top. Elements with smaller numbers for their ZIndex will render first, meaning they will appear behind elements with larger ones.
function module.create_background(env)
local Frame = Instance.new('Frame',env)
Frame.ZIndex = 1
-- <a bunch of other code>
return Frame
end
And then make the app's ZIndex higher.
function module.create_app(env)
local frame = Instance.new('Frame', env)
frame.ZIndex = 2
-- <a bunch of other code>
return frame
end
But you should be careful. Messing with ZIndices can get really messy really quick. A better alternative would be to just set the app Frame's parent to the background Frame.

Related

TensorFlow training gets slower every batch

I am new to TensorFlow and I get my code running successfully by modifying tutorials from the official website.
I checked some other answers on StackOverflow, which says my problem is likely due to something is being added to the graph every time. However, I have no idea where to look for the code that might have caused this.
Also, I used tf.py_function to map the dataset because I really need to enable eagerly mode in the mapping.
def get_dataset(data_index):
# data_index is a Pandas Dataframe that contains image/label pair info, each row is one pair
data_index = prepare_data_index(data_index)
# shuffle dataframe here because dataset.shuffle is taking very long time.
data_index = data_index.sample(data_index.shape[0])
path = path_to_img_dir
# list of dataframe indices indicating rows that are going to be included in the dataset for training.
indices_ls = ['{}_L'.format(x) for x in list(data_index.index)] + ['{}_R'.format(x) for x in list(data_index.index)]
# around 310k images
image_count = len(indices_ls)
list_ds = tf.data.Dataset.from_tensor_slices(indices_ls)
# dataset.shuffle is commented out because it takes too much time
# list_ds = list_ds.shuffle(image_count, reshuffle_each_iteration=False)
val_size = int(image_count * 0.2)
train_ds = list_ds.skip(val_size)
val_ds = list_ds.take(val_size)
def get_label(index):
index = str(np.array(index).astype(str))
delim = index.split('_')
state = delim[1]
index = int(delim[0])
if state == 'R':
label = data_index.loc[index][right_labels].to_numpy().flatten()
elif state == 'L':
label = data_index.loc[index][left_labels].to_numpy().flatten()
return tf.convert_to_tensor(label , dtype=tf.float16)
def get_img(index):
index = str(np.array(index).astype(str))
delim = index.split('_')
state = delim[1]
index = int(delim[0])
file_path = '{}_{}.jpg'.format(data_index.loc[index, 'sub_folder'],
str(int(data_index.loc[index, 'img_index'])).zfill(4)
)
img = tf.io.read_file(os.path.join(path, file_path))
img = tf.image.decode_jpeg(img, channels=3)
full_width = 320
img = tf.image.resize(img, [height, full_width])
# Crop half of the image depending on the state
if state == 'R':
img = tf.image.crop_to_bounding_box(img, offset_height=0, offset_width=0, target_height=height,
target_width=int(full_width / 2))
img = tf.image.flip_left_right(img)
elif state == 'L':
img = tf.image.crop_to_bounding_box(img, offset_height=0, offset_width=int(full_width / 2), target_height=height,
target_width=int(full_width / 2))
img = tf.image.resize(img, [height, width])
img = tf.keras.preprocessing.image.array_to_img(
img.numpy(), data_format=None, scale=True, dtype=None
)
# Apply auto white balancing, output an np array
img = AWB(img)
img = tf.convert_to_tensor(img, dtype=tf.float16)
return img
def process_path(index):
label = get_label(index)
img = get_img(index)
return img, label
AUTOTUNE = tf.data.experimental.AUTOTUNE
train_ds = train_ds.map(lambda x: tf.py_function(
process_path,
[x], (tf.float16, tf.float16)), num_parallel_calls=AUTOTUNE)
val_ds = val_ds.map(lambda x: tf.py_function(
process_path,
[x], (tf.float16, tf.float16)), num_parallel_calls=AUTOTUNE)
def configure_for_performance(ds):
ds = ds.cache()
# ds = ds.shuffle(buffer_size=image_count)
ds = ds.batch(batch_size)
ds = ds.prefetch(buffer_size=AUTOTUNE)
return ds
train_ds = configure_for_performance(train_ds)
val_ds = configure_for_performance(val_ds)
return train_ds, val_ds
Can anyone please help me? Thanks!
Here is the rest of my code.
def initialize_model():
IMG_SIZE = (height, width)
preprocess_input = tf.keras.applications.vgg19.preprocess_input
IMG_SHAPE = IMG_SIZE + (3,)
base_model = tf.keras.applications.VGG19(input_shape=IMG_SHAPE,
include_top=False,
weights='imagenet')
global_average_layer = tf.keras.layers.GlobalAveragePooling2D()
prediction_layer = tf.keras.layers.Dense(class_num, activation=tf.nn.sigmoid, use_bias=True)
inputs = tf.keras.Input(shape=(height, width, 3))
x = preprocess_input(inputs)
x = base_model(x, training=True)
x = global_average_layer(x)
outputs = prediction_layer(x)
model = tf.keras.Model(inputs, outputs)
def custom_loss(y_gt, y_pred):
L1_loss_out = tf.math.abs(tf.math.subtract(y_gt, y_pred))
scaler = tf.pow(50.0, y_gt)
scaled_loss = tf.math.multiply(L1_loss_out, scaler)
scaled_loss = tf.math.reduce_mean(
scaled_loss, axis=None, keepdims=False, name=None
)
return scaled_loss
base_learning_rate = 0.001
model.compile(optimizer=tf.keras.optimizers.SGD(learning_rate=base_learning_rate, momentum=0.9),
loss=custom_loss,
metrics=['mean_absolute_error']
)
return model
def train(data_index, epoch_num, save_path):
train_dataset, validation_dataset = get_dataset(data_index)
model = initialize_model()
model.summary()
history = model.fit(train_dataset,
epochs=epoch_num,
validation_data=validation_dataset)
model.save_weights(save_path)
return model, history

Hands up animation when stand on a brick [ROBLOX]

I need a script that can do an animation when you are standing on a brick. I just don't know how to do the animation. I can't find a free model with the animation I am looking for. Here is a preview of how I want the hands up. PREVIEW OF THE ANIMATION
The brick you are standing on is
script.Parent
There are two main ways of animation; The newer Animations and the older Joints.
The guide should be able to help you to getting started with animations. It even got a video.
If you want to use a old style Joint animation, something like this might work:
local Block = script.Parent
local function MakeFakeShoulder(Character, Side)
local Controller = { ["Stop"] = function() end }
local Torso = Character:findFirstChild("Torso")
local Arm = Character:findFirstChild(Side .. " Arm")
if not Torso or not Arm then return Controller end
local Shoulder = Torso:findFirstChild(Side .. " Shoulder")
if Shoulder then
local FakeShoulder = Instance.new("ManualWeld")
FakeShoulder.Name = "Fake " .. Side .. " Shoulder"
FakeShoulder.C0 = CFrame.new(1.5 * (Side == "Right" and 1 or -1),0.5,0)
FakeShoulder.C1 = CFrame.new(0,0.5,0) * CFrame.fromAxisAngle(Vector3.FromAxis(Enum.Axis.Z), math.rad(-180))
FakeShoulder.Part0 = Torso
FakeShoulder.Part1 = Arm
FakeShoulder.Parent = Torso
Shoulder.Parent = nil
function Controller:Stop()
Shoulder.Parent = Torso
FakeShoulder:Destroy()
end
end
return Controller
end
local function MakeFakeShoulders(Character)
local Controller = { }
local Right = MakeFakeShoulder(Character, "Right")
local Left = MakeFakeShoulder(Character, "Left")
function Controller:Stop()
Right:Stop()
Left:Stop()
end
return Controller
end
local function GetHumanoid(Part)
if Part.Parent == nil then return nil end
return Part.Parent:findFirstChild("Humanoid")
end
local CurrentlyTouching = { }
Block.Touched:connect(function(Part)
local Humanoid = GetHumanoid(Part)
if not Humanoid then return end
CurrentlyTouching[Humanoid] = CurrentlyTouching[Humanoid] or 0
CurrentlyTouching[Humanoid] = CurrentlyTouching[Humanoid] + 1
if CurrentlyTouching[Humanoid] > 1 then return end
local Controller = MakeFakeShoulders(Part.Parent)
while CurrentlyTouching[Humanoid] > 0 do
if GetHumanoid(Block.TouchEnded:wait()) == Humanoid then
CurrentlyTouching[Humanoid] = CurrentlyTouching[Humanoid] - 1
end
end
Controller:Stop()
end)
Note that if the ending touch do not register good enough, make a invisible CanCollide = false bounding part that is bigger than the visual part and put the script in that one instead,

AS3 SharedObject - Background images fails to load correctly. Set of images stored inside MC fails to load correct image from save

having issues with making a set of background images save and load correctly. Please note, that this has worked correctly in the past with "1 - 2" images in the caseSwapper.
Structure :
On my stage I have set of draggable objects that you can save and load as you please. (these work)
The background, which is movieClip called "caseSwapper" contains a set of frames with different images inside each frame. E.G frame one is called (labelled) "frameone" - contains a pretty picture. Frame 2 is labelled "Frametwo" which contains an alternative image etc etc
A load and save button on the stage allows you to store the data to sharedObject "mySO"
Issues and Behaviour
On the face of it, the save appears to be working. The trace statement is declaring that the current frame is being stored to mySO... although I'm not entirely convinced it is. Basically, when the player has a certain background selected and they click 'save' I need the current image to be saved/written to the sharedObject.
Notes : Frame 1 appears to work when I click 'load' from the stage. When I 'launch' the application (not load) even after saving frame 123 or 4 only frame 4 launches/dis[lays. I then have to click load to retrieve my sharedObject... which only shows the first frame... Any pointers. Script to edit is at the bottom. Please Note, that I'm designer first and foremost!
save_btn.addEventListener (MouseEvent.CLICK, clickersave);
function clickersave (e:MouseEvent):void {
saved.play();
mySO.data.myblcskull_mc_x = blcskull_mc.x;
mySO.data.myblcskull_mc_y = blcskull_mc.y;
mySO.data.myblackhandbag_mc_y = blackhandbag_mc.y;
mySO.data.myblackhandbag_mc_x = blackhandbag_mc.x;
mySO.data.myhotlips_mc_x = hotlips_mc.x;
mySO.data.myhotlips_mc_y = hotlips_mc.y;
mySO.data.my_x = bones_mc.x;
mySO.data.my_y = bones_mc.y;
mySO.data.mybut_x = btrfly_mc.x;
mySO.data.mybut_y = btrfly_mc.y;
mySO.data.mytig_x = tiger_mc.x;
mySO.data.mytig_y = tiger_mc.y;
mySO.data.myskullface_mc_y = skullface_mc.y;
mySO.data.myskullface_mc_x = skullface_mc.x;
mySO.data.myblack_tile_mc_zero_y = black_tile_mc_zero.y;
mySO.data.myblack_tile_mc_zero_x = black_tile_mc_zero.x;
mySO.data.myblack_tile_mc_one_x = black_tile_mc_one.x;
mySO.data.myblack_tile_mc_one_y = black_tile_mc_one.y;
mySO.data.mycrown_mc_y = crown_mc.y;
mySO.data.mycrown_mc_x = crown_mc.x;
mySO.data.myperfume_mc_y = perfume_mc.y;
mySO.data.myperfume_mc_x = perfume_mc.x;
mySO.data.myheart_mc_x = heart_mc.x;
mySO.data.myheart_mc_y = heart_mc.y;
mySO.data.myrose_mc_y = rose_mc.y;
mySO.data.myrose_mc_x = rose_mc.x;
// tears saved - - - - - - -
mySO.data.mytear_drop_mc_one_x = tear_drop_mc_one.x;
mySO.data.mytear_drop_mc_one_y = tear_drop_mc_one.y;
mySO.data.mytearup_drop_mc_three_x = tearup_drop_mc_three.x;
mySO.data.mytearup_drop_mc_three_y = tearup_drop_mc_three.y;
mySO.data.mytearup_drop_mc_four_x = tearup_drop_mc_four.x;
mySO.data.mytearup_drop_mc_four_y = tearup_drop_mc_four.y;
mySO.data.mytear_drop_mc_two_x = tear_drop_mc.x;
mySO.data.mytear_drop_mc_two_y = tear_drop_mc.y;
mySO.data.mytear_side_mc_one_x = tear_side_mc_one.x;
mySO.data.mytear_side_mc_one_y = tear_side_mc_one.y;
mySO.data.mytear_side_mc_two_x = tear_side_mc_two.x;
mySO.data.mytear_side_mc_two_y = tear_side_mc_two.y;
mySO.data.mytear_op_mc_one_y = tear_op_mc_one.y;
mySO.data.mytear_op_mc_one_x = tear_op_mc_one.x;
mySO.data.mytear_op_mc_two_y = tear_op_mc_two.y;
mySO.data.mytear_op_mc_two_x = tear_op_mc_two.x;
//tear_op_mc_one
// pink gems
mySO.data.mypink_jewel_mc_one_x = pink_jewel_mc_one.x;
mySO.data.mypink_jewel_mc_one_y = pink_jewel_mc_one.y;
mySO.data.mypink_jewel_mc_two_x = pink_jewel_mc_two.x;
mySO.data.mypink_jewel_mc_two_y = pink_jewel_mc_two.y;
mySO.data.mypink_jewel_mc_three_x = pink_jewel_mc_three.x;
mySO.data.mypink_jewel_mc_three_y = pink_jewel_mc_three.y;
mySO.data.mypink_jewel_mc_four_x = pink_jewel_mc_four.x;
mySO.data.mypink_jewel_mc_four_y = pink_jewel_mc_four.y;
mySO.data.mypink_jewel_mc_five_x = pink_jewel_mc_five.x;
mySO.data.mypink_jewel_mc_five_y = pink_jewel_mc_five.y;
mySO.data.mypink_jewel_mc_six_x = pink_jewel_mc_six.x;
mySO.data.mypink_jewel_mc_six_y = pink_jewel_mc_six.y;
mySO.data.mypink_jewel_mc_seven_x = pink_jewel_mc_seven.x;
mySO.data.mypink_jewel_mc_seven_y = pink_jewel_mc_seven.y;
mySO.data.mypink_jewel_mc_eight_x = pink_jewel_mc_eight.x;
mySO.data.mypink_jewel_mc_eight_y = pink_jewel_mc_eight.y;
mySO.data.mypink_jewel_mc_nine_x = pink_jewel_mc_nine.x;
mySO.data.mypink_jewel_mc_nine_y = pink_jewel_mc_nine.y;
// bg saves
mySO.data.myBgFrame = 1;
mySO.data.myBgFrameone = 2;
mySO.data.myBgFrametwo = 3;
mySO.data.myBgFramethree = 4;
trace("bgbackgrounds");
// silver gems - - - - - - - - -
mySO.data.mycircle_gem_mc_x = circle_gem_mc.x;
mySO.data.mycircle_gem_mc_y = circle_gem_mc.y;
mySO.data.mycircle_gem_mc_two_x = circle_gem_mc_two.x;
mySO.data.mycircle_gem_mc_two_y = circle_gem_mc_two.y;
mySO.data.mycircle_gem_mc_thirteen_x = circle_gem_mc_thirteen.x;
mySO.data.mycircle_gem_mc_thirteen_y = circle_gem_mc_thirteen.y;
//circle_gem_mc_six
mySO.flush ();
}
if (mySO.data.myBgFrame){
caseSwapper.gotoAndStop(mySO.data.myBgFrame);
}
if (mySO.data.myBgFrameone){
caseSwapper.gotoAndStop(mySO.data.myBgFrameone);
}
if (mySO.data.myBgFrametwo){
caseSwapper.gotoAndStop(mySO.data.myBgFrametwo);
}
if (mySO.data.myBgFramethree){
caseSwapper.gotoAndStop(mySO.data.myBgFramethree);
}
//caseSwapper.currentFrame = mySO.data.myBgFrame;
/////// ---------------------- loader
// ---------------------- LOADER -------------------------
//--------------------------------------------------------
//--------------------------------------------------------
// when load button is clicked it loads the x and y position of dragged objects pulled from the
//sharedOject, it remembers the last var!
load_btn.addEventListener (MouseEvent.CLICK, loadlast);
function loadlast (e:MouseEvent):void {
//saved.play();
caseSwapper.gotoAndStop(mySO.data.myBgFrame);
//caseSwapper.currentFrame = mySO.data.myBgFrame;
//caseSwapper.gotoAndStop(mySO.data.myBgFrameone);
//caseSwapper.gotoAndStop(mySO.data.myBgFrametwo);
//caseSwapper.gotoAndStop(mySO.data.myBgFramethree);
//caseSwapper.gotoAndStop(mySO.data.myBgFramefour);
blcskull_mc.x = mySO.data.myblcskull_mc_x;
blcskull_mc.y = mySO.data.myblcskull_mc_y;
blackhandbag_mc.y = mySO.data.myblackhandbag_mc_y;
blackhandbag_mc.x = mySO.data.myblackhandbag_mc_x;
bones_mc.x = mySO.data.my_x;
bones_mc.y = mySO.data.my_y;
tiger_mc.x = mySO.data.mytig_x;
tiger_mc.y = mySO.data.mytig_y;
btrfly_mc.x = mySO.data.mybut_x;
btrfly_mc.y = mySO.data.mybut_y;
crown_mc.x = mySO.data.mycrown_mc_x;
crown_mc.y = mySO.data.mycrown_mc_y;
perfume_mc.x = mySO.data.myperfume_mc_x;
perfume_mc.y = mySO.data.myperfume_mc_y;
heart_mc.x = mySO.data.myheart_mc_x;
heart_mc.y = mySO.data.myheart_mc_y;
rose_mc.y = mySO.data.myrose_mc_y;
rose_mc.x = mySO.data.myrose_mc_x;
pink_jewel_mc_one.x = mySO.data.mypink_jewel_mc_one_x;
pink_jewel_mc_one.y = mySO.data.mypink_jewel_mc_one_y;
pink_jewel_mc_two.x = mySO.data.mypink_jewel_mc_two_x;
pink_jewel_mc_two.y = mySO.data.mypink_jewel_mc_two_y;
pink_jewel_mc_three.x = mySO.data.mypink_jewel_mc_three_x;
pink_jewel_mc_three.y = mySO.data.mypink_jewel_mc_three_y;
pink_jewel_mc_four.x = mySO.data.mypink_jewel_mc_four_x;
pink_jewel_mc_four.y = mySO.data.mypink_jewel_mc_four_y;
pink_jewel_mc_five.x = mySO.data.mypink_jewel_mc_five_x;
pink_jewel_mc_five.y = mySO.data.mypink_jewel_mc_five_y;
pink_jewel_mc_six.x = mySO.data.mypink_jewel_mc_six_x;
pink_jewel_mc_six.y = mySO.data.mypink_jewel_mc_six_y;
pink_jewel_mc_seven.x = mySO.data.mypink_jewel_mc_seven_x;
pink_jewel_mc_seven.y = mySO.data.mypink_jewel_mc_seven_y;
pink_jewel_mc_eight.x = mySO.data.mypink_jewel_mc_eight_x;
pink_jewel_mc_eight.y = mySO.data.mypink_jewel_mc_eight_y;
pink_jewel_mc_nine.x = mySO.data.mypink_jewel_mc_nine_x;
pink_jewel_mc_nine.y = mySO.data.mypink_jewel_mc_nine_y;
hotlips_mc.x = mySO.data.myhotlips_mc_x;
hotlips_mc.y = mySO.data.myhotlips_mc_y;
tearup_drop_mc_three.y = mySO.data.mytearup_drop_mc_three_y;
tearup_drop_mc_three.x = mySO.data.mytearup_drop_mc_three_x;
tearup_drop_mc_four.x = mySO.data.mytearup_drop_mc_four_x;
tearup_drop_mc_four.y = mySO.data.mytearup_drop_mc_four_y;
tear_side_mc_one.x = mySO.data.mytear_side_mc_one_x;
tear_side_mc_one.y = mySO.data.mytear_side_mc_one_y;
//tear_side_mc_two.x = mySO.data.mytear_side_mc_two_x;
//tear_side_mc_two.y = mySO.data.mytear_side_mc_two_y;
tear_op_mc_one.y = mySO.data.mytear_op_mc_one_y;
tear_op_mc_one.x = mySO.data.mytear_op_mc_one_x;
tear_op_mc_two.y = mySO.data.mytear_op_mc_two_y;
tear_op_mc_two.x = mySO.data.mytear_op_mc_two_x;
//--- silver little gems -----------------
circle_gem_mc_thirteen.x = mySO.data.mycircle_gem_mc_thirteen_x;
circle_gem_mc_thirteen.y = mySO.data.mycircle_gem_mc_thirteen_y;
circle_gem_mc_two.x = mySO.data.mycircle_circle_gem_mc_two_x;
circle_gem_mc_two.y = mySO.data.mycircle_circle_gem_mc_two_y;
mySO.flush ();
}
You're not actually storing the current frame anywhere — this section just saves the same numbers every time:
mySO.data.myBgFrame = 1;
mySO.data.myBgFrameone = 2;
mySO.data.myBgFrametwo = 3;
mySO.data.myBgFramethree = 4;
This is also why you're only seeing frame four when you launch, because all of your if statements see a positive number (and anything other than zero or NaN counts as true), so they all get executed one after the other.
Instead of the above, all you need is this in your save function:
mySO.data.myBgFrame = caseSwapper.currentFrame;
Then if you want to jump to that frame on launch, you only need your first if statement:
if (mySO.data.myBgFrame){
caseSwapper.gotoAndStop(mySO.data.myBgFrame);
}

Corona - Touch Events In table objects?

I am trying to use this in a project, but I cannot figure out how to place a touch event listener to each of the icons/objects in the carousel, If someone could provide a quick answer of how to do that I'd appreciate it.
local NUM_ITEMS=20;
local radiusX= 200;
local radiusY= 40;
local centerX = 240;
local centerY = 160;
local speed = 0.05;
local perspective = 3;
local carousel = display.newGroup()
local icons = {}
local function zSort(myTable, myGroup)
table.sort(myTable,
function(a, b)
return a.depth < b.depth -- depth is your custom field
end
)
for i = 1, #myTable do
myGroup:insert(myTable[i].img)
end
end
function Icon(i)
local this = {}
local icon = display.newImage(carousel, "images/icon"..i..".png")
this.angle = (i-1) * math.rad(360/NUM_ITEMS);
this.img = icon
return this
end
function update(event)
local icon
local sin = math.sin
local cos = math.cos
for i=1, NUM_ITEMS, 1 do
icon = icons[i]
local img = icon.img
img.x = cos(icon.angle) * radiusX + centerX
img.y = sin(icon.angle) * radiusY + centerY
local s = (img.y - perspective) / (centerX + radiusY - perspective)
img.xScale = s*0.25
img.yScale = s*0.25
icon.angle = (icon.angle + speed) --%math.rad(360)
icon.depth = s
end
zSort(icons, carousel)
end
for i=1, NUM_ITEMS, 1 do
local icon = Icon(i)
icons[i] = icon
end
function onTouch(event)
if(event.phase=="moved") then
speed = (event.x - centerX) / 2000;
end
end
Runtime:addEventListener("enterFrame",update)
Runtime:addEventListener("touch", onTouch)
I can't exactly understood what you really need. But if you want to add individual touch to all same icons in a localGroup, then you can add the icons as an icon array and give specific tag to each and can give individual touch, as follows:
local icons = {}
for i=1,10 do
icons[i] = display.newImage(i..".png")
icons[i].tag = i
end
local function touchIt(e)
print(e.target.tag)
--[[ icons[e.target.tag] can be used to identify
and set properties to the touched icon --]]
end
for i=1,10 do
icons[i]:addEventListener("touch",touchIt)
end
OR
if you want to identify all group elements as the same and give touch, then you can use same tag/ give userdata to all icons and can give same touch action to all group elements(as follows).
local icons = {}
for i=1,10 do
icons[i] = display.newImage(i..".png")
icons[i].tag = 1 --[[ you can also use icons[i].userdata = "icons"
(or any string)--]]
end
local function touchIt(e)
print(e.target.tag) -- It willo be 1 for all icons
--[[ icons[e.target.tag] can be used to identify
whether if it is under 'icons' --]]
--[[ or use userdata as follows --]]
print(e.target.userdata)--[[ out put is a string
identifying the group/element--]]
end
for i=1,10 do
icons[i]:addEventListener("touch",touchIt)
end

Python GUI (tkinter.ttk) application slow

I've got (working) application done with ttk. It uses self-created module for showing a comport-related controls and a canvas which draws a few graphs on it. When I crate an instance of my object, it starts a thread in which processes serial input and appends this to a list (one list per graph). When I have 3-6 graphs, the application gets noticeably slow. It also has got a few bugs, but I will adress them when I'm done with the general concept.
Things that may help you help me:
comport is an instance of a self-written object that derives from
LabelFrame and Serial.Serial
coordinates for graphs are stored in a dictionary of lists:
self.graphs = {} self.graphs['name1']=[] number of coordinates stored
is up to the width of canvas, so about 1000-2000 per graph. Have six
graphs - please multiply by 6
With every new coordinate arriving I pop(0) from the list and
append() the new coordinate
I forgot, I also store timing of each new set of coordinates arriving
in a separate list
I use a preiodic call function to process the lists: self.after(100,
func=self.periodicCall)Thus every 100ms I delete(ALL) from the canvas
and I draw every graph with theset of lines. So if I have 1000 coords
in 6 graps, I draw 6000 small lines
Plus some service info of course such as a few rulers
So I guess the idea is clear. I want to figure out what would be the better approach. I'm just a started in python and in programming as well, so I'm asking for your excuse for the code that I'm going to post and for the pain in your eyes it's gonna cause. I don't have any programming style and I want to fix it. At least a bit. So any other comments on anything you'll se in the code are welcome.
#-------------------------------------------------------------------------------
# Name: dataVisualizer
# Purpose:
#
# Author: dccharacter
#
# Created: 23.03.2012
# Copyright: (c) dccharacter 2012
# Licence: <your licence>
#-------------------------------------------------------------------------------
#!/usr/bin/env python
from tkinter import *
from tkinter.ttk import *
from robowidgets.serialPortGui import *
import threading
import re
import atexit
import random
from datetime import datetime
import time
class dataVisualizer(LabelFrame):
def __init__(self, master, comport , cnf={}, **kw):
self.master = master
self.comport = comport
LabelFrame.__init__(self, *cnf, **kw)
self.messageVar = StringVar()
Label(self, text="Message format regexp:").pack()
self.messagePattern = Entry(self, width = 20, text = 234234, textvariable = self.messageVar);
self.messageVar.set(r'(-*\d+),(-*\d+),(-*\d+),(-*\d+),(-*\d+),(-*\d+)')
self.messagePattern.pack()
Button(self, text = "Pause", command = self.pause).pack()
self.pauseFlag = TRUE
self.canvWidth, self.canvHeight = 1000, 700
self.density = 1 ##width of pixel - the bigger, the wider graph
self.numOfDots = self.canvWidth//self.density
self.graphs = {}
self.graphs['name1']=[]
self.graphs['name2']=[]
self.graphs['name3']=[]
self.graphs['name4']=[]
self.graphs['name5']=[]
self.graphs['name6']=[]
self.timings = []
self.zeroTiming = datetime.now()
self.colors = ['red', 'blue', 'green', 'orange', 'violet', 'black', 'cyan']
self.canv = Canvas(self, width = self.canvWidth, height = self.canvHeight)
self.canv.pack()
self.thread = threading.Thread(target = self.workerThread)
self.thread.start()
self.serialData = []
self.periodicCall()
def pause(self):
self.pauseFlag = ~self.pauseFlag
def redraw(self):
self.canv.delete(ALL)
colorIndex = 0
for graphName in self.graphs:
runningAverage = sum(self.graphs[graphName][-10:])//10
text = str(runningAverage)
self.canv.create_text(self.canvWidth-60, 20*(colorIndex+1), text = text,
fill = self.colors[colorIndex], anchor = W)
prev_xxx, prev_yyy = 0, 0
for yyy in self.graphs[graphName]:
self.canv.create_line(prev_xxx, prev_yyy, prev_xxx+self.density, self.canvHeight//2 - yyy,
width = 1.4, fill = self.colors[colorIndex])
prev_xxx, prev_yyy = prev_xxx+self.density, self.canvHeight//2 - yyy
colorIndex = colorIndex + 1
self.drawMesh()
def drawMesh(self):
self.canv.create_rectangle(3, 3, self.canvWidth,
self.canvHeight, outline = 'black', width = 2)
self.canv.create_line(0, self.canvHeight/2, self.canvWidth,
self.canvHeight/2, fill="black", width = 1)
mouseX = self.canv.winfo_pointerx() - self.canv.winfo_rootx()
mouseY = self.canv.winfo_pointery() - self.canv.winfo_rooty()
if mouseY < 60: aaa = -1
else: aaa = 1
if mouseX > self.canvWidth - 200 : bbb = -12
else: bbb = 1
try:
self.canv.create_rectangle(mouseX + 10*bbb - 5, mouseY - 20*aaa +10,
mouseX + 10*bbb + 115, mouseY - 20*aaa - 30, outline = "black",
fill = "red")
self.canv.create_text(mouseX + 10*bbb, mouseY - 40*aaa,
text = "t="+str(self.timings[mouseX//self.density]),
anchor = W)
self.canv.create_text(mouseX + 10*bbb, mouseY - 20*aaa,
text = "value="+str(self.canvHeight//2 - mouseY),
anchor = W)
except IndexError:
pass
self.canv.create_line(mouseX, 0, mouseX,
self.canvHeight, fill="blue", dash = [4, 1, 2, 1], width = 1)
self.canv.create_line(0, mouseY, self.canvWidth,
mouseY, fill="blue", dash = [4, 1, 2, 1], width = 1)
def periodicCall(self):
self.redraw()
self.after(100, func=self.periodicCall)
def workerThread(self):
while (1):
try:
if self.comport.isOpen() and (self.pauseFlag == TRUE):
comLine = self.comport.readline()
if len(self.timings) == self.numOfDots:
self.timings.pop(0)
td = datetime.now() - self.zeroTiming
## b'271;-3:-50\r\n'
parsedLine = re.search(self.messagePattern.get(), str(comLine))
index = 1
if parsedLine:
self.timings.append(td)
for graphName in self.graphs:
if len(self.graphs[graphName]) == self.numOfDots:
self.graphs[graphName].pop(0)
try:
self.graphs[graphName].append(int(parsedLine.group(index)))
except IndexError:
self.graphs[graphName].append(0)
index = index + 1
else:
self.comport.flush();
time.sleep(1)
except TclError:
self.thread._stop()
def main():
root = Tk()
mainWindow = Frame(root)
mainWindow.pack()
port = comPortWidget(mainWindow)
port.pack()
dv = dataVisualizer(mainWindow, port)
dv.pack()
root.mainloop()
if __name__ == '__main__':
main()
And the serial part - may lag as well (used to lag when I used to reenumerate ports evey second or so...)
#-------------------------------------------------------------------------------
# Name: robowidgets
# Purpose:
#
# Author: dccharacter
#
# Created: 10.03.2012
# Copyright: (c) dccharacter 2012
# Licence: <your licence>
#-------------------------------------------------------------------------------
#!/usr/bin/env python
import serial
from serial.tools.list_ports_windows import comports
from tkinter import *
from tkinter.ttk import *
class comPortWidget(LabelFrame, serial.Serial):
commonComPortSpeeds = ["1200", "2400", "4800", "9600", "14400", "19200", "38400", "57600", "115200"]
def __init__(self, master=None, cnf={}, **kw):
"""Construct a comPortWidget widget with the parent MASTER.
STANDARD OPTIONS
borderwidth, cursor, font, foreground,
highlightbackground, highlightcolor,
highlightthickness, padx, pady, relief,
takefocus, text, background, class, colormap, container,
height, labelanchor, labelwidget,
visual, width
WIDGET-SPECIFIC OPTIONS
"""
self.master = master
LabelFrame.__init__(self, master, text="Serial settings", *cnf, **kw)
serial.Serial.__init__(self)
self.parent = master
self.draw()
def draw(self):
self.strVarComPort = StringVar()
self.comboComport = Combobox(self,
textvariable=self.strVarComPort)
self.comboComport.grid(row=0, column=1)
self.labelComportName = Label(self, text="Com port:")
self.labelComportName.grid(row=0, column=0)
self.strVarComSpeed = StringVar()
self.comboComSpeed = Combobox(self,
textvariable=self.strVarComSpeed, values=self.commonComPortSpeeds)
self.comboComSpeed.current(len(self.commonComPortSpeeds)-1)
self.comboComSpeed.grid(row=1, column=1)
self.labelComSpeed = Label(self, text="Com speed:")
self.labelComSpeed.grid(row=1, column=0)
self.buttonComOpen = Button(self, text="Open port", command=self.openPort)
self.buttonComOpen.grid(row=0, column=2)
self.buttonComClose = Button(self, text="Close port", command=self.closePort)
self.buttonComClose.grid(row=1, column=2)
self.buttonRefreshPorts = Button(self, text="Re", width=3, command=self.refreshComPortsCombo)
##self.buttonRefreshPorts.grid(row=0, column=2)
self.refreshComPortsCombo()
def refreshComPortsCombo(self):
listComs = self.enumerateComPorts()
if not listComs:
listComs.append("No com ports found")
self.disableControls(~self.isOpen())
self.buttonComClose.configure(state=DISABLED)
else:
self.disableControls(self.isOpen())
self.buttonRefreshPorts.configure(state=NORMAL)
self.comboComport.config(values=listComs)
self.comboComport.current(len(listComs)-1)
##self.after(500, func=self.refreshComPortsCombo)
def enumerateComPorts(self):
"""
Returns the list ofcom port names in the system or an empty list if
no ports found
"""
listComs = []
for port, desc, hwid in sorted(comports()):
listComs.append(port)
return listComs
def openPort(self):
if self.isOpen():
return
self.port = self.comboComport.get()
self.baudrate = int(self.comboComSpeed.get())
self.timeout = 1
try:
self.open()
self.disableControls(self.isOpen())
except IOError:
pass
def closePort(self):
if self.isOpen():
self.flush()
self.close()
self.disableControls(self.isOpen())
def disableControls(self, isConnected):
if isConnected:
self.labelComportName.configure(state=DISABLED)
self.labelComSpeed.configure(state=DISABLED)
self.comboComport.configure(state=DISABLED)
self.comboComSpeed.configure(state=DISABLED)
self.buttonComClose.configure(state=NORMAL)
self.buttonComOpen.configure(state=DISABLED)
self.buttonRefreshPorts.configure(state=DISABLED)
else:
self.labelComportName.configure(state=NORMAL)
self.labelComSpeed.configure(state=NORMAL)
self.comboComport.configure(state=NORMAL)
self.comboComSpeed.configure(state=NORMAL)
self.buttonComClose.configure(state=DISABLED)
self.buttonComOpen.configure(state=NORMAL)
self.buttonRefreshPorts.configure(state=NORMAL)
def main():
pass
if __name__ == '__main__':
main()
UPDATE: I did as Brian advised. Now I have two screen redraw functions. Difference between them is that first moves all the lines to the left adding new to the right and deleting those that fall off the canvas. The second one moves lines to the left and re-deploys elements that fall off the canvas to the right (without creating new ones). There's a huge improvement with any of these in respect to my initial variant, but I don't see big difference between the two wit the naked eye - mayme if I had more elements I would. The latter though works better specifically for my application as I don't have to track those who fall off the cliff.
Here the functions:
def drawGraph(self): ###needed for self.updateGraph2() only as it is creates the lines
for graphNum in range(0, self.numOfGraphs):
self.graphLines.append([])
self.graphData.append([0,]*self.numOfDots)
for iii in range(0,self.numOfDots):
self.graphLines[graphNum].append(
self.canv.create_line(0,0,0,0,fill=self.colors[graphNum],
width=1.2, tags=('graphLines', 'graph'+str(graphNum)))
)
def updateGraph2(self):
while not self.queue.empty():
iTuple = self.queue.get()
self.canv.move('graphLines', -self.density,0)
for graphNum in range(0, self.numOfGraphs):
try: self.graphData[graphNum].append(iTuple[graphNum])
except IndexError:
self.graphData[graphNum].append(0)
self.graphData[graphNum].pop(0)
self.graphLines[graphNum].append(self.graphLines[graphNum].pop(0))
self.canv.coords(self.graphLines[graphNum][-1],
self.canv.winfo_width()-self.density,
int(int(self.graphData[graphNum][-2])+int(self.canv.winfo_height()//2)),
self.canv.winfo_width(),
int(int(self.graphData[graphNum][-1])+int(self.canv.winfo_height()//2))
)
def updateGraph(self):
while not self.queue.empty():
self.timingIndex = self.timingIndex + 1
self.canv.move('graphLines', -self.density, 0)
iTuple = self.queue.get()
for iii in range(0, len(iTuple)):
yyy = int(iTuple[iii])+self.canv.winfo_height()//2
if yyy < 0: yyy = 0
if yyy > self.canv.winfo_height(): yyy = self.canv.winfo_height()
prev_yyy = int(self.prevTuple[iii])+self.canv.winfo_height()//2
if prev_yyy < 0: prev_yyy = 0
if prev_yyy > self.canv.winfo_height(): prev_yyy = self.canv.winfo_height()
self.canv.create_line(
self.canv.winfo_width()-self.density, prev_yyy,
self.canv.winfo_width(), yyy,
width = 1.4, fill = self.colors[iii], tags=('graphLines','graph'+str(iii)))
self.prevTuple = iTuple
self.canv.addtag_overlapping('todelete',-1,-1,-3,self.canv.winfo_height()+1)
self.canv.dtag('preserve','todelete')
self.canv.delete('todelete')
My understanding of the canvas is that the more element ids that have been allocated, the slower it gets. It can handle tens of thousands without much problem (and maybe even 100's of thousands), but if you're creating and deleting 6000 items every 100ms, that is likely your problem. Even though you are deleting the items, it still affects performance especially when you are creating 60,000 per second.
Instead of deleting all items every 100ms, simply move the items off screen and remember them, then reuse them by using the coords method to change their coordinates for the new graph.

Resources