How to make a d3 plugin? - plugins

I would like to make a simple d3 plugin but can't find information on how to do it.
It needs to be very simple:
s.append('text').text("Some Text").editable();
should just translate to
s.append('text').text("Some Text").attr('data-editable', true);
How would I do this?

Had to go digging through the source but got it finally.
(function() {
d3.selection.prototype.editable = function() {
return this.attr('data-editable', true);
};
})();
Jsbin here
also note that if you also want the plugin to apply after you .enter() you need to assign the d3.selection.enter.prototype.
If (as in my case) you want your plugin available in both scenarios:
(function() {
d3.selection.prototype.editable = d3.selection.enter.prototype.editable = function() {
        return this.attr('data-editable', true);
      };
})();

Mike Bostock wrote Towards Reusable Charts http://bost.ocks.org/mike/chart/
I followed this pattern to make an extremely simple example d3 plugin, please see this block: http://bl.ocks.org/cpbotha/5073718 (and the source gist: https://gist.github.com/cpbotha/5073718).
According to Mike Bostock, reusable charts should be implemented as "closures with getter-setter methods". I did exactly that in my example above.
The answer of #Wex follows this pattern too, except that it doesn't demonstrate the closure idea, as the original question did not specify requiring any properties.

The way I've seen it documented:
function editable() {
d3.select(this).attr("data-editable", true);
}
Followed by:
s.append('text').text("Some Text").call(editable);
or
d3.selectAll("text").each(editable);
Although I like George's solution better.

Related

Is there any way to route random string to dashboard in Codeigniter 3?

I have a question about Codeigniter: Is there any way to check function exists In the controller file and then route to the function path or else route it to a specific url?
I don't know what kind of Dashboard mean in your question.
I just answer how to check function exist or not in controller and route to that function.
In some case, you may need to add a route rule in config/routes.php.
$route['/programme/(.*)$'] = 'programme/programmes/$2';
Use method_exists() to check if function exist.
class Programme extends CI_Controller {
public function programmes($sub_part = NULL) {
if (!empty($sub_part) and method_exists($this, 'programmes_'. $sub_part)) {
return $this->{'programmes_'. $sub_part}(array_slice(func_get_args(), 1));
}
die('bar')
}
private function programmes_foo() {
die('foo')
}
}
When a visitor go to https://www.foobar.com/programme/foo (foo is something affect which function to call), your website should able to show foo. If the function is not exist, it show bar.
You can use
$route['product/(:any)'] = 'yourcontroller/your_function';
Source : https://codeigniter.com/userguide3/general/routing.html
i think you can change your route into this
$route[‘produk/(:num)/(:any)’] = ‘HomeControl/detail_produk/$1/$2’;
result from that route it's like this
http://www.localhost.com/produk/1/nama-produk-1
or maybe you can read the documentation CI 3 in this link or you can read my reference this link
i hope i can help you, thanks.

SugarCRM: how to use preDisplay function in ViewQuickcreate?

I'm trying to customize the quick create view to add a default value of a field in Sugar Community Edition 6.5.24
Similar code works fine for ViewEdit, but it seems never called in subpanels.
Current file is
custom/modules/Opportunities/views/view.quickcreate.php
Unfortunately the constructor is not invoked.
Any help very appreciated.
<?php
require_once('include/MVC/View/views/view.quickcreate.php');
class OpportunitiesViewQuickcreate extends ViewQuickcreate {
function OpportunitiesViewQuickcreate(){
parent::ViewQuickcreate();
}
function preDisplay() {
parent::preDisplay();
$_REQUEST['custom_field_c'] = "a value for this field";
}
}
After tens of trying, I've found solution.
The right way is to extend SubpanelQuickCreate in the file custom/modules/Opportunities/views/view.subpanelquickcreate
require_once('include/EditView/SubpanelQuickCreate.php');
class OpportunitiesSubpanelQuickcreate extends SubpanelQuickCreate {
function OpportunitiesSubpanelQuickcreate() {
$_REQUEST['custom_field_c'] = "a value for this field";
parent::SubpanelQuickCreate("Opportunities");
}
}
Going from memory, so I may be wrong, but try adding $this->useForSubpanel = true; in your constructor.

Is there a way to add macro definition to MonoDevelop?

I need a special keyword in my code to be replaced by a consequence of symbols before the build.
For example, I want hello to be replaced by Debug.Log("Hello");
According to this, MonoDevelop didn't have this feature in 2006. Has anything changed?
If no, are there any plugins/external tools implementing it?
I don't think that switching to another IDE will be helpful unless it can use code completion for unity3d.
Please, don't answer that macro definitions are evil.
Update:
I understood that my example was too abstract. In fact, I want to replace read("name"); with
var name;
name=gameObject.Find("name");
if(!name)
return;
name=name.param;
1)Every script should have all needed variables declared + a variable called "self".
2)They should be public.
3)
public static function set_var(target,name:String,value)
{
var fi=typeof(target).GetField(name);
fi.SetValue(target,value);
}
public static function read(name:String,target):String
{
set_var(target,"self",target);
return "var rtmp=self.gameObject.GetComponent(\""+name+"\");"+"if(!rtmp)return;"+name+"=rtmp.param;";
}
4)eval(read("name",this));
5)As far as I know, it wouldn't work in unity C#
6)Probably, set_var can be replaced by assignment
Far better solution:
var component_names = ["hello","thing","foo"];
var component;
for(var name:String in component_names)
{
component = gameObject.GetComponent(name);
if(!component)
return;
set_var(this,name,component.param);
}
(Requires set_var() from the first one)

