How to link keyboard press to action - keyboard

I'm getting the hang of Elm but I keep struggling with signals and keyboard presses. The code below is an example of the start-app package. I would like to have that when I press the spacebar that the counter is incremented. How is this done in the example below?
import Html exposing (div, button, text)
import Html.Events exposing (onClick)
import StartApp.Simple as StartApp
main =
StartApp.start { model = model, view = view, update = update }
model = 0
view address model =
div []
[ button [ onClick address Decrement ] [ text "-" ]
, div [] [ text (toString model) ]
, button [ onClick address Increment ] [ text "+" ]
]
type Action = Increment | Decrement
update action model =
case action of
Increment -> model + 1
Decrement -> model - 1

You'll need to use regular StartApp rather than StartApp.Simple because it provides the means to use Effects and Tasks.
The Action needs a NoOp constructor to allow our view to remain unchanged when a key press is not the spacebar.
Then you'll need a function which maps the Keyboard.presses value to an Action. Here's the updated code:
import Html exposing (div, button, text)
import Html.Events exposing (onClick)
import StartApp
import Effects exposing (Never)
import Task
import Keyboard
import Char
app =
StartApp.start
{ init = init
, view = view
, update = update
, inputs = [ Signal.map spaceToInc Keyboard.presses ]
}
main =
app.html
type alias Model = Int
init =
(0, Effects.none)
view address model =
div []
[ button [ onClick address Decrement ] [ text "-" ]
, div [] [ text (toString model) ]
, button [ onClick address Increment ] [ text "+" ]
]
type Action
= Increment
| Decrement
| NoOp
update action model =
case action of
NoOp -> (model, Effects.none)
Increment -> (model + 1, Effects.none)
Decrement -> (model - 1, Effects.none)
spaceToInc : Int -> Action
spaceToInc keyCode =
case (Char.fromCode keyCode) of
' ' -> Increment
_ -> NoOp
port tasks : Signal (Task.Task Never ())
port tasks =
app.tasks

Related

Nested triples with units on value in rdflib - > turtle file

I'm currently making a turtle file. I have to relate values/units based on qudt.org
Based on example data shown below:
data = { "objectid_l1": "Bridge_1",
"defid_l1": "Bridge",
"objectid_l2": "Deck_1",
"defid_l2": "Deck",
"variable": "height",
"value": "50.0",
"unit": "M",
}
i made the following code, but the output is not what i want:
from rdflib.namespace import RDF
from rdflib import URIRef, BNode, Literal, Namespace, Graph
EX = Namespace('https://example.com/id/')
UNIT = Namespace('http://qudt.org/2.1/vocab/unit/')
BS = Namespace('https://w3id.org/def/basicsemantics-owl#')
for i in data:
if i['objectid_l1'] != None:
g.add((
EX[i['objectid_l1']],
RDF.type,
EX[i['defid_l1']]
))
g.add((
EX[i['objectid_l1']],
BS['hasPart'],
EX[i['objectid_l2']]
))
g.add((
EX[i['objectid_l1']],
EX[i['variable']],
EX[i['value']]
))
g.add((
EX[i['variable']],
BS['unit'],
UNIT[i['unit']]
))
output:
ex:Bridge_1
a ex:Bridge ;
bs:hasPart ex:Deck_1 ;
ex:height 50.0 .
50.0 bs:unit unit:M .
As output i want that the units indent, the desired output is as follows:
ex:Bridge_1
a ex:Bridge ;
bs:hasPart ex:Deck_1 ;
ex:height [
rdf:value 50.0 ;
bs:unit unit:M ;
];
There is a few things missing in your code to achieve what you want :
you need to explicitely create the blank node you show in the expected output, using rdflib BNode, then use it as subject of the triples setting the height value and the unit
you have to specify that the height value (50.0) is a litteral value.
from rdflib.namespace import RDF, XSD, NamespaceManager
from rdflib import BNode, Literal, Namespace, Graph
EX = Namespace('https://example.com/id/')
UNIT = Namespace('http://qudt.org/2.1/vocab/unit/')
BS = Namespace('https://w3id.org/def/basicsemantics-owl#')
g = Graph()
g.namespace_manager = NamespaceManager(Graph())
g.namespace_manager.bind('unit', UNIT)
g.namespace_manager.bind('bs', BS)
g.namespace_manager.bind('ex', EX)
i = {
"objectid_l1": "Bridge_1",
"defid_l1": "Bridge",
"objectid_l2": "Deck_1",
"defid_l2": "Deck",
"variable": "height",
"value": "50.0",
"unit": "M",
}
if i['objectid_l1'] != None:
g.add((EX[i['objectid_l1']], RDF.type, EX[i['defid_l1']]))
g.add((EX[i['objectid_l1']], BS['hasPart'], EX[i['objectid_l2']]))
bnode = BNode()
g.add((bnode, RDF.value, Literal(i['value'])))
g.add((bnode, BS['unit'], UNIT[i['unit']]))
g.add((EX[i['objectid_l1']], EX[i['variable']], bnode))
g.serialize('test.ttl', format='ttl')
Should output as expected :
ex:Bridge_1 a ex:Bridge ;
bs:hasPart ex:Deck_1 ;
ex:height [ rdf:value "50.0" ;
bs:unit unit:M ] .

