Using Type-safe URLs with setMessage? (shamlet versus hamlet) - yesod

How do I use a type-safe url with setMessage?
I want to change
...
setMessage [shamlet|<span .warning>Warning! See Help.|]
...
to a message that contains a link.
From what I could gather thus far, it ought to work somehow like this
...
renderer <- getUrlRender
let html = [hamlet|<span .warning>Warning! See #
<a href=#{HelpR}> Help!|]
setMessage $ toHtml $ html renderer
...
but that code just gives me confusing error messages all over the file.
I did read the printed Yesod Book Chapter on Shakespearian Templates, but I found that it is not very explicit on the involved types. For instance what type does [hamlet|...|]| produce? Without URL-Interpolation, ghci reports t -> Markup but with URL-Interpolation inside, I just get errors.
I am further confused by all the type synonyms involved, e.g. [shamlet|...|] delivers something of type Html, while setMessage expects a Html (). I do not know how to look these up easily: Hoogle often finds nothing on the topic, while Google always finds possibly outdated versions (with examples that no longer work) - sure I get to the newest version eventually, but is there a place where I get an easy overview over these? (Can ghci list all synonyms for a type?)
Note that I actually want to produce the message in a purely functional code fragment, which is later on used by a handler. So that is why I would like to separate the URL rendering from where the hamlet is specified. Thanks for any pointer in the right direction!

I think you want to use getUrlRenderParams. Strangely enough, a related discussion came up on IRC today. Hamlet templates take a URL rendering function as their first argument, and that function must take two parameters: a type-safe URL, and a list of query string parameters. getUrlRender returns a function that doesn't take the query string parameters, which is why you need getUrlRenderParams instead.

Related

Dialogflow: Respond based on values and other conditional responses

I have $dinetype variable obtained from the user.
But I would like to give response based on what value has been set in $dinetype variable. In addition to giving responses, I also need to set relevant context. How do I do this in DialogFlow?
if($Dinetype=='dineout')
ask ('which restaurant would you like to go to?')
set_context ('awaiting-restaurant')
if($Dinetype=='takeaway')
ask ('When would you like to take away?')
set_context ('awaiting-takeaway-time')
Is it programmable at all? Or is it possible to achieve something equivalent to the above in the UI?
Edit: A much easier way has been added to handle this issue directly in Dialogflow
(Updated Solution) Follow-up Intents:
After creating an intent, you can add follow-up intents now.
Intents -> Create Intent >
[Response=Prompt For Conditional Response]
Intents -> Add Follow-up Intent -> Custom/Yes/No
Then set the training praise to a matching entity you want to conditionally respond to
  
 
OLD HACKY SOLUTION:
Late reply, but maybe someone will find this useful.
If the conditional response only needs to reference a single parameter
value, then I figured out what you can do is utilize the Entity's
"Reference Value" as the response you want to give for a particular
set of Synonyms.
So you'd have an entity that looked like this:
Then, setup your intent like this, with a response of $Dinetype:
Then the end result will look like this:
And you can make whatever follow-up intent you need from there.
Down-side is Dinetype won't be as reusable. But I still think it
beats writing a fulfillment webhook every time you need a simple
conditional response.
You can't do this in the Response section directly. The Response section is meant for fairly simple responses that don't require significant logic to process. Although you can use parameters in the response, you can't give a different response based on the value of the parameter. So you can set a response to something like
I think $Dinetype is great food.
but not
{{#if $Dinetype == "Thai"}}I think Thai food is too hot{{/if}}
or anything like that
However, you can add code that sends conditional responses and contexts by implementing a Fulfillment webhook. Although you can't do this for each Intent as part of the Intent editor screen, the Fulfillment screen includes a built-in code editor.
I found a solution to my similar problem using composite entities, which may or may not be overkill for your agent. The value assigned to a parameter associated with the (composite) entity will contain a JSON structure, if a synonym in that entity was matched.
Using the "Dot" notation, you can assign the matched sub-entity's property (similar to the reference value of a normal entity) to another parameter in the Actions and Parameters section. You can have one parameter for each sub-entity and hence, you can evaluate these parameters in your response section to select each response variants:
$Parameter_A ResponseA
$Parameter_B ResonseB
....
etc.
Clunky but works. Just have to be careful to reference the property exactly as it is defined in the composite entity.

How does one bypass SyntaxError when parsing code?

I am using openpyxl to read an excel file that will have changing values over time. The following function will take string inputs from the excel sheets to make frames for Tkinter.
def make_new_frame(strng, frame_location, frame_name, frame_list):
if not(frame_name in frame_list):
frame_list.append(frame_name)
exec("global %s" %(frame_name)) in globals()
exec("%s = Frame(%s)"%(frame_name, frame_location))
.... etc.
The code itself is quite long but I think this is enough of a snapshot to address my problem.
Now this results in the following error while parsing:
SyntaxError: function 'make_new_frame' uses import * and bare exec, which are illegal because it is a nested function
Everything in the code I included parsed and executed just fine several times, but after I added a few more lines in later versions in this function, it keeps spitting out the above error before executing the code. The error references the third line in the function, (which, I repeat, has been cleared in the past).
I added "in globals()" as recommended in another SO post, so that solution is not working.
There is a solution online here that uses setattr, which I have no idea how to use to create a widget without eventually using exec.
I would really appreciate if someone could tell me how to bypass the error while parsing or provide an alternative means for a dynamically changing set of frame names.
Quick Note:
I am aware that setting a variable as global in python is generally warned against, but I am quite certain that it will serve useful for my code
Edit 1: I have no idea why this was downvoted. If I have done something incorrectly, please let me know what it is so I can avoid doing so in the future.
I think this is an X/Y problem. You are asking for help with solution Y instead of asking for help on problem X.
If your goal is to create an unknown number of Frame objects based on external data, you can store references to the frame in a list or dictionary without having to resort to using exec and dynamically created variable names.
exec is a perfectly fine function, but is one of those things that you should never use until you fully understand why you should never use it.
Here's how to solve your actual problem without using exec:
frames = {}
def make_new_frame(strng, frame_location, frame_name, frames):
if not(frame_name in frames):
frames[frame_name] = Frame(frame_location)
return frames[frame_name]
With that, you now have a dictionary (frames) that includes a reference for every new frame by name. If you had a frame named "foo", for example, you could configure and pack it like this:
frames["foo"].configure(background="red", ...)
frames["foo"].pack(...)
If preserving the order of the frames is important you can use an OrderedDict.

cppcms url dispather with over 4 parameter

I started using cppcms to make a simple website + "service" that gets its input from the path like:
/maindb/2012/11/2/finalists/....
now i noticed that the nice url handling has only a regex dispatcher up to 4 parameters that will be given to the called function and a function without regex gets nothing at all not even the path.
Now what is the most feasible way to realize more than 4 parameters / subfolders.
Do I have to write my own url handling and if so where do i get the url from?
Is the url class public enough to iherit it and just extend it easiely for longer functions?
Or is there some other way how I am supposed to do it? (because 4 parameters seems kinda very less)
Two points:
If you have subfolders you are probably looking for organizing your URLs into hierarchy. See
http://cppcms.com/wikipp/en/page/cppcms_1x_tut_hierarchy
If you need more then 4 parameters you should:
Check if you really organize your application right (see above)
Combine several cases into single regex and split them afterwards in a parameters
For example (/\d\d\d\d/\d\d/\d\d)/(\w+) where the first would mach the data and not separatly year, month day.
P.S.: Url dispatcher is not designed to be derived from.

Scala / Lift - Trying to understand Lift's simultaneous claim to use valid html and propensity for lift: tags and tag rewriting in render

All of the Seven Things (http://seventhings.liftweb.net/) are certainly nice, but I was particularly enthusiastic about the claim in Templates (http://seventhings.liftweb.net/templates) that "Lift supports designer friendly templates."
As one of my steps in learning Lift's way of doing things I'm attempting to create a simple object creation form: take a few parameters, use them as constructor arguments, then stow the object away. After some research and experimentation, tho, I have two concerns:
There seems to be a considerable propensity for significantly rewriting/embellishing the template markup in snippets.
Forms don't seem to use valid or recognizable html elements.
What I'm basing this on:
The form examples/documentation seems all about special lift: tags. Exploring Lift suggests that a form should look like this: (http://exploring.liftweb.net/master/index-6.html)
<lift:Ledger.add form="POST">
<entry:description />
<entry:amount /><br />
<entry:submit />
</lift:Ledger.add>
I'm not sure that's even valid html5 and while it might be valid xhtml, it doesn't feel like that meets the spirit of having your templates look like real html for our designer friends. I read somewhere else (can't find it again) that we did have the option of using actual input tags, but then we wouldn't get some parts of Lift's fancy form wire-up or somesuch, the passage wasn't very clear on what exactly I'd be missing out and the examples don't seem interested in my writing a plain html form making a plain html post.
The code for a demo.liftweb.net example (1) suggests that your template should look like this (2)
<lift:surround with="default" at="content">
<div class="lift:PersonScreen"></div>
</lift:surround>
The code for PersonScreen snippet isn't exactly illuminating, either (3). There are several other examples of a template that has, e.g. only a ul tag in a particular location only to generate a whole series of complex li's with nested elements in the snippet. Sure, you can use xml in Scala and it reads tolerably, but it's still scattering your markup everywhere. This seems to violate the spirit of "designer friendly templates".
What I want to understand.
For a long time I've strictly followed two rules in my webapp development:
No markup in 'code' (controllers, business models).
No business logic in the templates whatsoever.
Idiomatic Lift seems to completely forego the first rule and completely miss the value of the second rule. These rules have served me well and I'm not ready to just follow along with the examples that seem to be violating them without understanding why its not going to create a mess. I want to understand why it's okay in Lift to have so much display code generated in the Snippets. I also want to understand why its okay that the markup in the templates so rarely reflects the output.
What I (think I) want:
I want all of my markup with very few, if any, exceptions to be in my templates. I want my snippets to do minimal template mangling, generally only replacing element text on "leaf" tags and possibly tweaking attribute values. I think I've done this for a reasonably complex display example and I suspect I could use the same technique to generate a vanilla html form and then handle the params myself. Is that what I need to do if I want my template to look like the end-result form?
Responses and any other thoughts, especially on understand the Lift mindset regarding this stuff, would be tremendously appreciated.
Thanks!
http://demo.liftweb.net/simple_screen?F674431078927QJVVYD=_
https://github.com/lift/examples/blob/master/combo/example/src/main/webapp/simple_screen.html
https://github.com/lift/examples/blob/master/combo/example/src/main/scala/net/liftweb/example/snippet/Wizard.scala#L94
EDIT
In response to #OXMO456. (Thanks for the response.)
I have, and they seem to just confirm my concerns: E.g. we start with:
Lift templates contain no executable code. They are pure, raw, valid HTML.
which is awesome. Then later:
The latter two mechanisms for invoking snippets will not result in valid Html5 templates.
and yet everyone seems to use the first of those two mechanisms. Also, it says:
Third, the designers don’t have to worry about learning to program anything in order to design HTML pages because the program execution is abstracted away from the HTML rather than embedded in the HTML.
But pretty consistently the example snippets like the one I referenced in the OP generate markup entirely programmatically. This seems counter to the goals (a) of having designer friendly templates so the designers don't have to be bothered with Freemarker markup and (b) separating display logic from business logic.
The second link is helpful and instructive, but it makes it pretty clear that this isn't The Lift Way. However, The Lift Way also seems to drag a whole load of markup generation into snippets, which is (I think) a huge compounding of markup and business logic. Is that The Lift Way?
Those are old-style tags, not designer-friendly tags.
<lift:MySnippet>
<b:field />
</lift:MySnippet>
becomes
<div class="lift:MySnippet">
<div class="field"></div>
</div>
Old-style Lift templates are valid XML, not XHTML - so you can't have unclosed tags or anything - this differentiates Lift from most frameworks, which treat templates as raw strings with bits of code intertwined throughout, without regard to tags or structure.
BTW, in old-style tags, those fields are all fabricated - they aren't part of some standard set of Lift tags. I could just as easily do:
<lift:MySnippet>
<frobnicate:blorb />
</lift:MySnippet>
as long as my snippet code is looking for that specific tag.
Lift doesn't allow any logic in your templates. All of the logic happens in your Snippet class. So for the designer-friendly example above, I might have a snippet class like this:
class MySnippet {
def render(in: NodeSeq): NodeSeq = ".field" #> Text("some text here")
}
which would yield this result:
<div>
<div class="field">some text here</div>
</div>
It's impossible to put any logic in Lift templates - all they can do is invoke Lift snippets, which are regular Scala classes where all of the work happens.
Lift discards the rule that you shouldn't have any display logic in your real code. Why? Because it makes for more reusable code, because Scala has powerful XML support baked into the language and because all of your logic is now treated as plain old Scala code.
If I define a Lift snippet called CurrentTime, I can simply drop that in to any template and it will display the current time - with old-school MVC frameworks, each action method needs to set the time as a page variable and then my templates would need to be modified to print it out. For more complicated logic, old-school frameworks would probably require a conditional in the templates. Lift doesn't allow that - all of your logic is regular Scala code, eligible for refactoring, easily testable, and compatible with modern IDE's.
In answer to you're "what I think I want" question, sure you can do that no problem. Lift is really all about choices, and understanding your use case. Often the samples you see with Lift intermingle code and markup, which is of course sub-optiomal. The important thing to note is that snippets conceptually are solely designed to produce markup, and render the view.
In addition, as Lift follows its view first paradigm the only thing that the view actually requires is a notation to outline which sections of markup you want to process in which rendering snippets. There are several ways, as illustrate by both the OP and "Bill", but personally I prefer:
<div lift="YourSnippet.method">
<p>Some other code</p>
</div>
This is preferable because you're then not culturing up the class attribute which (IMO) can be confusing for designers. Lift can be very designer friendly, but I think the main problem here is that you have to be both disciplined when writing your snippets whilst ignoring many of the samples available today which mix Scala and markup.
You may also be interested in this post ( http://blog.getintheloop.eu/2011/04/11/using-type-classes-for-lift-snippet-binding/ ); using this sort of pattern you can define decoupled, reusable parts of rendering logic whilst keeping your business logic safely out of the snippets.
Finally, and without wanting to shamelessly promote my own product, but I specifically went out of my way to not use any mixed Scala xml literals in my example code for Lift in Action (other than to illustrate that its possible), so perhaps it might be of assistance if you're looking at Lift ( http://manning.com/perrett/ )

Regex to change method call parameter

Regexs make me cry, so, I came here for help.
I'm looking for some tips on Find & Replace in Panic's Coda. I know the F&R
is pretty advance but I'm just looking for the best way to do this.
I'm trying to rewrite a 'template engine' (very basic) I have going on with a
webapp I'm coding in PHP (CodeIgniter).
Currently I'm calling my template like so:
$this->load->view('subviews/template/headerview');
$this->load->view('subviews/template/menuview');
$this->load->view('subviews/template/sidebar');
$this->load->view('The-View-I-Want-To-Load'); // This is the important line
$this->load->view('subviews/template/footerview');
However it's inefficient using five lines of code every time I want to
load up a different page, in every different controller. So I rewrote it like this:
$data['view'] = 'The-View-I-Want-To-Load';
$this->load->view('template',$data);
That way if I need to make any major changes to the design it can
easily be done from the template.php view file (which contains the header, menu, sidebar views etc. etc.).
However I use the previous 5-lines all over the place in many
different controllers and functions. So, my question is --- How can I
find and replace the old template engine (5 lines of code) for the new
one - substituting in the name of the view in the important, unique
line for the one in $data['view]?
Does that make any sense?! If not I'll try and rephrase! I mean, is there a way of doing this via a Regex or something? Or am I on completely the wrong lines here?
your regex will look something like this :
\$this->load->view\('subviews/template/headerview'\);\n\$this->load->view\('subviews/template/menuview'\);\n\$this->load->view\('subviews/template/sidebar'\);\n\$this->load->view\('([^']*)'\);\n\$this->load->view\('subviews/template/footerview'\);
and replace with
\$data['view'] = '$1';\n\$this->load->view('template',\$data);