Can I divide my tests into separate specs and then call them from another or is it better to use helper functions?

Just got started with Protractor for E2E testing and I am having a bit of trouble with the test case structure.
Not sure if can I divide my tests into separate specs and then call them from another or how can I make nice helper functions to handle this.
I am finding elements by a repeater and then I would like to make tests for each of the operation for each of the element in the repeater. Sort of like this:
describe('tasty', function () {
'use strict';
var ptor;
beforeEach(function () {
ptor = protractor.getInstance();
ptor.get('http://localhost:8000/');
});
it('Should sample three tasty fruits of every kind on my shopping list.', function () {
ptor.findElement(protractor.By.className('fruitstore')).click();
var fruitshelves = ptor.findElements(protractor.By.repeater('fruit in fruits').column('header'));
fruitshelves.then(function(arr) {
for (var i=0;i<arr.length; i++) {
// Pick up three fruits of this kind from the shelf and put in shopping cart
// Should be listed on my shopping list
// Open the wallet
// Should have money
// Pay for the fruits and put it in your shopping bag
// Should be able to complete the transaction
// For each one of the fruits in your shopping bag
// Take a bite
// Should be tasty
}
});
});
});
Based on the #langliman answer, I've managed to achieve the desired behaviour.
Note login.spec.js and Login.page.js should be located in the same folder.
Login.page.js file:
var LoginPage = function (ptor) {
//following PageObject pattern define the functions here.
}
module.exports.getLoginPage = function (ptor) {
return new LoginPage(ptor);
};
login.spec.js file:
(function () {
'use strict';
describe('login page', function () {
var ptor = protractor.getInstance();
var loginPageBuilder = require('./Login.page.js');
var loginPage = loginPageBuilder.getLoginPage(ptor);
it('should login as admin', function () {
loginPage.visit();
loginPage.enterUsername('user');
loginPage.enterPassword('password');
loginPage.login();
});
});
}());
I came to this question looking for a way to have helper functions shared between spec files in Protractor. In case others are looking for the same, turns out since Protractor is just running in Node, all you need to do is var helpers = require('./your-helper-file').
In case you want shared setup and before/after functions as well as helper methods, one solution is to require the tests from your spec helper instead of requiring your spec helper from the tests.
conf.js
exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub',
specs: ['e2e/spec.js']
}
e2e/spec.js
var chai = require('chai'),
homepage = require('./homepage.js'),
signin = require('./signin.js');
chai.should()
browser.baseUrl = 'http://localhost:3000'
homepage.test()
signin.test()
e2e/homepage.js
exports.test = function() {
describe('homepage', function() {
it('should have the right title', function() {
browser.get('/')
browser.getTitle().then(function(title){
title.should.eq('Home')
})
});
});
}
e2e/signin.js
exports.test = function() {
describe('signin', function() {
it('should have the right title', function() {
browser.get('/signin')
browser.getTitle().then(function(title){
title.should.eq('Sign in')
})
});
});
}
I'm looking at the same thing myself, and to some extent I had hoped that you would have an answer for me on this question. :-)
Having said that, it appears that protractor is new enough that nobody really knows the answer, and I guess that makes my answer as good as the next persons.
Firstly, I'm using the page object notation that is described on the protractor getting started page, towards the bottom: https://github.com/angular/protractor/blob/master/docs/getting-started.md
This gives an element of modularity, my view here is that I end up with a set of classes, one per page, that abstract away some of the detail. So, for example, I might have a "foo" class, which includes in it abstractions like "foo.get" and "foo.validate(id, name, otherData)". This would be a way to pull out repeated code.
The bit that I haven't worked out is how to create a library of modules and then assemble those into a single set of scenarios. I have a few thoughts though:
The underlying problem is the ability to include javascript files in each other - which really doesn't exist as a capability. There are third party libraries, which I'd prefer not to use, and I haven't seen a way to use Angular's module capability to do this.
End 2 end testing can be very dependent on the order of the tests. So one test may create data, another test may then use that data. As an example, if you want a test that logs people on, you may need a test that registers people first. You probably don't want to put registration on the front of every test that you run. As such, you probably need a lot of control over the order of your test scenarios anyway
As such, one option is to just put everything in one really big file. Which goes against everything we all learned in school, but I haven't really come up with a reason that wouldn't work. Then you can write functions and abstractions to your hearts content.
If you follow that to the next stage, another option is to write a series of javascript files with strict naming conventions, then use grunt to concatenate them for you before executing them. So, for example:
A set of files named xxxx.page.scenario.js, which contain the "page object" definitions - basically helper methods for each page
A set of files named xxxx.functions.scenario.js, which contain common components of your scenarios - so maybe you have a register and logon set of actions, and you make that into a library function
A set of files named nnxx.scenarios.scenario.js, which contain the actual scripts themselves. These are numbered at the start (the nn), so we can concatenate them in a reliable sequence and thereby control which order our scripts run
I'm not yet saying this is a good idea, just that it at least superficially looks like it could work, and would give the desired result. My main concern is that it feels fragile - so as the test suite grows in size it would perhaps become very difficult to maintain. Perhaps another way to do this would be, instead of numbering the scenarios, to instead define them as dependencies, and have something that makes sure that any given script runs after any script it declares itself to be dependent on. That would maybe allow for subsetting of the scripts as well - so you could say "run the bar script" and the framework would know that the bar script needs the foo script run first, and maybe the login script. But it's OK to leave all the other scripts out.
EDIT: I see astrolabe as potentially a good answer here, it looks like it explicitly allows you to modularise your tests. https://github.com/stuplum/astrolabe. I've just completed a proof of concept with it, and it seems to do everything I might hope. The code for it ends up something like:
clubs.part.scenario.js:
/**
* Partial for the page objects associated with clubs
*/
var Page = require('astrolabe').Page;
module.exports = Page.create({
url: { value: 'UI/index.html#clubs' },
title: { get: function() { return this.findElement(this.by.id('title')); } },
description: { get: function() { return this.findElement(this.by.id('description')); } },
clubTableElement: { value: function(rowNum, columnBinding) {
return this.findElement(this.by.repeater('club in clubs').row(rowNum).column(columnBinding)); } }
}
);
clubs.scenario.js:
/**
* End to end tests for the club functionality
*/
var homePage = require('../home/home.part.scenario.js');
var clubsPage = require('./clubs.part.scenario.js');
describe( 'Navigate to club list page', function() {
it ( 'should allow navigation to the club list page', function() {
homePage.go();
expect(homePage.clubsLink.getText()).toEqual('Clubs');
homePage.clubsLink.click();
expect(clubsPage.title.getText()).toEqual('Club functions');
expect(clubsPage.description.getText()).toEqual('Soon this will show a list of all the clubs, based on information from the server');
expect(clubsPage.clubTableElement(0, 'name').getText()).toEqual('First club');
expect(clubsPage.clubTableElement(0, 'contact_officer').getText()).toEqual('A Person');
expect(clubsPage.clubTableElement(1, 'name').getText()).toEqual('Second club');
expect(clubsPage.clubTableElement(1, 'contact_officer').getText()).toEqual('J Jones');
});
it ( 'should allow us to go directly to the club list page', function() {
clubsPage.go();
expect(clubsPage.title.getText()).toEqual('Club functions');
expect(clubsPage.description.getText()).toEqual('Soon this will show a list of all the clubs, based on information from the server');
expect(clubsPage.clubTableElement(0, 'name').getText()).toEqual('First club');
expect(clubsPage.clubTableElement(0, 'contact_officer').getText()).toEqual('A Person');
expect(clubsPage.clubTableElement(1, 'name').getText()).toEqual('Second club');
expect(clubsPage.clubTableElement(1, 'contact_officer').getText()).toEqual('J Jones');
});
});
I'm pretty happy with this structure, it doesn't do everything but it does most things. The sample code I've provided is from the tutorial that I've been working on for a while with angularjs, which I'm updating for e2e testing and Rails 4 at the moment, if you want the context that goes with that: http://technpol.wordpress.com/2013/11/16/5-end-to-end-testing/