Elm filter a list with input String

I have model
type alias Model =
{
url : String
, devices : List Device
, input : String
, isFilter : Bool
, deviceSuggestion : Maybe Device
}
type alias Device =
{
status : String
, license_plate : String
, device_id : String
}
This is how i update the data but i have no idea how to do for filter after i type something in the search box
update msg model =
case msg of
GotResult result ->
case result of
Ok devices ->
( { model | devices = devices }, portDevice devices )
Err devices ->
( { model | error = Just "Error" }, Cmd.none )
Tick _ ->
( model, fetchUrl )
InputChange newInput ->
( { model | input = newInput //function filter here?}, Cmd.none)
SearchFunction ->
({ model | input = "" }, toJS model.input)
This is my rendering View
renderPosts : Model -> Html Msg
renderPosts model =
div []
[ h3 [] [ text "Filter List" ] ,
, input [ type_ "text"
, placeholder "Searching for devices"
, onInput InputChange
, value model.input
, id "inputDevices"
] []
--, checkListFunction model //check and filter list function here as well?
, button [ onClick SearchFunction , id "searchDevice"] [ text "Search" ]
,
div []
([ text "Device List" ] ++ List.map (\device -> renderPost device) model.devices) //display function
]
I want the output is like when i type the 1234 in searchbox then it detects and filter the below list with the license_plate in devices list.
**I tried the list.filter but it allows compare list to list.
**I tried String.contains but i need 2 strings. It gives error because input box is String and license_plate is List
Any help is appreciate...
https://www.w3schools.com/howto/howto_js_filter_lists.asp <<< Example of output
Below is an example of modifying your renderPosts function with a filteredDevices binding, showing how you could apply the filter:
renderPosts : Model -> Html Msg
renderPosts model =
let
filteredDevices =
List.filter (\device => String.contains model.input device.license_plate) model.devices
in
div []
[ h3 [] [ text "Filter List" ] ,
...
div []
([ text "Device List" ] ++ List.map (\device -> renderPost device) filteredDevices)
]

Corona + objects are not cleared between levels despite removeSelf + set to nil

I have multilevel game and all my objects stay 'empty' in memory between levels
what i mean is that if I set physics to hybrid, when i come again in the level, (or another level) it shows a box but without the picture. (and physics act on these empty boxes)
in the destroyScene I have made sure they are all
myObj:removeSelf()
myObj = nil
and i print a message to prove that it actually does it.
Also in the menu in the enterScene, just in case I do a
local prior_scene = storyboard.getprevious()
storyboard.purgescene( prior_scene )
and also tried a
storyboard.removeAll()
and even a
storyboard.purgeOnSceneChange = true
nothing works when i go to the next level, or into the same level again, all my previous objects are still here, I just don't get it
ok, it's gonna be a bit long but here the entire level. it does go through the destroyscene but somehow the display objects are not removed.
-- scene5
----------------------------------------------------------------------------------
local storyboard = require( "storyboard" )
local scene5 = storyboard.newScene()
function scene5:createScene( event )
local group = self.view
puppetJColCount = 0
print ("createScene5", puppetJColCount)
-----------------------------------------------------------------------------
-- CREATE display objects and add them to 'group' here.
-- Example use-case: Restore 'group' from previously saved state.
local physics = require("physics")
physics.start()
--physics.setScale(50)
puppetT_outside = false
puppetJ_outside = false
end -- scene -------------------------
-- set and release the catapult for puppetT
function arm_puppetT(event)
if event.phase == "began" then
display.getCurrentStage():setFocus(puppetT)
arming_puppetT = true
elseif event.phase == "moved" then
puppetT.x = event.x
puppetT.y = event.y
elseif event.phase == "ended" then
puppetT:applyLinearImpulse(event.xStart - event.x, event.yStart - event.y, puppetT.x, puppetT.y)
display.getCurrentStage():setFocus(nil)
arming_puppetT = false
end
end -- arm_puppetT ----------------------------------------------------------------------------
function build_puppetT()
-- setup puppetT
puppetT = display.newImage("assets/t-head-57-78.png")
puppetT.x = 80
puppetT.y = 100
physics.addBody(puppetT,"dynamic",{density=1.0, friction =0.3, bounce=0.2})
-- setup catapult event for arming puppetT
puppetT:addEventListener("touch", arm_puppetT)
end -- build_puppetT
function build_puppetJ_wall()
puppetJColCount = puppetJColCount + 1 -- how many columns of puppetJ
puppetJIJ = {} -- define puppetJ as an array
ij = 0
ipuppetJtot = 0
--puppetJColCount = 1
print ("build_puppetJ_wall puppetJColCount>" , puppetJColCount);
for i=1, 4 do
for j=1, puppetJColCount do
ij = ij + 1 -- # of puppetJs on the screen
ipuppetJtot = ipuppetJtot + 1
puppetJIJ = display.newImageRect("assets/j-head-70-75.png",80,75)
puppetJIJ.x = 600 + j*22
puppetJIJ.y = 100 + (puppetJIJ.height /2 * (i -1))
physics.addBody(puppetJIJ,"dynamic",{density=1.0,friction=0.3,bounce=0.2,isSensor=false,radius = var})
end
end
print ("building puppetJs #:" ,ipuppetJtot)
end -- build_puppetJ_wall -------------------------------------------------------------
function every_frame( event )
end -- every_frame --------------------------------------------------------------------
--reset level
function tap_reset_level(event)
puppetT:applyLinearImpulse(0, 0, 0, 0) -- stop the kick
print "restarting physics?"
puppetT:setLinearVelocity( 0, 0 ) -- stop the speed
puppetT.x = 80
puppetT.y = 100
for ij = 1,ipuppetJtot do
if (puppetJIJ) then
puppetJIJ:removeSelf()
puppetJIJ = nil ------
end
end
puppetT:removeSelf()
puppetT = nil
build_puppetJ_wall()
build_puppetT()
puppetT_outside = false
puppetJ_outside = false
-- physics.addBody(puppetT,"dynamic",{density=1.0, friction =0.3, bounce=0.2})
-- puppetT:addEventListener("touch", arm_puppetT)
--physics.start()
end -- tap_reset_level -------------------------------------------------------------------------
function tap_main_menu(event)
print ("going to main menu")
Runtime:removeEventListener("enterFrame", every_frame)
for ij = 1,ipuppetJtot do
if (puppetJIJ) then
puppetJIJ:removeSelf()
puppetJIJ = nil ------
end
end
if (puppetT) then
puppetT:removeSelf()
puppetT = nil
end
-- scene5:exitScene(scene5)
storyboard.gotoScene( "menu" )
end -- tap_main_menu ---------------------------------------------------------------------------------
-- ======================================================================================
-- Called immediately after scene has moved onscreen:
function scene5:enterScene( event )
local group = self.view
-----------------------------------------------------------------------------
-- INSERT code here (e.g. start timers, load audio, start listeners, etc.)
-- group:insert( reset_btn )
-- load background
print ("enterScene scene5 " , puppetJtot)
background = display.newImage("assets/parliament-1200-800.png",0,0)
--create reset level button
reset_btn = display.newImageRect( "assets/btn_reset_128.png", 50,50)
reset_btn.x = 50
reset_btn.y = 50
--create main menu button
main_menu_btn = display.newImageRect( "assets/btn_home_128.png", 50,50)
main_menu_btn.x = 100
main_menu_btn.y = 50
-- show the level
local myText = display.newText( "Level 5", display.contentWidth - 60, 50, "Helvetica", 24 )
myText:setTextColor(255, 255, 255)
-- insert(floor);
floor = display.newRect(20,display.contentHeight - 40,display.contentWidth - 40 ,10)
physics.addBody(floor,"static",{density=1.0, friction =-0.3,bounce=-0.2,isSensor=false})
-- build puppetT
build_puppetT()
print ("width=" , display.contentWidth , "height=",display.contentHeight)
-- setup puppetJs
build_puppetJ_wall()
-- everything happens in everyframe function
Runtime:addEventListener("enterFrame", every_frame)
--add reset event
reset_btn:addEventListener( "tap", tap_reset_level )
--add mainmenu event
main_menu_btn:addEventListener( "tap", tap_main_menu )
end -- scene:enterScene ----------------------------------------------------------------
-- ======================================================================================
-- Called when scene is about to move offscreen:
function scene5:exitScene( event )
local group = self.view
print "scene:exitScene5"
-----------------------------------------------------------------------------
-- INSERT code here (e.g. stop timers, remove listeners, unload sounds, etc.)
end -- exitScene
-- Called prior to the removal of scene's "view" (display group)
function scene5:destroyScene( event )
local group = self.view
Runtime:removeEventListener("enterFrame", every_frame)
puppetJColCount = 0
if (reset_btn) then
print ("destroyScene5 - removing tap_reset_level")
reset_btn:removeEventListener( "tap", tap_reset_level )
reset_btn:removeSelf()
end
reset_btn = nil
if (main_menu_btn) then
main_menu_btn:removeEventListener( "tap", tap_main_menu )
main_menu_btn:removeSelf()
end
main_menu_btn = nil
for ij = 1,ipuppetJtot do
if (puppetJIJ) then
puppetJIJ:removeSelf()
end
puppetJIJ = nil ------
end
if (puppetT) then
puppetT:removeSelf()
end
puppetT = nil
scene5 = nil
end -- destroyScene ------------------------------------------------------------
scene5:addEventListener( "createScene", scene5 )
scene5:addEventListener( "enterScene", scene5 )
scene5:addEventListener( "exitScene", scene5 )
scene5:addEventListener( "destroyScene", scene5 )
---------------------------------------------------------------------------------
return scene5
update:
Hi #DevfaR
Ha, I have restarted from scratch with the corona template and figured out a few things:
1) the exitScene/destroyScene actually does something if the local group is used to group display objects. it removes the display group !
not really obvious as there is only one declaration in it, no code as such
2) the reason why I had so much of removeSelf of objects all over the place is because nothing was working. So I tried pretty much everything under the web.
3) And the reason why it didnt work is because I was creating my display objects into a function. and somehow the display group is not passed there. if I move the code into the createScene function then indeed it is all cleared up when going to the next scene.
problem is .. I really would like to group my puppetCreation code !
e.g.
function scene:createScene( event )
local group = self.view
local physics = require("physics")
physics.start()
background = display.newImage("assets/bckg.png",0,0)
group:insert(background)
createPuppet1(group)
createPuppet2(group)
end
function createPuppet1(group)
puppet1= display.newImage("assets/puppet1.png",0,0)
group:insert(puppet1)
end
function createPuppet2(group)
puppet2= display.newImage("assets/puppet2.png",0,0)
group:insert(puppet2)
end
I passed (group) because the function createPuppet doesnt let me specify
local group = self.view
my email address is edualczatebed#gmail.com
thank you for your help
there's a lot of bug in your code the way you implement it is not good because when you go to a scene and then you switch to another scene your removing all of the object on the destroyScene together with it's listener which is not very efficient i cannot point out what's causing the problem because like i said there is a lot of bug in your code. i think you didn't quite understand how to use a storyboard on Corona. to give you an idea on how will you solve your problem i will implement some code for you to understand that even if you do not remove the object on destroyScene you can remove the object via it's on display groups.
local rectangle
local circle
local function nextScene(event)
storyboard.gotoScene( "scene_2", "fade", "500")
end
-- Called when the scene's view does not exist:
function scene:createScene( event )
local group = self.view
-----------------------------------------------------------------------------
rectangle = display.newRect(100,100,100,100)
rectangle:setFillColor(255,0,0)
rectangle.x = 100
rectangle.y = 100
circle = display.newCircle(100,100,50)
circle.x = 250
circle.y = 100
circle:setFillColor(0,255,0)
--inserting all of your object into display group so that if you destroy the scene the display group will be remove
group:insert(rectangle)
group:insert(circle)
-----------------------------------------------------------------------------
end
-- Called immediately after scene has moved onscreen:
function scene:enterScene( event )
local group = self.view
-----------------------------------------------------------------------------
rectangle:addEventListener("tap", nextScene)
circle:addEventListener("tap", nextScene)
-----------------------------------------------------------------------------
end
-- Called when scene is about to move offscreen:
function scene:exitScene( event )
local group = self.view
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
end
-- Called prior to the removal of scene's "view" (display group)
function scene:destroyScene( event )
local group = self.view
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
end
as you can see i create 2 object the rectangle and circle after i created the objects insert it to group then on enterScene i added a tap listener which will go to the second scene if i tap the object. notice that i didn't bother to remove the object and listener on destroyScene when i go to the scene_2 that is because when i insert the object to the display group whenever i change the scene it will always remove the object. so after moving to the next scene you can either purged the last scene or completely remove it so when you get back to that scene it will recreate the object.
hope this can help you solve your problem

