Interesting uses of fluent interfaces? - language-agnostic

I am wondering where and when fluent interfaces are a good idea, so I am looking for examples. So far I have found only 3 useful cases, e.g. Ruby's collections, like
unique_words = File.read("words.txt").downcase.split.sort.uniq.length
and Fest (Java) for unit testing:
assertThat(yoda).isInstanceOf(Jedi.class)
.isEqualTo(foundJedi)
.isNotEqualTo(foundSith);
and JMock. Do you know of any other good examples that use a fluent interface?

jQuery. :)

StringBuilder: http://msdn.microsoft.com/en-us/library/system.text.stringbuilder(VS.71).aspx
Or

RSpec. Example from the home page:
# bowling_spec.rb
require 'bowling'
describe Bowling do
before(:each) do
#bowling = Bowling.new
end
it "should score 0 for gutter game" do
20.times { #bowling.hit(0) }
#bowling.score.should == 0
end
end

Ninject: http://www.ninject.org
For an example that doesn't come from general-purpose libraries, I built an automated regression suite for a configuration wizard. I created a state machine that fills in values on a wizard page, verifies those values are acceptable, then moves on to the next page. The code for each step in the state machine looks like:
step.Filler().Fill().Verify().GoForward();

Related

Accessing regmap RegFields

I am trying to find a clean way to access the regmap that is used with *RegisterNode for creating documentation and testing files. The TLRegisterNode has methods for generating the json through some Annotations. These are done in the regmap method by adding them to the ElaborationArtefacts object. Other protocols don't seem to have these annotations.
Is there anyway to iterate over the "regmap" Register Fields post elaboration or during?
I cannot just access the regmap as it's not really a val/var since it's a method. I can't quite figure out where this information is being stored. I don't really believe it's actually "storing" any information as much as it is simply creating the hardware to attach the specified logic to the RegisterNode based logic.
The JSON output is actually fine for me as I could just write a post processing script to convert JSON to my required formats, but I'm wondering if I can access this information OR if I could add a custom function call at the end. I cannot extend the case class *RegisterNode, but I'm not sure if it's possible to add custom functions to run at the end of the regmap method.
Here is something I threw together quickly:
//in *RegisterRouter.scala
def customregmap(customFunc: (RegField.Map*) => Unit, mapping: RegField.Map*) = {
regmap(mapping:_*)
customFunc(mapping:_*)
}
def regmap(mapping: RegField.Map*) = {
//normal stuff
}
A user could then create a custom function to run and pass it to the regmap or to the RegisterRouter
def myFunc(mapping: RegField.Map*): Unit = {
println("I'm doing my custom function for regmap!")
}
// ...
node.customregmap(myFunc,
0x0 -> coreControlRegFields,
0x4 -> fdControlRegFields,
0x8 -> fdControl2RegFields,
)
This is just a quick example I have. I believe what would be better, if something like this was possible, would be to have a Seq of functions that could be added to the RegisterNode that are ran at the end of the regmap method, similar to how TLRegisterNode currently works. So a user could add an arbitrary number and you still use the regmap call.
Background (not directly part of question):
I have a unified register script that I have built over the years in which I describe the registers for a particular IP. It works very similar to the RegField/node.regmap, except it obviously doesn't know about diplomacy and the like. It will generate the Verilog, but also a variety of files for DV (basic `defines for simple verilog simulations and more complex uvm_reg_block defines also with the ability to describe multiple of the IPs for a subsystem all the way up to an SoC level). It will also print out C Header files for SW and Sphinx reStructuredText for documentation.
Diplomacy actually solves one of the main issues I've been dealing with so I'm obviously trying to push most of my newer designs to Chisel/Diplo.
I ended up solving this by creating my own RegisterNode which is the same as the rocketchip RegisterNodes except that I use a different Elaboration Artifact to grab the info and store it for later.

How do I look inside the NLTK classifier train method

I've been looking at Laurent Luce's' blog on sentiment analysis. Unfortunately I have not been able to follow his blog so I cannot ask him a question directly. Here is the link to the blog: http://www.laurentluce.com/posts/twitter-sentiment-analysis-using-python-and-nltk/
Pretty much everything works nicely. However I cannot figure out how to get this part to work - text below is pasted from the link. My question is how do I look inside the classifier train method? It will help my understanding if I could do that.
"Let’s take a look inside the classifier train method in the source code of the NLTK library. ‘label_probdist’ is the prior probability of each label and ‘feature_probdist’ is the feature/value probability dictionary. Those two probability objects are used to create the classifier."
def train(labeled_featuresets, estimator=ELEProbDist):
...
# Create the P(label) distribution
label_probdist = estimator(label_freqdist)
...
# Create the P(fval|label, fname) distribution
feature_probdist = {}
...
return NaiveBayesClassifier(label_probdist, feature_probdist)
NLTK is open source. You can find the source-code here. Github has solid search functionality, so you should be able to find whatever it is you need using that. Specifically, the naive bayes classifier is here
and you can see the train method for it in that file.

WebSphere Portal 8.5 navigation between portlets with passing parameters

Our project in WebSphere Portal 8.5 have a few portlets (JSR 286).
Portlet A for example contains pages with description of some goods, and tools for the editing this description.
And Portlet B contains tools for create orders for these goods (this is a very simplified, but it should be enough to understand the problem).
We need to create link from one portlet to another with the passing some parameters both in one direction and vice versa. How we can do this?
It would be very useful to see simple code examples for a better understanding
Thank you
Well your most basic approach is to use public render parameters
https://www.ibm.com/support/knowledgecenter/en/SSYJ99_8.5.0/dev-portlet/pltcom_pubrndrprm.html
Set it up in the portlet.xml
<portlet>
...
<supported-public-render-parameter>custID</supported-public-render-parameter>
</portlet>
<public-render-parameter>
<identifier>custID</identifier>
<qname>x:customerID</qname>
</public-render-parameter>
and then you can get it liket his
String customerID = renderRequest.getParameter("custID");
If you need something more complex, you could put items into application scope in the session and share them that way and when the page renders again both have access to it
or you could use the url generation apis but that would be the last thing I would recommend

How do you implement odd business needs?

We provide web services that'll return informations about a product like this (simplified)
<product>
<id>123</id>
<name>Mobil-home</name>
<pricing>
<price>12</price>
<adults>2</adults>
</pricing>
<pricing>
<price>15</price>
<adults>3</adults>
</pricing>
</product>
Our partner says "Our problem is that in our system we can have only 1 adult count per product". This partner is working with a huge system, and they say that it's a big problem and they can't change anything about it in their side.
So what did we decide ? to explode our results like this
<product>
<id>123</id>
<virtualId>123#2</virtualId>
<name>Mobil-home</name>
<pricing>
<price>12</price>
<adults>2</adults>
</pricing>
</product>
<product>
<id>123</id>
<virtulId>123#3</virtualId>
<name>Mobil-home</name>
<pricing>
<price>15</price>
<adults>3</adults>
</pricing>
</product>
So we created a "virtualId" that concatenate the id and the adults with an #. Technically it's a mess, but we do software for a business, the target is not to make clean software, but to make money.
My solutions are :
I try to make a concept out of it : "In some call I have to call a service class that'll explode our results", and then add this functionality to my web service (even if I'm sure we'll use this only in the case of this partner).
I do 3 dirty lines of code with an ugly (if user == "thispartner")
I add a layer between my partner and my web service that'll do the ugly job
I'm stubborn and I say to my boss "We can't work with them, our systems are not compatible", and then I go to the Pole Emploi.
How do you deal in these cases ?
I think the best technical solution will really depend on your implementation, so it isn't really language-agnostic.
For example, if you use a language with full reflection, like Python, my solution would be to add a database field to the partner list named something like TransformationClass. Then, your web service code would look something like:
output = do_normal_processing()
if partner.TransformationClass is not null:
transformation = construct an instance of the partner.TransformationClass class
output = transformation.transform(output)
return output
(Note: for Python, you can construct an instance based on a classname like this.)
You can then create a source code subdirectory 'clientSpecificTransformations' and dropper-client transformations in there; no need to even recompile or restart anything.
However, IMHO for languages that lack the reflection to do such a thing, you'll end up jumping through hoops, and I'd just write a specific proxy for that client and instruct him to use the proxy's URL. The proxy can just make the exact same request to the original service and then explode as required.

Logging API for AS3

quick question, I've been looking for a simple logging tool for AS3 projects (I do not want any Flex dependencies) and my impression so far has been that there is no actively developed project.
What I need is basic logging, and adapters to allow me to send logging to file (using AIR and a LocalConnection maybe) and maybe send to html div etc.
Anyone have any opinions on a simple, light weight project?
We have recently started a project called AS3Commons that contains an early implementation of an AS3 Logging framework. We're aiming to provide a Logging abstraction API that allows you to plug in adapters for other logging frameworks. We also have a built-in logger that logs using trace.
It's usage is similar to other logging frameworks.
private static var logger:ILogger = LoggerFactory.getLogger("com.domain.Class");
Check it at http://code.google.com/p/as3-commons/
Any feedback is appreciated.
This is the best as3 logger by far!!!!
http://arthropod.stopp.se/
There is a standard Logging API in AS3. You can set it up to log to different targets. For instance, if you're using AIR, you could get it to log to a file using the FileTarget in as3corelib.
Setting up:
var logFile:File = File.applicationStorageDirectory.resolvePath("logs/logfile.log");
var logTarget:FileTarget = new FileTarget(logFile);
logTarget.filters = ["path.to.Class"];
logTarget.level = LogEventLevel.ALL;
logTarget.includeDate = true;
logTarget.includeTime = true;
logTarget.includeCategory = true;
logTarget.includeLevel = true;
Log.addTarget(logTarget);
Logging:
var log:ILogger = Log.getLogger("path.to.Class");
log.info("testing the logging...");
I'm always surprised at the number of people who haven't heard of Arthropod. It does everything you described and more. Including password encrypted connections. Arthropod is also set up in a way that it is very easy to make quick edits to the class for your specific needs.
I've got a Flash-friendly logging project going. It's nothing big (yet?) but it's light and handy. It does (optionally) take advantage of Arthropod (a great project) but you can pretty easily shoot the output anywhere you like. It works similarly to the Flex framework so if you are familiar with that then the transition would be painless.
You can read about the project and download the goods here.
MonsterDebugger has more options than it sounds like you're looking for. But it is small and has some very handy features. Including instance inspection, editing properties, calling methods remotely from the air console, and browsing/editing the display tree.
http://monsterdebugger.com/
They made a game so you could learn the debugger, its great.
I found the best solution for me is combining as3commons-logging with Arthropod, like so:
LOGGER_FACTORY.setup = new SimpleTargetSetup(mergeTargets(new TraceTarget(), new ArthropodTarget()));
Then, if you have a client who is having issues but can't tail the flashlog, they can just fire up Arhtropod. Awesome!