Coffeescript and markup based JS execution

From another thread here I found this great tutorial on markup based JS execution
Garber-Irish solution:
http://www.viget.com/inspire/extending-paul-irishs-comprehensive-dom-ready-execution/.
I'm checking out how I can do parts of this in Coffeescript.
This works OK:
SITENAME.surveys.show = ->
alert "Hello CoffeeScript"
Which renders out:
SITENAME.surveys.show = function() {
return alert("Hello CoffeeScript");
};
This one is not so happy:
SITENAME.surveys.new = ->
alert "Hello CoffeeScript"
SITENAME.surveys["new"] = function() {
return alert("Hello CoffeeScript");
};
I'm new to Coffeescript and doing a codeschool.com course on it now.
I guess the "new" keyword is special for coffeescript.
Is there any workaround for this?
Thanks!
new is special in JavaScript and CoffeeScript is aware of this so it's emitting code that will actually work even though it's bad practice to name methods using reserved keywords.
If you need to use new, you can use [] to define the function:
SITENAME.surveys['new'] = ->
alert "Hello CoffeeScript"
and to call it:
SITENAME.surveys['new']()
Demo: http://jsfiddle.net/ambiguous/Y3qnt/
A quick review of your link suggests that you'll be accessing the function with something like:
controller = 'surveys'
action = 'new'
SITENAME[controller][action]()
So it doesn't matter what the methods are called as you'll always be referring to them by their (string) name anyway.