QListWidget Align Items Center

I am adding a list of strings to a QList Widget like this:
myList.addItems( [ 'item1' , 'item2' , 'item3' ] )
By default the list aligns these to the left but I want to get them in the center of the list.
Any Ideas?
If you create a QListWidgetItem() you can call its setTextAlignment() method and pass Qt.AlignHCenter:
item_text_list = [ 'item1' , 'item2' , 'item3' ]
for item_text in item_text_list:
item = QListWidgetItem(item_text)
item.setTextAlignment(Qt.AlignHCenter)
myList.addItem(item)
Docs:
QListWidgetItem, Qt.AlignmentFlag

can't call method "geometry" without a package or object reference

I'm trying to centre a getSaveFile dialog on a selected(by xwininfo) window, I have the position, width and height of the selected window, but need help moving the getSaveFile dialog about (when it's up/showing maybe the key), and so to the centre of the selected window...
vars I have for the selected window are $window_width, $window_height, $abs_x, $abs_y
I believe to position the GetSaveFile dialog right, I would need something like:
$sfile ->geometry("originalWidth"."x"."orighnalHeight+($abs_x+($window_width/2 - originalWidth/2))+($abs_y+($window_height/2 -orighnalHeight/2)");
the above is not so much the problem, but some help there too would be nice,
it is what code to use to plug those numbers into that I'm after...
where and how to use the "$sfile ->geometry(widthxheight+x+y);" type bits, as I'm getting errors with the below:
# save dialog
my $types = [
['All Files', '*', ],
['mpg files', '.mpg', ],
['avi files', '.avi', ],
['mov files', '.mov', ],
];
my $sfile = $mw->getSaveFile(
-defaultextension => ".mov",
-initialdir => "/home/frank/Perl/screencaps", # standardise...
-initialfile => "ScreenCast01",
-title => "ScreenCast Capture file",
-filetypes => $types,
# position/geometry
);
# $sfile ->geometry('100x100+100+100'); # can't call method "geometry" without a package or object reference...
&do_saveFileWithType($sfile) if defined $sfile;
sub do_saveFileWithType {
my #InboundParameters = #_;
print "This is what was passed:\t$InboundParameters[0]\n";
# $sfile ->geometry('100x100+100+100'); # can't call method "geometry" without a package or object reference...
}
I now have this:
# to centre the save dialog(for when it's up):
my $title = "ScreenCast Capture file";
my $x = ($abs_x+($window_width/2)-207); # 207 = SaveDialogWidth/2
my $y = ($abs_y+($window_height/2)-134); # 134 = SaveDialogHeight/2
my $checking4win2move;
$checking4win2move = "on";
my $pid = fork(); # ??
if ($pid == 0){ # ??
while ($checking4win2move eq "on"){
my #runwmctrl = wmctrl ("-l");
for( #runwmctrl ) {
my $linesOf_wmctrl=$_;
chomp ($linesOf_wmctrl); # Get rid of the trailling \n ??
if($linesOf_wmctrl =~ m/ScreenCast Capture file/) {
#print "The \"ScreenCast Capture file\" dialog is mentioned and so is up, I can now move it to the centre of the selected window.\n";
my $windowMove = wmctrl ("-r $title", "-e 0,$x,$y,-1,-1");
# and stop checking:
# $checking4win2move = "off"; # unfork?? # X Error of failed request: BadIDChoice (invalid resource ID chosen for this connection)
exit(); #??
}else{ # print "The dialog is not mentioned in this line of wmctrl\'s output\n";
}
}
sleep .02; # then check again or...
}
}
The getSaveFile method returns a file name (or undef, if cancelled), not a widget reference. I don't see anything its documentation about positioning the window.

Resources