repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
kirilpopov/callback-registry
tests/index.js
13090
var expect = require('chai').expect; nocache = function (module) { delete require.cache[require.resolve(module)]; return require(module); }; var Registry = nocache('../lib/index.js'); console.log(Registry) describe('callback-registry', function (done) { it('should execute single callback', function (done) { var registry = Registry(); registry.add('test', done); registry.execute('test'); }); it('should execute multiple callbacks', function (done) { var registry = Registry(); var invoked = 0; var p = function () { invoked++; if (invoked == 3) { done(); } }; registry.add('test', p); registry.add('test', p); registry.add('test', p); registry.execute('test'); }); it('should not execute callbacks on different keys', function (done) { var registry = Registry(); var invoked = 0; var p1 = function () { invoked++; if (invoked == 2) { done(); } }; var p2 = function () { done('should not be invoked'); } registry.add('test1', p1); registry.add('test2', p2); registry.execute('test1'); registry.execute('test1'); }); it('should be able to remove callback', function (done) { var registry = Registry(); var removeCallback = registry.add('test', function () { console.log('!!! ERROR'); done('should not be executed'); }); removeCallback('test'); registry.execute('test'); done(); }); it('should pass arguments', function (done) { var registry = Registry(); registry.add('test', function (a, b, c) { console.log(arguments); if (a === 1 && b === '2' && c === 3) { done(); } else { done('error - arguments not matching'); } }); registry.execute('test', 1, '2', 3); }); it('should return arguments', function () { var registry = Registry(); registry.add('test', function () { return { a: 1 }; }); registry.add('test', function () { return { a: 2 }; }); var result = registry.execute('test'); expect(result[0]).to.be.an('object'); expect(result[0].a).to.equal(1); expect(result[1]).to.be.an('object'); expect(result[1].a).to.equal(2); }); it('should return results from the callbacks in array', function () { var registry = Registry(); registry.add('test', function () { return { a: 1 }; }); var unsubscribe2 = registry.add('test', function () { unsubscribe2(); return { a: 2 }; }); var result = registry.execute('test'); expect(result.length).to.equal(2); result = registry.execute('test'); expect(result.length).to.equal(1); }); it('should return empty array if no subscribers', function () { var registry = Registry(); var result = registry.execute('test'); expect(Array.isArray(result)).to.equal(true); expect(result.length).to.equal(0); }); it('should return results from the callbacks even if some of the callbacks throw Error', function () { var registry = Registry(); registry.add('test', function () { throw Error('test'); }); registry.add('test', function () { return 1; }); var result = registry.execute('test'); expect(Array.isArray(result)).to.equal(true); expect(result.length).to.equal(2); expect(result[0]).to.equal(undefined); expect(result[1]).to.equal(1); }); it('bugfix (https://github.com/gdavidkov) - issue when unsubscribing with more than one callbacks per key', function () { var registry = Registry(); var executions1 = 0; var executions2 = 0; var unsubscribe1 = registry.add('test', function () { unsubscribe1(); executions1++; }); var unsubscribe2 = registry.add('test', function () { unsubscribe2(); executions2++; }); registry.execute('test'); registry.execute('test'); registry.execute('test'); expect(executions1).to.equal(1); expect(executions2).to.equal(1); }); it('should remove all callbacks on clear', function () { var registry = Registry(); registry.add('test', function () { throw Error('test'); }); registry.add('test', function () { throw Error('test'); }); registry.clear(); var result = registry.execute('test'); }); it('after clear I can call remove and it should not fail', function () { var registry = Registry(); var remove1 = registry.add('test', function () { throw Error('test'); }); var remove2 = registry.add('test', function () { throw Error('test'); }); registry.clear(); var result = registry.execute('test'); remove1(); remove2(); }); it('should remove all callbacks for key on clearKey', function (done) { var flag = null; var registry = Registry(); registry.add('test', function () { done('should not have called this') }); registry.add('testOtherKey', function () { flag = 'pass' }); registry.clearKey('test'); registry.execute('test'); registry.execute('testOtherKey'); expect(flag).to.equal('pass'); done(); }); it('should not fail if execute key after clearKey', function (done) { var registry = Registry(); registry.add('test', function () { done('should not have called this') }); registry.clearKey('test'); registry.execute('test'); done(); }); it('should execute one callback after clearKey and adding a new callback', function (done) { var flag = null; var registry = Registry(); registry.add('test', function () { done('should not have called this') }); registry.clearKey('test'); registry.add('test', function () { flag = 'pass' }); registry.execute('test'); expect(flag).to.equal('pass'); done(); }); it('should clearKey for key that was never added', function (done) { var registry = Registry(); registry.clearKey('test'); done(); }); it('should log errors in console with default options', function (done) { var registry = Registry(); var remove1 = registry.add('test', function () { throw Error('test-error'); }); var oldConError = console.error; console.error = function wrappedError(...msg) { oldConError.apply(oldConError, msg); console.error = oldConError; expect(msg[0]).to.include('test-error'); done(); } var result = registry.execute('test'); remove1(); }); it('should log errors in console with log option set', function (done) { var registry = Registry({ errorHandling: "log" }); var remove1 = registry.add('test', function () { throw Error('test-error'); }); var oldConError = console.error; console.error = function wrappedError(...msg) { oldConError.apply(oldConError, msg); console.error = oldConError; expect(msg[0]).to.include('test-error'); done(); } var result = registry.execute('test'); remove1(); }); it('should silence errors with silent set', function (done) { var registry = Registry({ errorHandling: "silent" }); var remove1 = registry.add('test', function () { throw Error('test-error'); }); var oldConError = console.error; console.error = function wrappedError(...msg) { oldConError.apply(oldConError, msg); console.error = oldConError; expect(msg[0]).to.include('test-error'); done("should not be logging"); } var result = registry.execute('test'); remove1(); done(); }); it('should explode with throw set', function (done) { var registry = Registry({ errorHandling: "throw" }); var remove1 = registry.add('test', function () { throw Error('test-error'); }); var oldConError = console.error; console.error = function wrappedError(...msg) { oldConError.apply(oldConError, msg); console.error = oldConError; expect(msg[0]).to.include('test-error'); done("Should not be logging!"); } try { var result = registry.execute('test'); done("should have exploded"); } catch (error) { remove1(); done(); } }); it('should use custom handler when it is set', function (done) { var witness = ""; var registry = Registry({ errorHandling: function handleErr() { witness = "handled" } }); var remove1 = registry.add('test', function () { throw Error('test-error'); }); var oldConError = console.error; console.error = function wrappedError(...msg) { oldConError.apply(oldConError, msg); console.error = oldConError; expect(msg[0]).to.include('test-error'); done("Should not be logging!"); } try { var result = registry.execute('test'); expect(witness).to.equal("handled"); done(); remove1(); } catch (error) { done("should not have exploded"); } }); it('should explode when custom handler is set and explodes', function (done) { var registry = Registry({ errorHandling: function handleErr(err) { expect(err instanceof Error).to.be.true; throw new Error(`handler-error : ${err}`); } }); var remove1 = registry.add('test', function () { throw Error('test-error'); }); var oldConError = console.error; console.error = function wrappedError(...msg) { oldConError.apply(oldConError, msg); console.error = oldConError; expect(msg[0]).to.include('test-error'); done("Should not be logging!"); } try { var result = registry.execute('test'); done("should have exploded"); } catch (error) { expect(error.toString()).contains('test-error'); expect(error.toString()).contains('handler-error'); remove1(); done(); } }); it('should invoke the callback provided to add with the replayArguments (single argument)', function (done) { const replayArgumentsArr = ['Alice', 'Bob']; const invokedWith = []; const registry = Registry(); const callback = (name) => { invokedWith.push(name); if (invokedWith.length === replayArgumentsArr.length && invokedWith.every((arg) => replayArgumentsArr.includes(arg))) { done(); } }; registry.add('test', callback, replayArgumentsArr); }); it('should invoke the callback provided to add with the replayArguments (multiple arguments)', function (done) { const replayArgumentsArr = [['Alice', 25], ['Bob', 30]]; const invokedWith = []; const registry = Registry(); const callback = (name, age) => { invokedWith.push([name, age]); if (invokedWith.length === replayArgumentsArr.length && invokedWith.every((args) => replayArgumentsArr.some((replayArgs) => replayArgs.every((arg, index) => arg === args[index])))) { done(); } }; registry.add('test', callback, replayArgumentsArr); }); it('should not invoke the callback provided to add with the replayArguments after unsubscribing', function (done) { const replayArgumentsArr = [['Alice', 25], ['Bob', 30]]; const invokedWith = []; const registry = Registry(); let unsub; setTimeout(() => { if (invokedWith.length === 1 && replayArgumentsArr[0].every((arg, index) => arg === invokedWith[0][index])) { done(); } }, 1500); const callback = (name, age) => { invokedWith.push([name, age]); unsub(); }; unsub = registry.add('test', callback, replayArgumentsArr); }); });
mit
LoamStudios/sustainability-summit
app/dashboards/sponsorship_dashboard.rb
1439
require "administrate/base_dashboard" class SponsorshipDashboard < Administrate::BaseDashboard # ATTRIBUTE_TYPES # a hash that describes the type of each of the model's fields. # # Each different type represents an Administrate::Field object, # which determines how the attribute is displayed # on pages throughout the dashboard. ATTRIBUTE_TYPES = { event: Field::BelongsTo, sponsors: Field::HasMany, id: Field::Number, name: Field::String, priority: Field::Number, created_at: Field::DateTime, updated_at: Field::DateTime, } # COLLECTION_ATTRIBUTES # an array of attributes that will be displayed on the model's index page. # # By default, it's limited to four items to reduce clutter on index pages. # Feel free to add, remove, or rearrange items. COLLECTION_ATTRIBUTES = [ :event, :name, :sponsors ] # SHOW_PAGE_ATTRIBUTES # an array of attributes that will be displayed on the model's show page. SHOW_PAGE_ATTRIBUTES = ATTRIBUTE_TYPES.keys # FORM_ATTRIBUTES # an array of attributes that will be displayed # on the model's form (`new` and `edit`) pages. FORM_ATTRIBUTES = [ :event, :name, :priority, :sponsors ] # Overwrite this method to customize how sponsorships are displayed # across all pages of the admin dashboard. def display_resource(sponsorship) "#{sponsorship.event.name} #{sponsorship.name}" end end
mit
davidwparker/programmingtil-webgl
0101-complex-objects-part-1/src/uiMouse.js
1610
/* * UI Mouse Events * www.programmingtil.com * www.codenameparkerllc.com */ function mousedown(event) { if (uiUtils.inCanvas(event)) { state.gl.disable(state.gl.BLEND); state.gl.enable(state.gl.DEPTH_TEST); state.gl.depthMask(true); state.app.objects.forEach(function(obj) { obj.readState(); renderer.draw(); }); var pixels = Array.from( uiUtils.pixelsFromMouseClick(event, state.canvas, state.gl) ); var obj2 = uiUtils.pickObject(pixels, state.app.objects, 'selColor'); if (obj2) { state.app.objSel = obj2; state.ui.mouse.lastX = event.clientX; state.ui.mouse.lastY = event.clientY; state.ui.dragging = true; } state.gl.enable(state.gl.BLEND); state.gl.disable(state.gl.DEPTH_TEST); state.gl.depthMask(false); state.app.objects.forEach(function(obj) { obj.drawState(); renderer.draw(); }); } } function mouseup(event) { state.ui.dragging = false; } function mousemove(event) { var x = event.clientX; var y = event.clientY; if (state.ui.dragging) { // The rotation speed factor // dx and dy here are how for in the x or y direction the mouse moved var factor = 10 / state.canvas.height; var dx = factor * (x - state.ui.mouse.lastX); var dy = factor * (y - state.ui.mouse.lastY); // update the latest angle state.app.objSel.state.angle[0] = state.app.objSel.state.angle[0] + dy; state.app.objSel.state.angle[1] = state.app.objSel.state.angle[1] + dx; } // update the last mouse position state.ui.mouse.lastX = x; state.ui.mouse.lastY = y; }
mit
yogeshsaroya/new-cdnjs
ajax/libs/catiline/2.9.0-dev.2/catiline.min.js
130
version https://git-lfs.github.com/spec/v1 oid sha256:dce3dd49b42a9715d929b59a10021ffbcdc9af2429c4136e3fd7f941f3003b7c size 11445
mit
xiaozhuchacha/OpenBottle
grammar_induction/grammars/grammar2parser.py
5516
import argparse import os def load_aog(file_path): lines = [line.rstrip('\n') for line in open(file_path)] or_nodes_children = {} or_nodes_prob = {} for index, line in enumerate(lines): # count the number of nodes if line.startswith('Terminal#'): num_terminal = int(line.lstrip('Terminal#')) elif line.startswith('AndNode#'): num_and = int(line.lstrip('AndNode#')) elif line.startswith('OrNode#'): num_or = int(line.lstrip('OrNode#')) elif line.startswith('StartSymbol'): num_all = int(line.lstrip('StartSymbol')) + 1 assert num_terminal + num_and + num_or == num_all # read nodes elif line.startswith('Terminals'): terminal_nodes = lines[index+1:index+num_terminal+1] terminal_nodes = [int(t.split('\t')[0]) for t in terminal_nodes] assert len(terminal_nodes) == num_terminal elif line.startswith('AndNodes'): and_nodes = lines[index+1:index+num_and+1] and_nodes_parent = [int(t.split('\t')[0]) for t in and_nodes] and_nodes_left_child = [int(t.split('\t')[1].lstrip('[').split('][')[0].rstrip().split()[0]) for t in and_nodes] and_nodes_right_child = [int(t.split('\t')[1].lstrip('[').split('][')[0].rstrip().split()[1]) for t in and_nodes] assert len(and_nodes_parent) == num_and elif line.startswith('OrNodes'): or_nodes = lines[index+1:index+num_or+1] or_nodes_parent = [int(t.split('\t')[0]) for t in or_nodes] or_nodes_children_raw = [t.split('\t')[1].lstrip('[').split('] [')[0].rstrip().split() for t in or_nodes] or_nodes_prob_raw = [t.split('\t')[1].lstrip('[').split('] [')[1].rstrip(' ]').split() for t in or_nodes] for i in range(len(or_nodes_parent)): or_nodes_children[i] = [int(t) for t in or_nodes_children_raw[i]] freq = [float(t) for t in or_nodes_prob_raw[i]] or_nodes_prob[i] = [float(t) / sum(freq) for t in or_nodes_prob_raw[i]] assert len(or_nodes_parent) == num_or root_node = or_nodes_parent[:] root_node.extend(and_nodes_parent) [root_node.remove(i) for i in and_nodes_left_child] [root_node.remove(i) for i in and_nodes_right_child] [root_node.remove(i) for i in list(or_nodes_children) if i in root_node] assert len(root_node) == 1 return root_node[0], and_nodes_parent, and_nodes_left_child, and_nodes_right_child, \ or_nodes_parent, or_nodes_children, or_nodes_prob, terminal_nodes, num_all def write_parser(root_node, and_nodes_parent, and_nodes_left_child, and_nodes_right_child, or_nodes_parent, or_nodes_children, or_nodes_prob, terminal_nodes, num_nodes): str_name = ['\'approach\'', '\'move\'', '\'grasp_left\'', '\'grasp_right\'', '\'ungrasp_left\'', '\'ungrasp_right\'', '\'twist\'', '\'push\'', '\'neutral\'', '\'pull\'', '\'pinch\'', '\'unpinch\''] # padding name to name for i in range(len(str_name), num_nodes): str_name.append('node_'+str(i)) with open('parser_input.txt', 'w') as output_file: # root if root_node in and_nodes_parent: root_index = and_nodes_parent.index(root_node) output_file.write('root_%d -> %s %s [1.0]\n' % (root_node, str_name[and_nodes_left_child[root_index]], str_name[and_nodes_right_child[root_index]])) del and_nodes_parent[root_index] del and_nodes_right_child[root_index] del and_nodes_left_child[root_index] elif root_node in or_nodes_parent: root_index = or_nodes_parent.index(root_node) output_file.write('root_%d ->' % root_node) for i in or_nodes_children[root_index]: output_file.write(' %s %s\n' % (str_name[i], str(or_nodes_prob[root_index]))) del or_nodes_parent[root_index] del or_nodes_children[root_index] del or_nodes_prob[root_index] else: print 'no root found in and or parent node' # and for i in range(len(and_nodes_parent)): output_file.write('%s -> %s %s [1.0]\n' % (str_name[and_nodes_parent[i]], str_name[and_nodes_left_child[i]], str_name[and_nodes_right_child[i]])) # or for i in range(len(or_nodes_parent)): for s, t in zip(or_nodes_children[i], or_nodes_prob[i]): output_file.write('%s -> %s [%s]\n' % (str_name[or_nodes_parent[i]], str_name[s], str(t))) def main(): # parse input parser = argparse.ArgumentParser() parser.add_argument('-i', '--input_grammar') args = parser.parse_args() input_grammar = args.input_grammar assert (os.path.exists(input_grammar)) assert (os.path.isfile(input_grammar)) root_node, and_nodes_parent, and_nodes_left_child, and_nodes_right_child, \ or_nodes_parent, or_nodes_children, or_nodes_prob, terminal_nodes, num_nodes = load_aog(input_grammar) write_parser(root_node, and_nodes_parent, and_nodes_left_child, and_nodes_right_child, or_nodes_parent, or_nodes_children, or_nodes_prob, terminal_nodes, num_nodes) if __name__ == '__main__': main()
mit
bernardotc/P-Learning
View/EditMCQ.php
16698
<?php /** * Created by PhpStorm. * User: bernardot * Date: 6/17/16 * Time: 11:59 AM */ require ("../Model/User.php"); require ("../Model/Course.php"); require ("../Model/PLContent.php"); session_start(); $login = ''; $signin = ''; $home = 'class=""'; $courseActive = 'class=""'; $user = $_SESSION["user"]; $course = $_SESSION["course"]; if ($user == null) { header("Location: ../Control/MainController.php?do=logout"); } else if ($course == null) { header("Location: ../View/Home.php"); } $image0 = $image1 = $image2 = $image3 = $image4 = null; $image0ext = $image1ext = $image2ext = $image3ext = $image4ext = null; $errorMessage = ""; if($_SERVER["REQUEST_METHOD"] == "POST") { if (isset($_POST["delete"])) { $mysqli = new mysqli("localhost", "root", "", "p-learning"); if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error; } $statement = $mysqli->prepare("DELETE FROM Questions WHERE id = ?"); $statement->bind_param("i", $_GET["id"]); $statement->execute(); header("Location: ../View/EditMCQs.php"); } $question = new Question($_POST["question"], $_POST["optionA"], $_POST["optionB"], $_POST["optionC"], $_POST["optionD"], $_POST["cAnswer"], $course->id); // REFERENCE: http://www.w3schools.com/php/php_file_upload.asp $uploadOk = 1; for ($i = 0; $i < 5; $i++) { $imageFileType = pathinfo(basename($_FILES["image" . $i]["name"]), PATHINFO_EXTENSION); // Check if image file is a actual image or fake image $check = getimagesize($_FILES["image" . $i]["tmp_name"]); if ($check !== false) { //echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; // Check file size if ($_FILES["image" . $i]["size"] > 10000000) { $errorMessage .= "Sorry, your file is too large. "; $uploadOk = 0; } // Allow certain file formats echo "IMAGE TYPE = " . $imageFileType; if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif") { $errorMessage .= "Sorry, only JPG, JPEG, PNG & GIF files are allowed. "; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { $errorMessage .= "Your file was not uploaded. "; // if everything is ok, try to upload file } else { if ($i == 0) { $question->questionI = file_get_contents($_FILES["image" . $i]["tmp_name"]); $question->questionIExt = $imageFileType; } else if ($i == 1) { $question->answerAI = file_get_contents($_FILES["image" . $i]["tmp_name"]); $question->answerAIExt = $imageFileType; } else if ($i == 2) { $question->answerBI = file_get_contents($_FILES["image" . $i]["tmp_name"]); $question->answerBIExt = $imageFileType; } else if ($i == 3) { $question->answerCI = file_get_contents($_FILES["image" . $i]["tmp_name"]); $question->answerCIExt = $imageFileType; } else if ($i == 4) { $question->answerDI = file_get_contents($_FILES["image" . $i]["tmp_name"]); $question->answerDIExt = $imageFileType; } } } } if($uploadOk == 1) { $question->id = $_GET["id"]; //echo '<img src="data:image/'.$question->questionIExt.';base64,'.base64_encode($question->questionI).'"/>'; $mysqli = new mysqli("localhost", "root", "", "p-learning"); if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error; } $question->updateCompleteInDatabase($mysqli); $mysqli->close(); header("Location: ../View/EditMCQs.php"); } } $question = null; $mysqli = new mysqli("localhost", "root", "", "p-learning"); if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error; } $statement = $mysqli->prepare("SELECT * FROM Questions WHERE id = ?"); $statement->bind_param("i", $_GET["id"]); $statement->execute(); $result = $statement->get_result(); while ($row = $result->fetch_row()) { $i = $row[0]; $q = $row[1]; $a = $row[4]; $b = $row[7]; $c = $row[10]; $d = $row[13]; $cA = $row[16]; $co = $row[17]; $question = new Question($i, $q, $a, $b, $c, $d, $cA, $co); $question->questionI = $row[3]; $question->questionIExt = $row[2]; $question->answerAI = $row[6]; $question->answerAIExt = $row[5]; $question->answerBI = $row[9]; $question->answerBIExt = $row[8]; $question->answerCI = $row[12]; $question->answerCIExt = $row[11]; $question->answerDI = $row[15]; $question->answerDIExt = $row[14]; } ?> <style> aside { display: block; background-color: #2c68b2; border-color: #255897; } .list-group { text-align: center; } section { display: block; } #questionForm { background-color: #8dbdd9; border: 1px solid; border-color: #255897; min-height: 25%; padding-top: 1%; padding-left: 1%; padding-right: 1%; text-align: left; overflow: hidden; } .list-group > a { cursor: pointer; } form > button { float: right; display:none; height: 0; } </style> <?php include 'Header.php';?> <h1 id="title">Edit a Multiple Choice Question</h1> <h4><?php echo $course->code.' - '.$course->title; ?></h4> <hr/> <section class="col-lg-10"> <form id="questionForm" enctype="multipart/form-data" method="post"> <p style="color: #ffffff">In this space you can modify a question by changing its text and images.</p> <div class="input-group input-group-sm"> <input type="text" class="form-control" id="question" name="question" placeholder="Question related to the slide." value="<?php echo $question->question;?>" required/> <?php if($question->questionIExt != null) { ?> <span class="input-group-btn"><button data-toggle="modal" data-target="#questionModal" type="button" class="btn btn-default">View Image</button></span> <?php } ?> <span class="input-group-addon"><input type="file" name="image0" id="image"></span> </div> <div class="input-group input-group-sm"> <span class="input-group-addon">Correct Answer:</span> <span class="input-group-addon"><input class="form-control" type="radio" id="cAnswerA" name="cAnswer" value="A" style="width: 20px; height:18px;" <?php if ($question->correct == "A") echo "checked"?> required/></span> <input class="form-control" type="text" id="optionA" name="optionA" placeholder="Answer A" value="<?php echo $question->answerA;?>" required> <?php if($question->answerAIExt != null) { ?> <span class="input-group-btn"><button data-toggle="modal" data-target="#answerAModal" type="button" class="btn btn-default">View Image</button></span> <?php } ?> <span class="input-group-addon"><input type="file" name="image1" id="image"></span> </div> <div class="input-group input-group-sm"> <span class="input-group-addon">Correct Answer:</span> <span class="input-group-addon"><input class="form-control" type="radio" id="cAnswerB" name="cAnswer" value="B" style="width: 20px; height:18px;" <?php if ($question->correct == "B") echo "checked"?> required></span> <input class="form-control" type="text" id="optionB" name="optionB" placeholder="Answer B" value="<?php echo $question->answerB;?>" required> <?php if($question->answerBIExt != null) { ?> <span class="input-group-btn"><button data-toggle="modal" data-target="#answerBModal" type="button" class="btn btn-default">View Image</button></span> <?php } ?> <span class="input-group-addon"><input type="file" name="image2" id="image"></span> </div> <div class="input-group input-group-sm"> <span class="input-group-addon">Correct Answer:</span> <span class="input-group-addon"><input class="form-control" type="radio" id="cAnswerC" name="cAnswer" value="C" style="width: 20px; height:18px;" <?php if ($question->correct == "C") echo "checked"?> required/></span> <input class="form-control" type="text" id="optionC" name="optionC" placeholder="Answer C" value="<?php echo $question->answerC;?>" required> <?php if($question->answerCIExt != null) { ?> <span class="input-group-btn"><button data-toggle="modal" data-target="#answerCModal" type="button" class="btn btn-default">View Image</button></span> <?php } ?> <span class="input-group-addon"><input type="file" name="image3" id="image"></span> </div> <div class="input-group input-group-sm"> <span class="input-group-addon">Correct Answer:</span> <span class="input-group-addon"><input class="form-control" type="radio" id="cAnswerD" name="cAnswer" value="D" style="width: 20px; height:18px;" <?php if ($question->correct == "D") echo "checked"?> required/></span> <input class="form-control" type="text" id="optionD" name="optionD" placeholder="Answer D" value="<?php echo $question->answerD;?>" required> <?php if($question->answerDIExt != null) { ?> <span class="input-group-btn"><button data-toggle="modal" data-target="#answerDModal" type="button" class="btn btn-default">View Image</button></span> <?php } ?> <span class="input-group-addon"><input type="file" name="image4" id="image"></span> </div> <div style="text-align: right"> <span style="color: #ffffff">Note: Image size should be less than 10 MB.</span> </div> <h4><?php echo $errorMessage?></h4> <button id="submitForm" type="submit" style="display: none">Save</button> </form> </section> <aside class="col-lg-2"> <br/> <div class="list-group"> <a class="list-group-item" onclick="save()"> <h5 class="list-group-item-heading">Save Question</h5> </a> <a class="list-group-item" onclick="deleteQuestion()"> <h5 class="list-group-item-heading">Delete Question</h5> </a> </div> </aside> <div class="modal fade" id="questionModal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h3 class="modal-title">Question Image</h3> </div> <div class="modal-body" style="text-align: center;"> <img src="data:image/<?php echo $question->questionIExt; ?>;base64,<?php echo base64_encode($question->questionI);?>" width="500px"/> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> <div class="modal fade" id="answerAModal" style="text-align: center;"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h3 class="modal-title">Answer A Image</h3> </div> <div class="modal-body"> <img src="data:image/<?php echo $question->answerAIExt; ?>;base64,<?php echo base64_encode($question->answerAI);?>" width="500px"/> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> <div class="modal fade" id="answerBModal" style="text-align: center;"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h3 class="modal-title">Answer B Image</h3> </div> <div class="modal-body"> <img src="data:image/<?php echo $question->answerBIExt; ?>;base64,<?php echo base64_encode($question->answerBI);?>" width="500px"/> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> <div class="modal fade" id="answerCModal" style="text-align: center;"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h3 class="modal-title">Answer C Image</h3> </div> <div class="modal-body"> <img src="data:image/<?php echo $question->answerCIExt; ?>;base64,<?php echo base64_encode($question->answerCI);?>" width="500px"/> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> <div class="modal fade" id="answerDModal" style="text-align: center;"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h3 class="modal-title">Answer D Image</h3> </div> <div class="modal-body"> <img src="data:image/<?php echo $question->answerDIExt; ?>;base64,<?php echo base64_encode($question->answerDI);?>" width="500px"/> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> <script> function save() { $("#submitForm").click(); } function deleteQuestion() { $("#questionForm").append($("<input>", {type: "hidden", name: "delete", value: "true"})).submit(); } // REFERENCE: http://stackoverflow.com/questions/20327505/navbar-stick-to-top-of-screen-when-scrolling-past $(function() { // grab the initial top offset of the navigation var sticky_navigation_offset_top = $('aside').offset().top; // our function that decides weather the navigation bar should have "fixed" css position or not. var sticky_navigation = function(){ var scroll_top = $(window).scrollTop(); // our current vertical position from the top // if we've scrolled more than the navigation, change its position to fixed to stick to top, otherwise change it back to relative if (scroll_top > sticky_navigation_offset_top) { $('aside').css({ 'position': 'fixed', 'top':0, 'right':0 }); } else { $('aside').css({ 'position': 'relative' }); } }; // run our function on load sticky_navigation(); // and run it again every time you scroll $(window).scroll(function() { sticky_navigation(); }); }); </script> <?php include 'Footer.php';?>
mit
vikramcse/react-qrcode-generator
app/components/Navbar.js
1037
var React = require('react'); var Navbar = React.createClass({ render() { return ( <nav className="navbar navbar-default"> <div className="container-fluid"> <div className="navbar-header"> <button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span className="sr-only">Toggle navigation</span> <span className="icon-bar"></span> <span className="icon-bar"></span> <span className="icon-bar"></span> </button> <a className="navbar-brand" href="#">QR Generator</a> </div> <div id="navbar" className="navbar-collapse collapse"> <ul className="nav navbar-nav"> <li className="active"> <a href="#">URL</a> </li> </ul> </div> </div> </nav> ); } }); module.exports = Navbar;
mit
rafecolton/docker-builder
job/job.go
8075
package job import ( "io" "net/http" "os" "strings" "time" "github.com/Sirupsen/logrus" "github.com/modcloth/go-fileutils" "github.com/modcloth/kamino" gouuid "github.com/nu7hatch/gouuid" "github.com/winchman/builder-core" "github.com/winchman/builder-core/unit-config" "github.com/rafecolton/docker-builder/conf" ) const ( defaultTail = "100" defaultBobfile = "Bobfile" specFixturesRepoDir = "./_testing/fixtures/repodir" ) var ( // TestMode monkeys with certain things for tests so bad things don't happen TestMode bool // SkipPush indicates whether or not a global --skip-push directive has been given SkipPush bool logger *logrus.Logger ) /* Job is the struct representation of a build job. Intended to be created with NewJob, but exported so it can be used for tests. */ type Job struct { Account string `json:"account,omitempty"` Bobfile string `json:"bobfile,omitempty"` Completed time.Time `json:"completed,omitempty"` Created time.Time `json:"created"` Error error `json:"error,omitempty"` GitCloneDepth string `json:"clone_depth,omitempty"` GitHubAPIToken string `json:"-"` ID string `json:"id,omitempty"` LogRoute string `json:"log_route,omitempty"` Logger *logrus.Logger `json:"-"` Ref string `json:"ref,omitempty"` Repo string `json:"repo,omitempty"` Status string `json:"status"` Workdir string `json:"-"` InfoRoute string `json:"info_route,omitempty"` logDir string `json:"-"` logFile *os.File `json:"-"` clonedRepoLocation string `json:"-"` } /* Config contains global configuration options for jobs */ type Config struct { Workdir string Logger *logrus.Logger GitHubAPIToken string } //Logger sets the (global) logger for the server package func Logger(l *logrus.Logger) { logger = l } func (job *Job) addHostToRoutes(req *http.Request) { var host string if req.Host != "" { host = req.Host } else { host = req.URL.Host } var scheme string if req.TLS == nil { scheme = "http" } else { scheme = "https" } if strings.HasPrefix(job.LogRoute, "/") { job.LogRoute = scheme + "://" + host + job.LogRoute } if strings.HasPrefix(job.InfoRoute, "/") { job.InfoRoute = scheme + "://" + host + job.InfoRoute } } /* NewJob creates a new job from the config as well as a job spec. After creating the job, calling job.Process() will actually perform the work. */ func NewJob(cfg *Config, spec *Spec, req *http.Request) *Job { var idUUID *gouuid.UUID var err error idUUID, err = gouuid.NewV4() if TestMode { idUUID, err = gouuid.NewV5(gouuid.NamespaceURL, []byte("0")) } if err != nil { cfg.Logger.WithField("error", err).Error("error creating uuid") } id := idUUID.String() bobfile := spec.Bobfile if bobfile == "" { bobfile = defaultBobfile } ret := &Job{ Bobfile: bobfile, ID: id, Account: spec.RepoOwner, GitHubAPIToken: spec.GitHubAPIToken, Ref: spec.GitRef, Repo: spec.RepoName, Workdir: cfg.Workdir, InfoRoute: "/jobs/" + id, LogRoute: "/jobs/" + id + "/tail?n=" + defaultTail, logDir: cfg.Workdir + "/" + id, Status: "created", Created: time.Now(), } ret.addHostToRoutes(req) out, file, err := newMultiWriter(ret.logDir) if err != nil { cfg.Logger.WithField("error", err).Error("error creating log dir") id = "" } ret.logFile = file ret.Logger = &logrus.Logger{ Formatter: cfg.Logger.Formatter, Level: cfg.Logger.Level, Out: out, } if ret.GitHubAPIToken == "" { ret.GitHubAPIToken = cfg.GitHubAPIToken } if id != "" { jobs[id] = ret } return ret } func newMultiWriter(logDir string) (io.Writer, *os.File, error) { var out io.Writer if err := fileutils.MkdirP(logDir, 0755); err != nil { return nil, nil, err } file, err := os.Create(logDir + "/log.log") if err != nil { return nil, nil, err } if TestMode { out = file } else { out = io.MultiWriter(os.Stdout, file) } return out, file, nil } func (job *Job) clone() (string, error) { job.Logger.WithFields(logrus.Fields{ "api_token_present": job.GitHubAPIToken != "", "account": job.Account, "ref": job.Ref, "repo": job.Repo, "clone_cache_option": kamino.No, }).Info("starting clone process") genome := &kamino.Genome{ APIToken: job.GitHubAPIToken, Account: job.Account, Ref: job.Ref, Repo: job.Repo, UseCache: kamino.No, } factory, err := kamino.NewCloneFactory(job.Workdir) if err != nil { job.Logger.WithFields(logrus.Fields{ "api_token_present": job.GitHubAPIToken != "", "account": job.Account, "ref": job.Ref, "repo": job.Repo, "clone_cache_option": kamino.No, "error": err, }).Error("issue creating clone factory") return "", err } job.Logger.Debug("attempting to clone") path, err := factory.Clone(genome) if err != nil { job.Logger.WithFields(logrus.Fields{ "api_token_present": job.GitHubAPIToken != "", "account": job.Account, "ref": job.Ref, "repo": job.Repo, "clone_cache_option": kamino.No, "error": err, }).Error("issue cloning") return "", err } job.Logger.WithFields(logrus.Fields{ "api_token_present": job.GitHubAPIToken != "", "account": job.Account, "ref": job.Ref, "repo": job.Repo, "clone_cache_option": kamino.No, }).Info("cloning successful") return path, nil } func (job *Job) build() error { job.Logger.Debug("attempting to create a builder") unitConfig, err := unitconfig.ReadFromFile(job.clonedRepoLocation + "/" + job.Bobfile) if err != nil { job.Logger.WithField("error", err).Error("issue parsing Bobfile") return err } globals := unitconfig.ConfigGlobals{ SkipPush: SkipPush, CfgUn: conf.Config.CfgUn, CfgPass: conf.Config.CfgPass, CfgEmail: conf.Config.CfgEmail, } unitConfig.SetGlobals(globals) job.Logger.WithField("file", job.Bobfile).Info("building from file") return runner.RunBuildSynchronously(runner.Options{ UnitConfig: unitConfig, ContextDir: job.clonedRepoLocation, LogLevel: job.Logger.Level, }) } /* Process does the actual job processing work, including: 1. clone the repo 2. build from the Bobfile at the top level 3. clean up the cloned repo */ func (job *Job) Process() error { if TestMode { return job.processTestMode() } defer func() { if job.logFile != nil { job.logFile.Close() } }() // step 1: clone job.Status = "cloning" path, err := job.clone() if err != nil { job.Logger.WithField("error", err).Error("unable to process job synchronously") job.Status = "errored" job.Error = err return err } job.clonedRepoLocation = path // step 2: build job.Status = "building" if err = job.build(); err != nil { job.Logger.WithField("error", err).Error("unable to process job synchronously") job.Status = "errored" job.Error = err return err } job.Status = "completed" job.Completed = time.Now() fileutils.RmRF(path) return nil } func (job *Job) processTestMode() error { // If this function is used correctly, // we should never see this warning message. job.Logger.Warn("processing job in test mode") // set status to validating in anticipation of performing validation step job.Status = "validating" // set clone path to fixtures dir job.clonedRepoLocation = specFixturesRepoDir // log something for test purposes levelBefore := job.Logger.Level job.Logger.Level = logrus.DebugLevel job.Logger.Debug("FOO") job.Logger.Level = levelBefore // mark job as completed job.Status = "completed" job.Completed = time.Now() return nil }
mit
mklevin/hackru
src/android/HackRU/app/src/androidTest/java/com/example/natalie/hackru/ApplicationTest.java
357
package com.example.natalie.hackru; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
mit
githubpermutation/pyradio
pyradio/player.py
5936
import subprocess import threading import os import logging logger = logging.getLogger(__name__) class Player(object): """ Media player class. Playing is handled by mplayer """ process = None def __init__(self, outputStream): self.outputStream = outputStream def __del__(self): self.close() def updateStatus(self): if (logger.isEnabledFor(logging.DEBUG)): logger.debug("updateStatus thread started.") try: out = self.process.stdout while(True): subsystemOut = out.readline().decode("utf-8", "ignore") if subsystemOut == '': break subsystemOut = subsystemOut.strip() subsystemOut = subsystemOut.replace("\r", "").replace("\n", "") if (logger.isEnabledFor(logging.DEBUG)): logger.debug("User input: {}".format(subsystemOut)) self.outputStream.write(subsystemOut) except: logger.error("Error in updateStatus thread.", exc_info=True) if (logger.isEnabledFor(logging.DEBUG)): logger.debug("updateStatus thread stopped.") def isPlaying(self): return bool(self.process) def play(self, streamUrl): """ use a multimedia player to play a stream """ self.close() opts = [] isPlayList = streamUrl.split("?")[0][-3:] in ['m3u', 'pls'] opts = self._buildStartOpts(streamUrl, isPlayList) self.process = subprocess.Popen(opts, shell=False, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT) t = threading.Thread(target=self.updateStatus, args=()) t.start() if logger.isEnabledFor(logging.DEBUG): logger.debug("Player started") def _sendCommand(self, command): """ send keystroke command to mplayer """ if(self.process is not None): try: if logger.isEnabledFor(logging.DEBUG): logger.debug("Command: {}".format(command).strip()) self.process.stdin.write(command.encode("utf-8")) except: msg = "Error when sending: {}" logger.error(msg.format(command).strip(), exc_info=True) def close(self): """ exit pyradio (and kill mplayer instance) """ # First close the subprocess self._stop() # Here is fallback solution and cleanup if self.process is not None: os.kill(self.process.pid, 15) self.process.wait() self.process = None def _buildStartOpts(self, streamUrl, playList): pass def mute(self): pass def _stop(self): pass def volumeUp(self): pass def volumeDown(self): pass class MpPlayer(Player): """Implementation of Player object for MPlayer""" PLAYER_CMD = "mplayer" def _buildStartOpts(self, streamUrl, playList=False): """ Builds the options to pass to subprocess.""" if playList: opts = [self.PLAYER_CMD, "-quiet", "-playlist", streamUrl] else: opts = [self.PLAYER_CMD, "-quiet", streamUrl] return opts def mute(self): """ mute mplayer """ self._sendCommand("m") def pause(self): """ pause streaming (if possible) """ self._sendCommand("p") def _stop(self): """ exit pyradio (and kill mplayer instance) """ self._sendCommand("q") def volumeUp(self): """ increase mplayer's volume """ self._sendCommand("*") def volumeDown(self): """ decrease mplayer's volume """ self._sendCommand("/") class VlcPlayer(Player): """Implementation of Player for VLC""" PLAYER_CMD = "cvlc" muted = False def _buildStartOpts(self, streamUrl, playList=False): """ Builds the options to pass to subprocess.""" opts = [self.PLAYER_CMD, "-Irc", "--quiet", streamUrl] return opts def mute(self): """ mute mplayer """ if not self.muted: self._sendCommand("volume 0\n") self.muted = True else: self._sendCommand("volume 256\n") self.muted = False def pause(self): """ pause streaming (if possible) """ self._sendCommand("stop\n") def _stop(self): """ exit pyradio (and kill mplayer instance) """ self._sendCommand("shutdown\n") def volumeUp(self): """ increase mplayer's volume """ self._sendCommand("volup\n") def volumeDown(self): """ decrease mplayer's volume """ self._sendCommand("voldown\n") def probePlayer(): """ Probes the multimedia players which are available on the host system.""" if logger.isEnabledFor(logging.DEBUG): logger.debug("Probing available multimedia players...") implementedPlayers = Player.__subclasses__() if logger.isEnabledFor(logging.INFO): logger.info("Implemented players: " + ", ".join([player.PLAYER_CMD for player in implementedPlayers])) for player in implementedPlayers: try: p = subprocess.Popen([player.PLAYER_CMD, "--help"], stdout=subprocess.PIPE, stdin=subprocess.PIPE, shell=False) p.terminate() if logger.isEnabledFor(logging.DEBUG): logger.debug("{} supported.".format(str(player))) return player except OSError: if logger.isEnabledFor(logging.DEBUG): logger.debug("{} not supported.".format(str(player)))
mit
ameet007/popin
application/views/admin/include/09062017header.php
6554
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="A fully featured admin theme which can be used to build CRM, CMS, etc."> <meta name="author" content="Coderthemes"> <!-- App favicon --> <link rel="shortcut icon" href="<?= base_url('theme/admin/assets/images/favicon.ico'); ?>"> <!-- App title --> <title><?= $module_heading.' | '.SITE_DISPNAME; ?></title> <!--Morris Chart CSS --> <link rel="stylesheet" href="<?= base_url('theme/admin/plugins/morris/morris.css'); ?>"> <!-- App css --> <link href="<?= base_url('theme/admin/assets/css/bootstrap.min.css'); ?>" rel="stylesheet" type="text/css" /> <link href="<?= base_url('theme/admin/assets/css/core.css'); ?>" rel="stylesheet" type="text/css" /> <link href="<?= base_url('theme/admin/assets/css/components.css'); ?>" rel="stylesheet" type="text/css" /> <link href="<?= base_url('theme/admin/assets/css/icons.css'); ?>" rel="stylesheet" type="text/css" /> <link href="<?= base_url('theme/admin/assets/css/pages.css'); ?>" rel="stylesheet" type="text/css" /> <link href="<?= base_url('theme/admin/assets/css/menu.css'); ?>" rel="stylesheet" type="text/css" /> <link href="<?= base_url('theme/admin/assets/css/custom.css'); ?>" rel="stylesheet" type="text/css" /> <link href="<?= base_url('theme/admin/assets/css/responsive.css'); ?>" rel="stylesheet" type="text/css" /> <link rel="stylesheet" href="<?= base_url('theme/admin/plugins/switchery/switchery.min.css'); ?>"> <link href="<?= base_url('theme/admin/plugins/bootstrap-datepicker/css/bootstrap-datepicker.min.css'); ?>" rel="stylesheet"> <!--Initialize Jquery--> <script src="<?= base_url('theme/admin/assets/js/jquery.min.js'); ?>"></script> <!--Initialize Bootstrap--> <script src="<?= base_url('theme/admin/assets/js/bootstrap.min.js'); ?>"></script> <!--Initialize Jquery Validation with Additional Methods--> <script src="<?= base_url('theme/admin/assets/js/jquery.validate.js'); ?>"></script> <script src="<?= base_url('theme/admin/assets/js/additional-methods.js'); ?>"></script> <!-- BEGIN DATATABLE PLUGINS --> <link href="<?= base_url('theme/admin/plugins/datatables/datatables.min.css'); ?>" rel="stylesheet" type="text/css" /> <link href="<?= base_url('theme/admin/plugins/datatables/plugins/bootstrap/datatables.bootstrap.css'); ?>" rel="stylesheet" type="text/css" /> <!-- END DATATABLE PLUGINS --> <!-- HTML5 Shiv and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script> <![endif]--> <script src="<?= base_url('theme/admin/assets/js/modernizr.min.js'); ?>"></script> <!--Wysiwig js--> <script src="<?= base_url('theme/admin/plugins/tinymce/tinymce.min.js'); ?>"></script> <style> .error { color: #f5707a; } </style> <script> $(document).ready(function(e) { jQuery.validator.addMethod("fileSize", function (val, element) { if(typeof element.files[0]=== "undefined") { return true; } else { var size = element.files[0].size; console.log(size); if (size > 2048576)// checks the file more than 1 MB { return false; } else { return true; } } }, "Maximum 2MB Image Size Allowed"); $('.history-back').click(function(){ window.history.back(); }); }); </script> </head> <body class="fixed-left"> <!-- Begin page --> <div id="wrapper"> <!-- Top Bar Start --> <div class="topbar"> <!-- LOGO --> <div class="topbar-left"> <a href="<?= base_url(ADMIN_DIR); ?>" class="logo"><span><?= SITE_DISPNAME; ?></span><i class="mdi mdi-layers"></i></a> <!-- Image logo --> <!--<a href="index.html" class="logo">--> <!--<span>--> <!--<img src="assets/images/logo.png" alt="" height="30">--> <!--</span>--> <!--<i>--> <!--<img src="assets/images/logo_sm.png" alt="" height="28">--> <!--</i>--> <!--</a>--> </div> <!-- Button mobile view to collapse sidebar menu --> <div class="navbar navbar-default" role="navigation"> <div class="container"> <!-- Right(Notification) --> <ul class="nav navbar-nav navbar-right"> <li class="dropdown user-box"> <a href="" class="dropdown-toggle waves-effect user-link" data-toggle="dropdown" aria-expanded="true"> <img src="<?= base_url('uploads/admin/'.$adminProfileInfo->avatar); ?>" alt="<?= $adminProfileInfo->name; ?>" title="<?= $adminProfileInfo->name; ?>" class="img-circle user-img"> </a> <ul class="dropdown-menu dropdown-menu-right arrow-dropdown-menu arrow-menu-right user-list notify-list"> <li> <h5>Hi, <?= $adminProfileInfo->name; ?></h5> </li> <li><a href="<?= base_url(ADMIN_DIR.'/profile'); ?>"><i class="ti-user m-r-5"></i> Profile</a></li> <li><a href="<?= base_url(ADMIN_DIR.'/settings'); ?>"><i class="ti-settings m-r-5"></i> Settings</a></li> <li><a href="<?= base_url(ADMIN_DIR.'/logout'); ?>"><i class="ti-power-off m-r-5"></i> Logout</a></li> </ul> </li> </ul> <!-- end navbar-right --> </div><!-- end container --> </div><!-- end navbar --> </div> <!-- Top Bar End -->
mit
bkahlert/seqan-research
raw/pmsb13/pmsb13-data-20130530/sources/427smdvbnknp0jra/2013-05-13T21-49-34.899+0200/sandbox/gruppe1/apps/PEMer_Lite/PEMer_Lite_test.cpp
8774
#undef SEQAN_ENABLE_TESTING #define SEQAN_ENABLE_TESTING 1 #include <seqan/sequence.h> #include <seqan/basic.h> #include <seqan/file.h> #include "PEMer_Lite.h" int median(candidate &input) // erstellt den median muss noch an struct candidate angepasst werden { std::nth_element( begin(input.len), begin(input.len) + input.length()/2,end(input.len)); input.e=*(begin(input.len) + input.length()/2 ); return 0; } unsigned average(candidate &input) // erzeugt den Durchschnitt und speichert ihm Objekt { unsigned tmpi=0; unsigned n = input.length(); for (unsigned i=0;i<n;i++) { tmpi += input.len[i]; } return tmpi/n; } seqan::ArgumentParser::ParseResult commands(modifier &options, int argc, char const ** argv) { seqan::ArgumentParser parser("PEMer_Lite"); // Optionen hinzufügen addOption(parser, seqan::ArgParseOption("i","input-file","Input SAM-file.",seqan::ArgParseArgument::INPUTFILE)); setValidValues(parser, "input-file", "sam"); setRequired(parser, "input-file"); addOption(parser,seqan::ArgParseOption("x","SD-variable", "Variable to use for multiples of standard degression.",seqan::ArgParseArgument::INTEGER, "INT")); setMinValue(parser, "SD-variable", "1"); setDefaultValue(parser,"SD-variable","1"); addOption(parser,seqan::ArgParseOption("y","Del_SD-variable", "Variable to spezify multiples of standard degression for deletions.",seqan::ArgParseArgument::INTEGER, "INT")); setMinValue(parser, "Del_SD-variable", "1"); setDefaultValue(parser,"Del_SD-variable","1"); addOption(parser,seqan::ArgParseOption("s","standard_degression", "Variable to use for standard degression for length of fragments.",seqan::ArgParseArgument::INTEGER, "INT")); setMinValue(parser, "standard_degression", "1"); addOption(parser,seqan::ArgParseOption("e","expected_value", "Variable to use for the expected value for length of fragments.",seqan::ArgParseArgument::INTEGER, "INT")); setMinValue(parser, "expected_value", "1"); addOption(parser, seqan::ArgParseOption("p","Print", "Select to print temporary solutions.")); // verarbeitet die Kommandozeile seqan::ArgumentParser::ParseResult res = seqan::parse(parser, argc, argv); // Überprüfung der richtigen Ausführung von commands() if (res != seqan::ArgumentParser::PARSE_OK) return res; // extrahiert Werte aus der parser. getOptionValue(options.x, parser, "SD-variable"); getOptionValue(options.y, parser, "Del_SD-variable"); getOptionValue(options.e, parser, "expected_value"); getOptionValue(options.sd, parser, "standard_degression"); options.p = isSet(parser, "Print"); getOptionValue(options.inputFile, parser, "input-file"); return seqan::ArgumentParser::PARSE_OK; } int analyse(candidate &input) //erzeugt die Standartabweichung { median(input); input.sd=0; unsigned n = input.length(); for (unsigned i=0;i<n;i++) { input.sd += (input.len[i]-input.e)*(input.len[i]-input.e); } input.sd /= n; input.sd = sqrt((double)input.sd); return 0; } int saminput(candidate &save, char *file) // impotiert eine SAM-Datei und speichert sie im Format candidate { // BamStream öffnet Eingangsdatenstrom seqan::BamStream SamInput(file); if (!isGood(SamInput)) { std::cerr << "-ERROR- Could not open" << std::endl; return 1; } // record enthält die inhalte aus einer SAM-Datei seqan::BamAlignmentRecord record; while (!atEnd(SamInput)) { readRecord(record, SamInput); save.len.push_back(length(record.seq)); save.ref.push_back(record.rID); save.pos.push_back(record.beginPos); save.type.push_back(candidate::u); } return 0; } int devide(candidate &input,candidate &result,modifier &options) // sucht nach insertions und deletions { result.clear(); if(options.sd==0) { analyse(input); } else { input.e=options.e; input.sd=options.sd; } for (unsigned i=0;i<input.length();i++) { if(input.len[i]<input.e-(options.x * input.sd)) { result.len.push_back(input.len[i]); result.pos.push_back(input.pos[i]); result.ref.push_back(input.ref[i]); result.type.push_back(candidate::d); } if(input.len[i]>input.e+(options.y * input.sd)) { result.len.push_back(input.len[i]); result.pos.push_back(input.pos[i]); result.ref.push_back(input.ref[i]); result.type.push_back(candidate::i); } } return 0; } int tsv(std::vector<std::vector<unsigned>> &input,candidate &ref, char *out) { std::fstream outFile(out, std::ios::out); int k=0; if (!outFile) { std::cerr << "-ERROR- Could not open output file" << std::endl; return 1; } else { if(!input.empty()) { for (unsigned i=0;i<input.size();i++) { if(!input[i].empty()) { outFile << "Cluster " << i-k+1 << ":\n"; for(auto j=input[i].begin();j != input[i].end();j++) { outFile << " " << ref.ref[*j] << " " << ref.pos[*j] << " " << ref.len[*j] << " " << (candidate::form)ref.type[*j] << std::endl; } } else { k++; } } } } outFile.close(); return 0; } int findCluster(candidate &input, std::vector<std::vector<unsigned> > &dest, candidate::form indel) { std::vector<unsigned> currentCluster; unsigned currentClusterEndPos; // Iterieren über alle Funde for(unsigned i = 0; i < input.length(); ++i) { // Insertionen bzw. Deletionen herausfiltern if(input.type[i] == indel) { if(currentCluster.empty()) { // ersten Fund zu bisher leerem ersten Cluster hinzufügen currentCluster.push_back(i); currentClusterEndPos = input.pos[i] + input.len[i] - 1; } else { // Fall 1: Fund liegt innerhalb der Grenzen eines vorherigen Fundes if(input.pos[i] + input.len[i] - 1 <= currentClusterEndPos){ currentCluster.push_back(i); } else { unsigned overlapLen = std::max((int)(currentClusterEndPos - input.pos[i] + 1), 0); // Fall 2: Fund überlappt ausreichend mit dem Cluster if(overlapLen / std::min(currentClusterEndPos - input.pos[currentCluster.back()] + 1, input.pos[i] + input.len[i] - 1) > 0.5){ currentCluster.push_back(i); } // Fall 3: Fund überlappt nicht ausreichend mit dem Cluster else { dest.push_back(currentCluster); currentCluster.clear(); currentCluster.push_back(i); } currentClusterEndPos = input.pos[i] + input.len[i] - 1; } } } } dest.push_back(currentCluster); return 0; } SEQAN_DEFINE_TEST(test_my_app_PEMer_Lite_input) { candidate test; char *file ="/Informatik/Development/test.sam"; SEQAN_ASSERT(!saminput(test,file)); } SEQAN_DEFINE_TEST(test_my_app_PEMer_Lite_input2) { candidate test; char *file =" "; SEQAN_ASSERT(saminput(test,file)); } SEQAN_DEFINE_TEST(test_my_app_PEMer_Lite_input3) { candidate test; char *file ="2579816ß15362466183b513ü6ß148z5!§%%!&°%(!%§(%§c465cn4ü457346511425129562e85z148z5!§%%!&°%(!%§(%§&&&&&("; SEQAN_ASSERT(saminput(test,file)); } SEQAN_DEFINE_TEST(test_my_app_PEMer_Lite_devide) { candidate test,result; modifier opt; for(unsigned i=1;i<6;i++) { test.len.push_back(10); test.pos.push_back(i); test.ref.push_back(i); } test.len.push_back(3); test.pos.push_back(6); test.ref.push_back(6); test.len.push_back(9); test.pos.push_back(7); test.ref.push_back(7); test.len.push_back(11); test.pos.push_back(8); test.ref.push_back(8); test.len.push_back(1000); test.pos.push_back(9); test.ref.push_back(9); test.len.push_back(200); test.pos.push_back(10); test.ref.push_back(10); test.e=10; test.sd=1; opt.x=1; opt.y=1; devide(test,result,opt); SEQAN_ASSERT_EQ(result.type[0],1); SEQAN_ASSERT_EQ(result.type[1],1); SEQAN_ASSERT_EQ(result.type[2],2); SEQAN_ASSERT_EQ(result.ref[0],6); SEQAN_ASSERT_EQ(result.ref[1],9); SEQAN_ASSERT_EQ(result.ref[2],10); } SEQAN_BEGIN_TESTSUITE(test_my_app_funcs) { SEQAN_CALL_TEST(test_my_app_PEMer_Lite_input); SEQAN_CALL_TEST(test_my_app_PEMer_Lite_input2); SEQAN_CALL_TEST(test_my_app_PEMer_Lite_input3); SEQAN_CALL_TEST(test_my_app_PEMer_Lite_devide); } SEQAN_END_TESTSUITE
mit
kingsamchen/Eureka
CompileTimeContainers/main.cpp
1318
/* @ 0xCCCCCCCC */ #include "array_result.h" #include "upper_case.h" #include "string_sort.h" template<typename T, size_t N> constexpr auto GenerateArray() -> array_result<T, N> { array_result<T, N> ary; for (size_t i = 0; i < N; ++i) { ary[i] = i + 1; } return ary; } void VerifyArrayResult() { constexpr auto ary = GenerateArray<int, 3>(); static_assert(ary[0] == 1, "Yep"); static_assert(ary[1] == 2, "Yep"); static_assert(ary[2] == 3, "Yep"); } void VerifyCompileTimeUpperCase() { constexpr auto str = MakeUpperCase("Hello, world"); static_assert(str[0] == 'H', "Yek"); static_assert(str[4] == 'O', "Yek"); static_assert(str[5] == ',', "Yek"); } void VerifyStringSort() { static_assert(compile_time_string_less("abc", "bcd"), "Yak"); constexpr const char* strings[] { "test", "hello", "jungle" }; constexpr auto sorted = compile_time_str_sort(strings); static_assert(compile_time_string_equals(sorted[0], "hello"), "Yak"); static_assert(compile_time_string_equals(sorted[2], "test"), "Yak"); for (size_t i = 0; i < sorted.size(); ++i) { printf("%s\n", sorted[i]); } } int main() { VerifyArrayResult(); VerifyCompileTimeUpperCase(); VerifyStringSort(); return 0; }
mit
tkw1536/JAUS
lib/server/routes/main.js
1009
var config = require("../../config"); var Link = require("../../db").models.Link; module.exports = function(router, express){ router.use("/!/", express.static(__dirname + "/../../../htdocs")); router.use(function(req, res, next){ // get the path, redirect if we are at "!" var path = unescape(req.url); if(path == "/" || path == ""){ return res.redirect("/!/"); } var normalLink = Link.cleanupPath(path); var normalQuestion = Link.cleanupQuestion(path); Link.findOne({ $or : [ {"isQuestion": false, path: normalLink}, {"isQuestion": true, path: normalQuestion} ] }, function(err, doc){ if(err || !doc){ return next(); } if(doc.inFrame){ res.render("frame", {url: doc.url}) } else { res.redirect(doc.url); } }); }, function(req, res){ res .status(404) .render("error", { "siteName": config.name, "message": "HTTP 404 - Page not found" }) }); };
mit
lowks/flask-sqlalchemy-booster
flask_sqlalchemy_booster/json_columns.py
2164
from sqlalchemy.types import TypeDecorator, TEXT from sqlalchemy.ext.mutable import Mutable from flask.json import _json as json from .json_encoder import json_encoder class JSONEncodedStruct(TypeDecorator): "Represents an immutable structure as a json-encoded string." impl = TEXT def process_bind_param(self, value, dialect): if value is not None: value = json.dumps(value, default=json_encoder) return value def process_result_value(self, value, dialect): if value is not None: value = json.loads(value) return value class MutableDict(Mutable, dict): @classmethod def coerce(cls, key, value): "Convert plain dictionaries to MutableDict." if not isinstance(value, MutableDict): if isinstance(value, dict): return MutableDict(value) # this call will raise ValueError return Mutable.coerce(key, value) else: return value def __setitem__(self, key, value): "Detect dictionary set events and emit change events." dict.__setitem__(self, key, value) self.changed() def __delitem__(self, key): "Detect dictionary del events and emit change events." dict.__delitem__(self, key) self.changed() class MutableList(Mutable, list): @classmethod def coerce(cls, key, value): "Convert plain lists to MutableList." if not isinstance(value, MutableList): if isinstance(value, list): return MutableList(value) # this call will raise ValueError return Mutable.coerce(key, value) else: return value def __setitem__(self, key, value): "Detect set events and emit change events." list.__setitem__(self, key, value) self.changed() def __delitem__(self, key): "Detect del events and emit change events." list.__delitem__(self, key) self.changed() def append(self, value): "Detect append events and emit change events." list.append(self, value) self.changed()
mit
smellyriver/tankinspector
TankInspector/Modeling/Tank/BadRoadsKingSkill.cs
1568
namespace Smellyriver.TankInspector.Modeling { internal class BadRoadsKingSkill : CrewSkill { public const string SkillDomain = "crewSkill:badRoadsKing"; public const string SoftGroundResistanceFactorDecrementSkillKey = "softGroundResistanceFactorDecrement"; public const string MediumGroundResistanceFactorDecrementSkillKey = "mediumGroundResistanceFactorDecrement"; public override DuplicatedCrewSkillPolicy DuplicatedCrewSkillPolicy => DuplicatedCrewSkillPolicy.Highest; protected override CrewSkillType Type => CrewSkillType.Skill; public override CrewRoleType CrewRole => CrewRoleType.Driver; public override string[] EffectiveDomains => new[] { SkillDomain }; public BadRoadsKingSkill(Database database) : base(database) { } protected override void Execute(ModificationContext context, double level) { context.SetValue(this.EffectiveDomains[0], SoftGroundResistanceFactorDecrementSkillKey, this.Parameters["softGroundResistanceFactorPerLevel"] * level); context.SetValue(this.EffectiveDomains[0], MediumGroundResistanceFactorDecrementSkillKey, this.Parameters["mediumGroundResistanceFactorPerLevel"] * level); } protected override void Clear(ModificationContext context) { context.SetValue(this.EffectiveDomains[0], SoftGroundResistanceFactorDecrementSkillKey, 0); context.SetValue(this.EffectiveDomains[0], MediumGroundResistanceFactorDecrementSkillKey, 0); } } }
mit
linyu90/leetcode
java/src/single_element_in_a_sorted_array/Solution1.java
1689
package single_element_in_a_sorted_array; /** * Solution to LeetCode problem * <a href="https://leetcode.com/problems/single-element-in-a-sorted-array/#/description"> * "Single Element in a Sorted Array"</a> * * <h4>Problem Description</h4> * <p> * Given a sorted array of integers where every element appears twice except for one that appears * once. Find this single element. * <p> * Example 1:<br> * Input: [1,1,2,3,3,4,4,8,8]<br> * Output: 2<br> * <p> * Example 2:<br> * Input: [3,3,7,7,10,11,11]<br> * Output: 10<br> */ public class Solution1 { private static boolean isEqualToLeftNeighbor(int[] nums, int index) { return index - 1 >= 0 && nums[index] == nums[index - 1]; } private static boolean isEqualToRightNeighbor(int[] nums, int index) { return index + 1 < nums.length && nums[index] == nums[index + 1]; } private static boolean isDuplicateElement(int[] nums, int index) { return isEqualToLeftNeighbor(nums, index) || isEqualToRightNeighbor(nums, index); } public int singleNonDuplicate(int[] nums) { assert nums != null && nums.length > 0; int low = 0; int high = nums.length - 1; while (low <= high) { int mid = low + (high - low) / 2; if (!isDuplicateElement(nums, mid)) { return nums[mid]; } int numSmallerElements = isEqualToLeftNeighbor(nums, mid) ? mid - 1 : mid; if ((numSmallerElements & 0x01) != 0) { // numSmallerElements is odd high = isEqualToLeftNeighbor(nums, mid) ? mid - 2 : mid - 1; } else { low = isEqualToRightNeighbor(nums, mid) ? mid + 2 : mid + 1; } } throw new IllegalArgumentException("Invalid Input"); } }
mit
fluentdesk/fluentCV
dist/generators/xml-generator.js
493
(function() { /** Definition of the XMLGenerator class. @license MIT. See LICENSE.md for details. @module generatprs/xml-generator */ var BaseGenerator, XMLGenerator; BaseGenerator = require('./base-generator'); /** The XmlGenerator generates an XML resume via the TemplateGenerator. */ module.exports = XMLGenerator = class XMLGenerator extends BaseGenerator { constructor() { super('xml'); } }; }).call(this); //# sourceMappingURL=xml-generator.js.map
mit
pltod/hb-nodejs-2014
week2/task3/server.js
2204
var debug = require('debug')('geo-server'); var _ = require('underscore'); var config = require('./config.json'); var url = 'mongodb://' + config.server + ":" + config.port + "/" + config.defaultDatabase; var mongo = require('mongodb'); var express = require("express"); var bodyParser = require('body-parser'); var app = express(); app.all("*", function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", ["X-Requested-With", "Content-Type", "Access-Control-Allow-Methods"]); res.header("Access-Control-Allow-Methods", ["GET"]); next(); }); app.use( bodyParser.json() ); app.use(bodyParser.urlencoded({ extended: true })); app.get("/locations", function(req, res) { debug('Getting locations with...'); var c = app.db.collection(config.defaultCollection); var lng = parseFloat(req.query.position.lng); debug('Longitude: ' + lng); var lat = parseFloat(req.query.position.lat); debug('Latitude: ' + lat); var data = c.find( { loc: { $nearSphere: { $geometry: { type : "Point", coordinates : [lng, lat] }, $maxDistance: req.query.range * 1000 } } } ).toArray(function (err, docs) { var validLocs = []; if (err) { res.json('KO') } else { debug('Found locations: '); debug(docs); docs.forEach(function (doc) { if (_.intersection(req.query.tags, doc.tags).length > 0) { validLocs.push(doc); } }) res.json(validLocs); } }); }); app.post("/locations", function(req, res) { debug('Saving location with...'); debug('Longitude: ' + req.body.position.lng); debug('Latitude: ' + req.body.position.lat); var item = { "name": req.body.name, "loc" : { "type": "Point", "coordinates": [ req.body.position.lng, req.body.position.lat ] }, "tags": req.body.tags, } var c = app.db.collection(config.defaultCollection); c.insert(item, function (err, result) { err ? res.json('KO') : res.json(result) }); }); mongo.connect(url, function (err, db) { app.db = db; app.listen(8000); })
mit
perspicapps/toolbox
PA.SimiliBrowser/Extensibility/IDocumentHandler.cs
319
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.IO; using System.Linq; using System.Text; namespace PA.SimiliBrowser { [InheritedExport] public interface IDocumentHandler { void Load(StreamReader data, Action<Uri, string[]> Submit); } }
mit
marcusvetter/yoda-chat
app/header-container/header-container.ts
885
import {Component} from "angular2/core"; @Component({ selector: 'header-container', template: ` <div class="header"> <div class="container"> <h1 class="title">The Yoda-Chat</h1> <p class="description">The fastest chat for humans and Yoda on earth</p> </div> </div>`, styles: [` .header { text-align: center; padding-top: 1rem; background-color: #f9f9f9; } .title { margin-bottom: 0; font-size: 2rem; font-weight: normal; } .description { font-size: 1.3rem; color: #999; } @media (min-width: 40em) { .title { font-size: 3.5rem; } } `] }) export class HeaderContainer { }
mit
CellarHQ/cellarhq.com
model/src/main/generated/com/cellarhq/generated/tables/Glassware.java
6424
/* * This file is generated by jOOQ. */ package com.cellarhq.generated.tables; import com.cellarhq.generated.Indexes; import com.cellarhq.generated.Keys; import com.cellarhq.generated.Public; import com.cellarhq.generated.tables.records.GlasswareRecord; import java.time.LocalDateTime; import java.util.Arrays; import java.util.List; import javax.annotation.processing.Generated; import org.jooq.Field; import org.jooq.ForeignKey; import org.jooq.Index; import org.jooq.JSON; import org.jooq.Name; import org.jooq.Record; import org.jooq.Row10; import org.jooq.Schema; import org.jooq.Table; import org.jooq.TableField; import org.jooq.UniqueKey; import org.jooq.impl.DSL; import org.jooq.impl.TableImpl; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.12.3" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class Glassware extends TableImpl<GlasswareRecord> { private static final long serialVersionUID = 488836462; /** * The reference instance of <code>public.glassware</code> */ public static final Glassware GLASSWARE = new Glassware(); /** * The class holding records for this type */ @Override public Class<GlasswareRecord> getRecordType() { return GlasswareRecord.class; } /** * The column <code>public.glassware.id</code>. */ public final TableField<GlasswareRecord, Long> ID = createField(DSL.name("id"), org.jooq.impl.SQLDataType.BIGINT.nullable(false), this, ""); /** * The column <code>public.glassware.version</code>. */ public final TableField<GlasswareRecord, Integer> VERSION = createField(DSL.name("version"), org.jooq.impl.SQLDataType.INTEGER.nullable(false).defaultValue(org.jooq.impl.DSL.field("1", org.jooq.impl.SQLDataType.INTEGER)), this, ""); /** * The column <code>public.glassware.name</code>. */ public final TableField<GlasswareRecord, String> NAME = createField(DSL.name("name"), org.jooq.impl.SQLDataType.VARCHAR(100).nullable(false), this, ""); /** * The column <code>public.glassware.description</code>. */ public final TableField<GlasswareRecord, String> DESCRIPTION = createField(DSL.name("description"), org.jooq.impl.SQLDataType.CLOB, this, ""); /** * The column <code>public.glassware.searchable</code>. */ public final TableField<GlasswareRecord, Boolean> SEARCHABLE = createField(DSL.name("searchable"), org.jooq.impl.SQLDataType.BOOLEAN.nullable(false).defaultValue(org.jooq.impl.DSL.field("true", org.jooq.impl.SQLDataType.BOOLEAN)), this, ""); /** * The column <code>public.glassware.brewery_db_id</code>. */ public final TableField<GlasswareRecord, String> BREWERY_DB_ID = createField(DSL.name("brewery_db_id"), org.jooq.impl.SQLDataType.VARCHAR(64), this, ""); /** * The column <code>public.glassware.brewery_db_last_updated</code>. */ public final TableField<GlasswareRecord, LocalDateTime> BREWERY_DB_LAST_UPDATED = createField(DSL.name("brewery_db_last_updated"), org.jooq.impl.SQLDataType.LOCALDATETIME, this, ""); /** * The column <code>public.glassware.created_date</code>. */ public final TableField<GlasswareRecord, LocalDateTime> CREATED_DATE = createField(DSL.name("created_date"), org.jooq.impl.SQLDataType.LOCALDATETIME.nullable(false).defaultValue(org.jooq.impl.DSL.field("now()", org.jooq.impl.SQLDataType.LOCALDATETIME)), this, ""); /** * The column <code>public.glassware.modified_date</code>. */ public final TableField<GlasswareRecord, LocalDateTime> MODIFIED_DATE = createField(DSL.name("modified_date"), org.jooq.impl.SQLDataType.LOCALDATETIME.nullable(false).defaultValue(org.jooq.impl.DSL.field("now()", org.jooq.impl.SQLDataType.LOCALDATETIME)), this, ""); /** * The column <code>public.glassware.data</code>. */ public final TableField<GlasswareRecord, JSON> DATA = createField(DSL.name("data"), org.jooq.impl.SQLDataType.JSON, this, ""); /** * Create a <code>public.glassware</code> table reference */ public Glassware() { this(DSL.name("glassware"), null); } /** * Create an aliased <code>public.glassware</code> table reference */ public Glassware(String alias) { this(DSL.name(alias), GLASSWARE); } /** * Create an aliased <code>public.glassware</code> table reference */ public Glassware(Name alias) { this(alias, GLASSWARE); } private Glassware(Name alias, Table<GlasswareRecord> aliased) { this(alias, aliased, null); } private Glassware(Name alias, Table<GlasswareRecord> aliased, Field<?>[] parameters) { super(alias, null, aliased, parameters, DSL.comment("")); } public <O extends Record> Glassware(Table<O> child, ForeignKey<O, GlasswareRecord> key) { super(child, key, GLASSWARE); } @Override public Schema getSchema() { return Public.PUBLIC; } @Override public List<Index> getIndexes() { return Arrays.<Index>asList(Indexes.GLASSWARE_PKEY, Indexes.IDX_GLASSWARE_BREWERY_DB_ID); } @Override public UniqueKey<GlasswareRecord> getPrimaryKey() { return Keys.GLASSWARE_PKEY; } @Override public List<UniqueKey<GlasswareRecord>> getKeys() { return Arrays.<UniqueKey<GlasswareRecord>>asList(Keys.GLASSWARE_PKEY); } @Override public Glassware as(String alias) { return new Glassware(DSL.name(alias), this); } @Override public Glassware as(Name alias) { return new Glassware(alias, this); } /** * Rename this table */ @Override public Glassware rename(String name) { return new Glassware(DSL.name(name), null); } /** * Rename this table */ @Override public Glassware rename(Name name) { return new Glassware(name, null); } // ------------------------------------------------------------------------- // Row10 type methods // ------------------------------------------------------------------------- @Override public Row10<Long, Integer, String, String, Boolean, String, LocalDateTime, LocalDateTime, LocalDateTime, JSON> fieldsRow() { return (Row10) super.fieldsRow(); } }
mit
carls-app/carls
fastlane/actions/set_gradle_version_code.rb
1682
# coding: utf-8 require 'tempfile' require 'fileutils' module Fastlane module Actions class SetGradleVersionCodeAction < Action def self.run(params) gradle_path = params[:gradle_path] old_version_code = '0' new_version_code = params[:version_code] temp_file = Tempfile.new('fastlaneIncrementVersionCode') File.foreach(gradle_path) do |line| if line.include? 'versionCode ' old_version_code = line.strip.split(' ')[1] line = line.sub(old_version_code, new_version_code.to_s) end temp_file.puts line end temp_file.rewind temp_file.close FileUtils.mv(temp_file.path, gradle_path) temp_file.unlink if old_version_code == '0' UI.user_error!("Could not find the version code in #{gradle_path}") else UI.success("#{old_version_code} changed to #{new_version_code}") end new_version_code end def self.description 'Change the version code of your android project.' end def self.authors ['Jérémy TOUDIC', 'Hawken Rives'] end def self.available_options [ FastlaneCore::ConfigItem.new(key: :gradle_path, description: 'The path to the build.gradle file'), FastlaneCore::ConfigItem.new(key: :version_code, description: 'The version to change to', type: Integer), ] end def self.is_supported?(platform) [:android].include?(platform) end end end end
mit
Lincoln-xzc/angular-demo
app/view5/view5.js
1231
/** * Created by MAKS- on 2015/11/3. */ var myApp=angular.module('myApp.view5',['ngRoute']); myApp.config(['$routeProvider',function($routeProvider){ $routeProvider.when('/view5',{ templateUrl:'view5/view5.html', controller:'myController' }); }]); myApp.controller('myController',['$scope',function($scope){ $scope.people=[ { id: 0, name: '乔乐', interest: [ '爬山', '游泳', '旅游', '美食' ] }, { id: 1, name: 'Chris', interest: [ '音乐', '美食', 'Coffee', '看书' ] }, { id: 2, name: '魏瑞', interest: [ '音乐', '电影', '中国好声音', '爸爸去哪了', '非常静距离' ] }, { id: 3, name: '小飞子', interest: [ '游泳', '游戏', '宅家里' ] } ]; }]);
mit
lmpetek/paperclipwin
lib/paperclip/storage/fog.rb
6247
module Paperclip module Storage # fog is a modern and versatile cloud computing library for Ruby. # Among others, it supports Amazon S3 to store your files. In # contrast to the outdated AWS-S3 gem it is actively maintained and # supports multiple locations. # Amazon's S3 file hosting service is a scalable, easy place to # store files for distribution. You can find out more about it at # http://aws.amazon.com/s3 There are a few fog-specific options for # has_attached_file, which will be explained using S3 as an example: # * +fog_credentials+: Takes a Hash with your credentials. For S3, # you can use the following format: # aws_access_key_id: '<your aws_access_key_id>' # aws_secret_access_key: '<your aws_secret_access_key>' # provider: 'AWS' # region: 'eu-west-1' # * +fog_directory+: This is the name of the S3 bucket that will # store your files. Remember that the bucket must be unique across # all of Amazon S3. If the bucket does not exist, Paperclip will # attempt to create it. # * +path+: This is the key under the bucket in which the file will # be stored. The URL will be constructed from the bucket and the # path. This is what you will want to interpolate. Keys should be # unique, like filenames, and despite the fact that S3 (strictly # speaking) does not support directories, you can still use a / to # separate parts of your file name. # * +fog_public+: (optional, defaults to true) Should the uploaded # files be public or not? (true/false) # * +fog_host+: (optional) The fully-qualified domain name (FQDN) # that is the alias to the S3 domain of your bucket, e.g. # 'http://images.example.com'. This can also be used in # conjunction with Cloudfront (http://aws.amazon.com/cloudfront) module Fog def self.extended base begin require 'fog' rescue LoadError => e e.message << " (You may need to install the fog gem)" raise e end unless defined?(Fog) base.instance_eval do unless @options[:url].to_s.match(/^:fog.*url$/) @options[:path] = @options[:path].gsub(/:url/, @options[:url]) @options[:url] = ':fog_public_url' end Paperclip.interpolates(:fog_public_url) do |attachment, style| attachment.public_url(style) end unless Paperclip::Interpolations.respond_to? :fog_public_url end end AWS_BUCKET_SUBDOMAIN_RESTRICTON_REGEX = /^(?:[a-z]|\d(?!\d{0,2}(?:\.\d{1,3}){3}$))(?:[a-z0-9]|\.(?![\.\-])|\-(?![\.])){1,61}[a-z0-9]$/ def exists?(style = default_style) if original_filename !!directory.files.head(path(style)) else false end end def fog_credentials @fog_credentials ||= parse_credentials(@options[:fog_credentials]) end def fog_file @fog_file ||= @options[:fog_file] || {} end def fog_public return @fog_public if defined?(@fog_public) @fog_public = defined?(@options[:fog_public]) ? @options[:fog_public] : true end def flush_writes for style, file in @queued_for_write do log("saving #{path(style)}") retried = false begin directory.files.create(fog_file.merge( :body => file, :key => path(style), :public => fog_public )) rescue Excon::Errors::NotFound raise if retried retried = true directory.save retry end end after_flush_writes # allows attachment to clean up temp files @queued_for_write = {} end def flush_deletes for path in @queued_for_delete do log("deleting #{path}") directory.files.new(:key => path).destroy end @queued_for_delete = [] end # Returns representation of the data of the file assigned to the given # style, in the format most representative of the current storage. def to_file(style = default_style) if @queued_for_write[style] @queued_for_write[style] else body = directory.files.get(path(style)).body filename = path(style) extname = File.extname(filename) basename = File.basename(filename, extname) file = Tempfile.new([basename, extname]) file.binmode file.write(body) file.rewind file end end def public_url(style = default_style) if @options[:fog_host] host = (@options[:fog_host] =~ /%d/) ? @options[:fog_host] % (path(style).hash % 4) : @options[:fog_host] "#{host}/#{path(style)}" else if fog_credentials[:provider] == 'AWS' if @options[:fog_directory].to_s =~ Fog::AWS_BUCKET_SUBDOMAIN_RESTRICTON_REGEX "https://#{@options[:fog_directory]}.s3.amazonaws.com/#{path(style)}" else # directory is not a valid subdomain, so use path style for access "https://s3.amazonaws.com/#{@options[:fog_directory]}/#{path(style)}" end else directory.files.new(:key => path(style)).public_url end end end def parse_credentials(creds) creds = find_credentials(creds).stringify_keys env = Object.const_defined?(:Rails) ? Rails.env : nil (creds[env] || creds).symbolize_keys end private def find_credentials(creds) case creds when File YAML::load(ERB.new(File.read(creds.path)).result) when String, Pathname YAML::load(ERB.new(File.read(creds)).result) when Hash creds else raise ArgumentError, "Credentials are not a path, file, or hash." end end def connection @connection ||= ::Fog::Storage.new(fog_credentials) end def directory @directory ||= connection.directories.new(:key => @options[:fog_directory]) end end end end
mit
SonarSource-VisualStudio/sonarlint-visualstudio
src/TestInfrastructure/Helpers/MoqExtensions.cs
1096
/* * SonarLint for Visual Studio * Copyright (C) 2016-2021 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ namespace SonarLint.VisualStudio.Integration.UnitTests.Helpers { public static class MoqExtensions { public delegate void OutAction<in T1, in T2, in T3, TOut>(T1 arg1, T2 args2, T3 args3, out TOut outVal); } }
mit
aurarad/auroracoin
src/test/sigopcount_tests.cpp
10344
// Copyright (c) 2012-2019 The Bitcoin Core developers // Copyright (c) 2014-2019 The DigiByte Core developers // Copyright (c) 2019-2020 The Auroracoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <consensus/consensus.h> #include <consensus/tx_verify.h> #include <pubkey.h> #include <key.h> #include <script/script.h> #include <script/standard.h> #include <uint256.h> #include <test/setup_common.h> #include <vector> #include <boost/test/unit_test.hpp> // Helpers: static std::vector<unsigned char> Serialize(const CScript& s) { std::vector<unsigned char> sSerialized(s.begin(), s.end()); return sSerialized; } BOOST_FIXTURE_TEST_SUITE(sigopcount_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(GetSigOpCount) { // Test CScript::GetSigOpCount() CScript s1; BOOST_CHECK_EQUAL(s1.GetSigOpCount(false), 0U); BOOST_CHECK_EQUAL(s1.GetSigOpCount(true), 0U); uint160 dummy; s1 << OP_1 << ToByteVector(dummy) << ToByteVector(dummy) << OP_2 << OP_CHECKMULTISIG; BOOST_CHECK_EQUAL(s1.GetSigOpCount(true), 2U); s1 << OP_IF << OP_CHECKSIG << OP_ENDIF; BOOST_CHECK_EQUAL(s1.GetSigOpCount(true), 3U); BOOST_CHECK_EQUAL(s1.GetSigOpCount(false), 21U); CScript p2sh = GetScriptForDestination(ScriptHash(s1)); CScript scriptSig; scriptSig << OP_0 << Serialize(s1); BOOST_CHECK_EQUAL(p2sh.GetSigOpCount(scriptSig), 3U); std::vector<CPubKey> keys; for (int i = 0; i < 3; i++) { CKey k; k.MakeNewKey(true); keys.push_back(k.GetPubKey()); } CScript s2 = GetScriptForMultisig(1, keys); BOOST_CHECK_EQUAL(s2.GetSigOpCount(true), 3U); BOOST_CHECK_EQUAL(s2.GetSigOpCount(false), 20U); p2sh = GetScriptForDestination(ScriptHash(s2)); BOOST_CHECK_EQUAL(p2sh.GetSigOpCount(true), 0U); BOOST_CHECK_EQUAL(p2sh.GetSigOpCount(false), 0U); CScript scriptSig2; scriptSig2 << OP_1 << ToByteVector(dummy) << ToByteVector(dummy) << Serialize(s2); BOOST_CHECK_EQUAL(p2sh.GetSigOpCount(scriptSig2), 3U); } /** * Verifies script execution of the zeroth scriptPubKey of tx output and * zeroth scriptSig and witness of tx input. */ static ScriptError VerifyWithFlag(const CTransaction& output, const CMutableTransaction& input, int flags) { ScriptError error; CTransaction inputi(input); bool ret = VerifyScript(inputi.vin[0].scriptSig, output.vout[0].scriptPubKey, &inputi.vin[0].scriptWitness, flags, TransactionSignatureChecker(&inputi, 0, output.vout[0].nValue), &error); BOOST_CHECK((ret == true) == (error == SCRIPT_ERR_OK)); return error; } /** * Builds a creationTx from scriptPubKey and a spendingTx from scriptSig * and witness such that spendingTx spends output zero of creationTx. * Also inserts creationTx's output into the coins view. */ static void BuildTxs(CMutableTransaction& spendingTx, CCoinsViewCache& coins, CMutableTransaction& creationTx, const CScript& scriptPubKey, const CScript& scriptSig, const CScriptWitness& witness) { creationTx.nVersion = 1; creationTx.vin.resize(1); creationTx.vin[0].prevout.SetNull(); creationTx.vin[0].scriptSig = CScript(); creationTx.vout.resize(1); creationTx.vout[0].nValue = 1; creationTx.vout[0].scriptPubKey = scriptPubKey; spendingTx.nVersion = 1; spendingTx.vin.resize(1); spendingTx.vin[0].prevout.hash = creationTx.GetHash(); spendingTx.vin[0].prevout.n = 0; spendingTx.vin[0].scriptSig = scriptSig; spendingTx.vin[0].scriptWitness = witness; spendingTx.vout.resize(1); spendingTx.vout[0].nValue = 1; spendingTx.vout[0].scriptPubKey = CScript(); AddCoins(coins, CTransaction(creationTx), 0); } BOOST_AUTO_TEST_CASE(GetTxSigOpCost) { // Transaction creates outputs CMutableTransaction creationTx; // Transaction that spends outputs and whose // sig op cost is going to be tested CMutableTransaction spendingTx; // Create utxo set CCoinsView coinsDummy; CCoinsViewCache coins(&coinsDummy); // Create key CKey key; key.MakeNewKey(true); CPubKey pubkey = key.GetPubKey(); // Default flags int flags = SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH; // Multisig script (legacy counting) { CScript scriptPubKey = CScript() << 1 << ToByteVector(pubkey) << ToByteVector(pubkey) << 2 << OP_CHECKMULTISIGVERIFY; // Do not use a valid signature to avoid using wallet operations. CScript scriptSig = CScript() << OP_0 << OP_0; BuildTxs(spendingTx, coins, creationTx, scriptPubKey, scriptSig, CScriptWitness()); // Legacy counting only includes signature operations in scriptSigs and scriptPubKeys // of a transaction and does not take the actual executed sig operations into account. // spendingTx in itself does not contain a signature operation. assert(GetTransactionSigOpCost(CTransaction(spendingTx), coins, flags) == 0); // creationTx contains two signature operations in its scriptPubKey, but legacy counting // is not accurate. assert(GetTransactionSigOpCost(CTransaction(creationTx), coins, flags) == MAX_PUBKEYS_PER_MULTISIG * WITNESS_SCALE_FACTOR); // Sanity check: script verification fails because of an invalid signature. assert(VerifyWithFlag(CTransaction(creationTx), spendingTx, flags) == SCRIPT_ERR_CHECKMULTISIGVERIFY); } // Multisig nested in P2SH { CScript redeemScript = CScript() << 1 << ToByteVector(pubkey) << ToByteVector(pubkey) << 2 << OP_CHECKMULTISIGVERIFY; CScript scriptPubKey = GetScriptForDestination(ScriptHash(redeemScript)); CScript scriptSig = CScript() << OP_0 << OP_0 << ToByteVector(redeemScript); BuildTxs(spendingTx, coins, creationTx, scriptPubKey, scriptSig, CScriptWitness()); assert(GetTransactionSigOpCost(CTransaction(spendingTx), coins, flags) == 2 * WITNESS_SCALE_FACTOR); assert(VerifyWithFlag(CTransaction(creationTx), spendingTx, flags) == SCRIPT_ERR_CHECKMULTISIGVERIFY); } // P2WPKH witness program { CScript p2pk = CScript() << ToByteVector(pubkey) << OP_CHECKSIG; CScript scriptPubKey = GetScriptForWitness(p2pk); CScript scriptSig = CScript(); CScriptWitness scriptWitness; scriptWitness.stack.push_back(std::vector<unsigned char>(0)); scriptWitness.stack.push_back(std::vector<unsigned char>(0)); BuildTxs(spendingTx, coins, creationTx, scriptPubKey, scriptSig, scriptWitness); assert(GetTransactionSigOpCost(CTransaction(spendingTx), coins, flags) == 1); // No signature operations if we don't verify the witness. assert(GetTransactionSigOpCost(CTransaction(spendingTx), coins, flags & ~SCRIPT_VERIFY_WITNESS) == 0); assert(VerifyWithFlag(CTransaction(creationTx), spendingTx, flags) == SCRIPT_ERR_EQUALVERIFY); // The sig op cost for witness version != 0 is zero. assert(scriptPubKey[0] == 0x00); scriptPubKey[0] = 0x51; BuildTxs(spendingTx, coins, creationTx, scriptPubKey, scriptSig, scriptWitness); assert(GetTransactionSigOpCost(CTransaction(spendingTx), coins, flags) == 0); scriptPubKey[0] = 0x00; BuildTxs(spendingTx, coins, creationTx, scriptPubKey, scriptSig, scriptWitness); // The witness of a coinbase transaction is not taken into account. spendingTx.vin[0].prevout.SetNull(); assert(GetTransactionSigOpCost(CTransaction(spendingTx), coins, flags) == 0); } // P2WPKH nested in P2SH { CScript p2pk = CScript() << ToByteVector(pubkey) << OP_CHECKSIG; CScript scriptSig = GetScriptForWitness(p2pk); CScript scriptPubKey = GetScriptForDestination(ScriptHash(scriptSig)); scriptSig = CScript() << ToByteVector(scriptSig); CScriptWitness scriptWitness; scriptWitness.stack.push_back(std::vector<unsigned char>(0)); scriptWitness.stack.push_back(std::vector<unsigned char>(0)); BuildTxs(spendingTx, coins, creationTx, scriptPubKey, scriptSig, scriptWitness); assert(GetTransactionSigOpCost(CTransaction(spendingTx), coins, flags) == 1); assert(VerifyWithFlag(CTransaction(creationTx), spendingTx, flags) == SCRIPT_ERR_EQUALVERIFY); } // P2WSH witness program { CScript witnessScript = CScript() << 1 << ToByteVector(pubkey) << ToByteVector(pubkey) << 2 << OP_CHECKMULTISIGVERIFY; CScript scriptPubKey = GetScriptForWitness(witnessScript); CScript scriptSig = CScript(); CScriptWitness scriptWitness; scriptWitness.stack.push_back(std::vector<unsigned char>(0)); scriptWitness.stack.push_back(std::vector<unsigned char>(0)); scriptWitness.stack.push_back(std::vector<unsigned char>(witnessScript.begin(), witnessScript.end())); BuildTxs(spendingTx, coins, creationTx, scriptPubKey, scriptSig, scriptWitness); assert(GetTransactionSigOpCost(CTransaction(spendingTx), coins, flags) == 2); assert(GetTransactionSigOpCost(CTransaction(spendingTx), coins, flags & ~SCRIPT_VERIFY_WITNESS) == 0); assert(VerifyWithFlag(CTransaction(creationTx), spendingTx, flags) == SCRIPT_ERR_CHECKMULTISIGVERIFY); } // P2WSH nested in P2SH { CScript witnessScript = CScript() << 1 << ToByteVector(pubkey) << ToByteVector(pubkey) << 2 << OP_CHECKMULTISIGVERIFY; CScript redeemScript = GetScriptForWitness(witnessScript); CScript scriptPubKey = GetScriptForDestination(ScriptHash(redeemScript)); CScript scriptSig = CScript() << ToByteVector(redeemScript); CScriptWitness scriptWitness; scriptWitness.stack.push_back(std::vector<unsigned char>(0)); scriptWitness.stack.push_back(std::vector<unsigned char>(0)); scriptWitness.stack.push_back(std::vector<unsigned char>(witnessScript.begin(), witnessScript.end())); BuildTxs(spendingTx, coins, creationTx, scriptPubKey, scriptSig, scriptWitness); assert(GetTransactionSigOpCost(CTransaction(spendingTx), coins, flags) == 2); assert(VerifyWithFlag(CTransaction(creationTx), spendingTx, flags) == SCRIPT_ERR_CHECKMULTISIGVERIFY); } } BOOST_AUTO_TEST_SUITE_END()
mit
pixelballoon/pixelboost
engine/src/platform/android/pixelboost/file/fileHelpers.cpp
1247
#ifdef PIXELBOOST_PLATFORM_ANDROID #include "pixelboost/file/fileHelpers.h" #include "pixelboost/misc/jni.h" using namespace pb; std::string pb::FileHelpers::GetBundlePath() { JNIEnv* env = Jni::GetJniEnv(); jclass classId = env->FindClass("com/pixelballoon/pixelboost/PixelboostHelpers"); jmethodID methodId = env->GetStaticMethodID(classId, "getBundleFilePath", "()Ljava/lang/String;"); jstring result = static_cast<jstring>(env->CallStaticObjectMethod(classId, methodId)); const char *nativeString = env->GetStringUTFChars(result, 0); std::string savePath = nativeString; env->ReleaseStringUTFChars(result, nativeString); return savePath; } std::string pb::FileHelpers::GetSavePath() { JNIEnv* env = Jni::GetJniEnv(); jclass classId = env->FindClass("com/pixelballoon/pixelboost/PixelboostHelpers"); jmethodID methodId = env->GetStaticMethodID(classId, "getSaveFilePath", "()Ljava/lang/String;"); jstring result = static_cast<jstring>(env->CallStaticObjectMethod(classId, methodId)); const char *nativeString = env->GetStringUTFChars(result, 0); std::string savePath = nativeString; env->ReleaseStringUTFChars(result, nativeString); return savePath; } #endif
mit
gl-vis/gl-mesh3d
example/flat.js
2371
var createCamera = require('3d-view-controls') var getBounds = require('bound-points') var bunny = require('bunny') var perspective = require('gl-mat4/perspective') var createAxes = require('gl-axes3d') var createSpikes = require('gl-spikes3d') var createSelect = require('gl-select-static') var getBounds = require('bound-points') var mouseChange = require('mouse-change') var createMesh = require('../mesh') var canvas = document.createElement('canvas') document.body.appendChild(canvas) window.addEventListener('resize', require('canvas-fit')(canvas)) var gl = canvas.getContext('webgl') var ext = ( gl.getExtension('OES_standard_derivatives') ) var bounds = getBounds(bunny.positions) var camera = createCamera(canvas, { eye: [0,0,50], center: [-0.5*(bounds[0][0]+bounds[1][0]), -0.5*(bounds[0][1]+bounds[1][1]), -0.5*(bounds[0][2]+bounds[1][2])], zoomMax: 500 }) var mesh = createMesh(gl, { cells: bunny.cells, positions: bunny.positions, meshColor: [1, 0, 0], useFacetNormals: true, specular: 5. }) var select = createSelect(gl, [canvas.width, canvas.height]) var axes = createAxes(gl, { bounds: bounds }) var spikes = createSpikes(gl, { bounds: bounds }) var spikeChanged = false mouseChange(canvas, function(buttons, x, y) { var pickData = select.query(x, canvas.height - y, 10) var pickResult = mesh.pick(pickData) if(pickResult) { spikes.update({ position: pickResult.position, enabled: [true, true, true] }) spikeChanged = true } else { spikeChanged = spikes.enabled[0] spikes.update({ enabled: [false, false, false] }) } }) function render() { requestAnimationFrame(render) gl.enable(gl.DEPTH_TEST) var needsUpdate = camera.tick() var cameraParams = { projection: perspective([], Math.PI/4, canvas.width/canvas.height, 0.01, 1000), view: camera.matrix } if(needsUpdate || spikeChanged) { gl.bindFramebuffer(gl.FRAMEBUFFER, null) gl.viewport(0, 0, canvas.width, canvas.height) gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT) axes.draw(cameraParams) spikes.draw(cameraParams) mesh.draw(cameraParams) spikeChanged = false } if(needsUpdate) { select.shape = [canvas.width, canvas.height] select.begin() mesh.drawPick(cameraParams) select.end() } } render()
mit
xamarinhq/app-evolve
src/Conference.Clients.UI/Pages/Sessions/SessionDetailsPage.xaml.cs
3779
using System; using System.Collections.Generic; using Xamarin.Forms; using Conference.DataObjects; using Conference.Clients.Portable; using FormsToolkit; namespace Conference.Clients.UI { public partial class SessionDetailsPage : ContentPage { SessionDetailsViewModel ViewModel => vm ?? (vm = BindingContext as SessionDetailsViewModel); SessionDetailsViewModel vm; public SessionDetailsPage(Session session) { InitializeComponent(); FavoriteButtonAndroid.Clicked += (sender, e) => { Device.BeginInvokeOnMainThread (() => FavoriteIconAndroid.Grow ()); }; FavoriteButtoniOS.Clicked += (sender, e) => { Device.BeginInvokeOnMainThread (() => FavoriteIconiOS.Grow ()); }; ListViewSpeakers.ItemSelected += async (sender, e) => { var speaker = ListViewSpeakers.SelectedItem as Speaker; if(speaker == null) return; var speakerDetails = new SpeakerDetailsPage(vm.Session.Id); speakerDetails.Speaker = speaker; App.Logger.TrackPage(AppPage.Speaker.ToString(), speaker.FullName); await NavigationService.PushAsync(Navigation, speakerDetails); ListViewSpeakers.SelectedItem = null; }; ButtonRate.Clicked += async (sender, e) => { if(!Settings.Current.IsLoggedIn) { DependencyService.Get<ILogger>().TrackPage(AppPage.Login.ToString(), "Feedback"); MessagingService.Current.SendMessage(MessageKeys.NavigateLogin); return; } await NavigationService.PushModalAsync(Navigation, new ConferenceNavigationPage(new FeedbackPage(ViewModel.Session))); }; BindingContext = new SessionDetailsViewModel(Navigation, session); ViewModel.LoadSessionCommand.Execute(null); } void ListViewTapped (object sender, ItemTappedEventArgs e) { var list = sender as ListView; if (list == null) return; list.SelectedItem = null; } void MainScroll_Scrolled (object sender, ScrolledEventArgs e) { if (e.ScrollY > SessionDate.Y) Title = ViewModel.Session.ShortTitle; else Title = "Session Details"; } protected override void OnAppearing() { base.OnAppearing(); MainScroll.Scrolled += MainScroll_Scrolled; ListViewSpeakers.ItemTapped += ListViewTapped; //if(Device.RuntimePlatform == Device.Android || Device.RuntimePlatform == Device.iOS) //Application.Current.AppLinks.RegisterLink(ViewModel.Session.GetAppLink()); var count = ViewModel?.Session?.Speakers?.Count ?? 0; var adjust = Device.RuntimePlatform != Device.Android ? 1 : -count + 1; if((ViewModel?.Session?.Speakers?.Count ?? 0) > 0) ListViewSpeakers.HeightRequest = (count * ListViewSpeakers.RowHeight) - adjust; } protected override void OnDisappearing() { base.OnDisappearing(); MainScroll.Scrolled -= MainScroll_Scrolled; ListViewSpeakers.ItemTapped -= ListViewTapped; } protected override void OnBindingContextChanged() { base.OnBindingContextChanged(); vm = null; ListViewSpeakers.HeightRequest = 0; } } }
mit
zzwwws/RxZhihuDaily
app/src/main/java/com/github/zzwwws/rxzhihudaily/model/entities/Story.java
3713
package com.github.zzwwws.rxzhihudaily.model.entities; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "images", "type", "id", "ga_prefix", "title", "multipic" }) public class Story { @JsonProperty("images") private List<String> images = new ArrayList<String>(); @JsonProperty("type") private Integer type; @JsonProperty("id") private Integer id; @JsonProperty("ga_prefix") private String gaPrefix; @JsonProperty("title") private String title; @JsonProperty("date") private String date; @JsonProperty("multipic") private Boolean multipic; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); /** * * @return * The images */ @JsonProperty("images") public List<String> getImages() { return images; } /** * * @param images * The images */ @JsonProperty("images") public void setImages(List<String> images) { this.images = images; } /** * * @return * The type */ @JsonProperty("type") public Integer getType() { return type; } /** * * @param type * The type */ @JsonProperty("type") public void setType(Integer type) { this.type = type; } /** * * @return * The id */ @JsonProperty("id") public Integer getId() { return id; } /** * * @param id * The id */ @JsonProperty("id") public void setId(Integer id) { this.id = id; } /** * * @return * The gaPrefix */ @JsonProperty("ga_prefix") public String getGaPrefix() { return gaPrefix; } /** * * @param gaPrefix * The ga_prefix */ @JsonProperty("ga_prefix") public void setGaPrefix(String gaPrefix) { this.gaPrefix = gaPrefix; } /** * * @return * The title */ @JsonProperty("title") public String getTitle() { return title; } /** * * @param title * The title */ @JsonProperty("title") public void setTitle(String title) { this.title = title; } /** * * @return * The title */ @JsonProperty("date") public String getDate() { return date; } /** * * @param date * The title */ @JsonProperty("date") public void setDate(String date) { this.date = date; } /** * * @return * The multipic */ @JsonProperty("multipic") public Boolean getMultipic() { return multipic == null?false:multipic; } /** * * @param multipic * The multipic */ @JsonProperty("multipic") public void setMultipic(Boolean multipic) { this.multipic = multipic; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } }
mit
tkopacz/2016NetCoreWebApiOneDriveBusiness
2016MT45/2016MT45WebApi/Models/ApplicationDbContext.cs
683
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Data.Entity; using System.Linq; using System.Web; namespace _2016MT45WebApi.Models { public class ApplicationDbContext : DbContext { public ApplicationDbContext() : base("DefaultConnection") { } public DbSet<UserTokenCache> UserTokenCacheList { get; set; } } public class UserTokenCache { [Key] public int UserTokenCacheId { get; set; } public string webUserUniqueId { get; set; } public byte[] cacheBits { get; set; } public DateTime LastWrite { get; set; } } }
mit
asterissco/Silvanus
src/Silvanus/ChainsBundle/Form/ChainType.php
1668
<?php namespace Silvanus\ChainsBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; //~ use Symfony\Component\Form\CallbackValidator; //~ use Symfony\Component\Form\FormError; //~ use Symfony\Component\Form\FormInterface; class ChainType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('name') ->add('active') ->add('host') ->add('trusted') ->add('type','choice',array( 'label' => 'Chain type', 'required'=>true, 'choices'=>array( 'normal' => 'Normal', 'stack' => 'Stack', 'prototype' => 'Prototype', ) )); //~ //~ //validacion de campos de este tipo //~ $builder->addEventListener("error",new CallbackValidator(function(FormInterface $form) { //~ //~ //~ if(!preg_match("[^/?*:;{}\\]+\\.[^/?*:;{}\\]+",$form['name'])){ //~ //~ $form['name']->addError(new FormError('File name without spaces and /')); //~ //~ } //~ //~ })); } /** * @param OptionsResolverInterface $resolver */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'Silvanus\ChainsBundle\Entity\Chain' )); } /** * @return string */ public function getName() { return 'silvanus_chainsbundle_chaintype'; } }
mit
tinyhan/voyager_demo
src/Http/Controllers/VoyagerBreadController.php
8024
<?php namespace TCG\Voyager\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use TCG\Voyager\Models\DataType; use TCG\Voyager\Voyager; class VoyagerBreadController extends Controller { //*************************************** // ____ // | _ \ // | |_) | // | _ < // | |_) | // |____/ // // Browse our Data Type (B)READ // //**************************************** public function index(Request $request) { // GET THE SLUG, ex. 'posts', 'pages', etc. $slug = $this->getSlug($request); // GET THE DataType based on the slug $dataType = DataType::where('slug', '=', $slug)->first(); // Check permission Voyager::can('browse_'.$dataType->name); $getter = $dataType->server_side ? 'paginate' : 'get'; // Next Get or Paginate the actual content from the MODEL that corresponds to the slug DataType if (strlen($dataType->model_name) != 0) { $model = app($dataType->model_name); if ($model->timestamps) { $dataTypeContent = call_user_func([$model->latest(), $getter]); } else { $dataTypeContent = call_user_func([$model->orderBy('id', 'DESC'), $getter]); } } else { // If Model doesn't exist, get data from table name $dataTypeContent = call_user_func([DB::table($dataType->name), $getter]); } $view = 'voyager::bread.browse'; if (view()->exists("voyager::$slug.browse")) { $view = "voyager::$slug.browse"; } return view($view, compact('dataType', 'dataTypeContent')); } //*************************************** // _____ // | __ \ // | |__) | // | _ / // | | \ \ // |_| \_\ // // Read an item of our Data Type B(R)EAD // //**************************************** public function show(Request $request, $id) { $slug = $this->getSlug($request); $dataType = DataType::where('slug', '=', $slug)->first(); // Check permission Voyager::can('read_'.$dataType->name); $dataTypeContent = (strlen($dataType->model_name) != 0) ? call_user_func([$dataType->model_name, 'findOrFail'], $id) : DB::table($dataType->name)->where('id', $id)->first(); // If Model doest exist, get data from table name $view = 'voyager::bread.read'; if (view()->exists("voyager::$slug.read")) { $view = "voyager::$slug.read"; } return view($view, compact('dataType', 'dataTypeContent')); } //*************************************** // ______ // | ____| // | |__ // | __| // | |____ // |______| // // Edit an item of our Data Type BR(E)AD // //**************************************** public function edit(Request $request, $id) { $slug = $this->getSlug($request); $dataType = DataType::where('slug', '=', $slug)->first(); // Check permission Voyager::can('edit_'.$dataType->name); $dataTypeContent = (strlen($dataType->model_name) != 0) ? call_user_func([$dataType->model_name, 'findOrFail'], $id) : DB::table($dataType->name)->where('id', $id)->first(); // If Model doest exist, get data from table name $view = 'voyager::bread.edit-add'; if (view()->exists("voyager::$slug.edit-add")) { $view = "voyager::$slug.edit-add"; } return view($view, compact('dataType', 'dataTypeContent')); } // POST BR(E)AD public function update(Request $request, $id) { $slug = $this->getSlug($request); $dataType = DataType::where('slug', '=', $slug)->first(); // Check permission Voyager::can('edit_'.$dataType->name); $data = call_user_func([$dataType->model_name, 'findOrFail'], $id); $this->insertUpdateData($request, $slug, $dataType->editRows, $data); return redirect() ->route("voyager.{$dataType->slug}.index") ->with([ 'message' => "Successfully Updated {$dataType->display_name_singular}", 'alert-type' => 'success', ]); } //*************************************** // // /\ // / \ // / /\ \ // / ____ \ // /_/ \_\ // // // Add a new item of our Data Type BRE(A)D // //**************************************** public function create(Request $request) { $slug = $this->getSlug($request); $dataType = DataType::where('slug', '=', $slug)->first(); // Check permission Voyager::can('add_'.$dataType->name); $view = 'voyager::bread.edit-add'; if (view()->exists("voyager::$slug.edit-add")) { $view = "voyager::$slug.edit-add"; } return view($view, compact('dataType')); } // POST BRE(A)D public function store(Request $request) { $slug = $this->getSlug($request); $dataType = DataType::where('slug', '=', $slug)->first(); // Check permission Voyager::can('add_'.$dataType->name); if (function_exists('voyager_add_post')) { $url = $request->url(); voyager_add_post($request); } $data = new $dataType->model_name(); $this->insertUpdateData($request, $slug, $dataType->addRows, $data); return redirect() ->route("voyager.{$dataType->slug}.index") ->with([ 'message' => "Successfully Added New {$dataType->display_name_singular}", 'alert-type' => 'success', ]); } //*************************************** // _____ // | __ \ // | | | | // | | | | // | |__| | // |_____/ // // Delete an item BREA(D) // //**************************************** public function destroy(Request $request, $id) { $slug = $this->getSlug($request); $dataType = DataType::where('slug', '=', $slug)->first(); // Check permission Voyager::can('delete_'.$dataType->name); $data = call_user_func([$dataType->model_name, 'findOrFail'], $id); foreach ($dataType->deleteRows as $row) { if ($row->type == 'image') { $this->deleteFileIfExists('/uploads/'.$data->{$row->field}); $options = json_decode($row->details); if (isset($options->thumbnails)) { foreach ($options->thumbnails as $thumbnail) { $ext = explode('.', $data->{$row->field}); $extension = '.'.$ext[count($ext) - 1]; $path = str_replace($extension, '', $data->{$row->field}); $thumb_name = $thumbnail->name; $this->deleteFileIfExists('/uploads/'.$path.'-'.$thumb_name.$extension); } } } } $data = $data->destroy($id) ? [ 'message' => "Successfully Deleted {$dataType->display_name_singular}", 'alert-type' => 'success', ] : [ 'message' => "Sorry it appears there was a problem deleting this {$dataType->display_name_singular}", 'alert-type' => 'error', ]; return redirect()->route("voyager.{$dataType->slug}.index")->with($data); } }
mit
celluloid/celluloid
lib/celluloid/supervision/container/behavior/pool.rb
2053
require "set" module Celluloid module ClassMethods extend Forwardable def_delegators :"Celluloid::Supervision::Container::Pool", :pooling_options # Create a new pool of workers. Accepts the following options: # # * size: how many workers to create. Default is worker per CPU core # * args: array of arguments to pass when creating a worker # def pool(config = {}, &block) _ = Celluloid.supervise(pooling_options(config, block: block, actors: self)) _.actors.last end # Same as pool, but links to the pool manager def pool_link(klass, config = {}, &block) Supervision::Container::Pool.new_link(pooling_options(config, block: block, actors: klass)) end end module Supervision class Container extend Forwardable def_delegators :"Celluloid::Supervision::Container::Pool", :pooling_options def pool(klass, config = {}, &block) _ = supervise(pooling_options(config, block: block, actors: klass)) _.actors.last end class Instance attr_accessor :pool, :pool_size end class << self # Register a pool of actors to be launched on group startup def pool(klass, config, &block) blocks << lambda do |container| container.pool(klass, config, &block) end end end class Pool include Behavior class << self def pooling_options(config = {}, mixins = {}) combined = { type: Celluloid::Supervision::Container::Pool }.merge(config).merge(mixins) combined[:args] = [%i[block actors size args].each_with_object({}) do |p, e| e[p] = combined.delete(p) if combined[p] end] combined end end identifier! :size, :pool configuration do @supervisor = Container::Pool @method = "pool_link" @pool = true @pool_size = @configuration[:size] @configuration end end end end end
mit
dantin/leetcode-solutions
java/DifferentWaysToAddParentheses.java
1408
import java.util.List; import java.util.LinkedList; public class DifferentWaysToAddParentheses { public List<Integer> diffWaysToCompute(String input) { List<Integer> ans = new LinkedList<>(); for (int i = 0; i < input.length(); i++) { char ch = input.charAt(i); if (ch == '+' || ch == '-' || ch == '*') { List<Integer> left = diffWaysToCompute(input.substring(0, i)); List<Integer> right = diffWaysToCompute(input.substring(i + 1)); for (int l : left) { for (int r : right) { switch (ch) { case '+': ans.add(l + r); break; case '-': ans.add(l - r); break; case '*': ans.add(l * r); break; } } } } } if (ans.size() == 0) { ans.add(Integer.parseInt(input)); } return ans; } public static void main(String[] args) { String input = "2*3-4*5"; DifferentWaysToAddParentheses solution = new DifferentWaysToAddParentheses(); System.out.println(solution.diffWaysToCompute(input)); } }
mit
logger-app/logger-app
server.babel.js
339
// enable runtime transpilation to use ES6/7 in node /* eslint no-var:0 */ var fs = require('fs'); var babelrc = fs.readFileSync('./.babelrc'); var config; try { config = JSON.parse(babelrc); } catch (err) { console.error('==> ERROR: Error parsing your .babelrc.'); console.error(err); } require('babel-register')(config);
mit
InfernoEngine/engine
dev/src/base/memory/src/poolID.cpp
4935
/*** * Inferno Engine v4 2015-2017 * Written by Tomasz "Rex Dex" Jonarski * * [#filter: allocator\id #] ***/ #include "build.h" #include "poolID.h" namespace base { namespace mem { namespace prv { // registry of pool names class PoolRegistry : public base::NoCopy { public: PoolRegistry() : m_numRegisteredNames(0) { // prepare name table memset(&m_names, 0, sizeof(m_names)); // setup static pool names m_numRegisteredNames += setPoolName(POOL_DEFAULT, "Engine.Default"); m_numRegisteredNames += setPoolName(POOL_CONTAINERS, "Engine.Containers"); m_numRegisteredNames += setPoolName(POOL_IO, "Engine.IO"); m_numRegisteredNames += setPoolName(POOL_RTTI, "Engine.RTTI"); m_numRegisteredNames += setPoolName(POOL_SCRIPTS, "Engine.Scripts"); m_numRegisteredNames += setPoolName(POOL_NET, "Engine.Network"); m_numRegisteredNames += setPoolName(POOL_IMAGE, "Engine.Images"); m_numRegisteredNames += setPoolName(POOL_STRINGS, "Engine.Strings"); m_numRegisteredNames += setPoolName(POOL_PAGE_RETENTION, "Engine.PageRetention"); m_numRegisteredNames += setPoolName(POOL_NEW, "Engine.NewDelete"); m_numRegisteredNames += setPoolName(POOL_TEMP, "Engine.Temp"); m_numRegisteredNames += setPoolName(POOL_PTR, "Engine.Pointers"); m_numRegisteredNames += setPoolName(POOL_OBJECTS, "Engine.Objects"); m_numRegisteredNames += setPoolName(POOL_RESOURCES, "Engine.Resources"); m_numRegisteredNames += setPoolName(POOL_MEM_BUFFER, "Engine.MemBuffers"); m_numRegisteredNames += setPoolName(POOL_DATA_BUFFER, "Engine.DataBuffers"); m_numRegisteredNames += setPoolName(POOL_ASYNC_BUFFER, "Engine.AsyncBuffers"); } // get name of the pool FORCEINLINE const AnsiChar* getName(PoolIDValue value) { if (value < m_numRegisteredNames) return m_names[value]; return "UNKNOWN"; } // find/register a pool by name FORCEINLINE PoolIDValue registerPool(const AnsiChar* name) { // fallback to default pool on overflow if (m_numRegisteredNames == MAX_POOLS) return 0; // allocate entry auto newID = range_cast<PoolIDValue>(m_numRegisteredNames++); setPoolName(newID, name); return newID; } // register a pool name under ID FORCEINLINE Uint32 setPoolName(const PoolIDValue id, const AnsiChar* name) { m_names[id] = name; m_hashes[id] = CalcHash(name); const auto bucket = m_hashes[id] % MAX_BUCKETS; m_buckets[bucket] = id; // NOTE: this may replace previous value, it's fine for now return 1; } // get max registered ID FORCEINLINE PoolIDValue getMax() const { return (PoolIDValue)m_numRegisteredNames; } private: static const Uint32 MAX_POOLS = 256; static const Uint32 MAX_BUCKETS = 1024; const AnsiChar* m_names[MAX_POOLS]; Uint32 m_hashes[MAX_POOLS]; Uint32 m_numRegisteredNames; static FORCEINLINE const Uint32 CalcHash(const AnsiChar* ch) { Uint32 hval = UINT32_C(0x811c9dc5); // FNV-1a while (*ch) { hval ^= (Uint32)*ch++; hval *= UINT32_C(0x01000193); } return hval; } PoolIDValue m_buckets[MAX_BUCKETS]; }; static PoolRegistry ThePoolRegistry; } PoolID::PoolID(const AnsiChar* name) { m_value = prv::ThePoolRegistry.registerPool(name); } const char* PoolID::getName() const { return prv::ThePoolRegistry.getName(m_value); } const AnsiChar* PoolID::GetPoolNameForID(const PoolIDValue id) { return prv::ThePoolRegistry.getName(id); } const PoolIDValue PoolID::GetPoolIDRange() { return prv::ThePoolRegistry.getMax(); } } // mem } // base
mit
ademko/wexus2
wexus2.src/wexus/FileHTTPHandler.cpp
3977
/* * Copyright (c) 2011 Aleksander B. Demko * This source code is distributed under the MIT license. * See the accompanying file LICENSE.MIT.txt for details. */ #include <wexus/FileHTTPHandler.h> #include <wexus/MimeTypes.h> #include <QFile> #include <QFileInfo> #include <QDir> #include <QDebug> using namespace wexus; FileHTTPHandler::FileException::FileException(const QString &usermsg) : Exception("FileException: " + usermsg) { } FileHTTPHandler::FileHTTPHandler(const QString &docdir, int flags) : dm_docdir(docdir), dm_flags(flags) { if (dm_docdir[dm_docdir.size()-1] != '/') dm_docdir += '/'; // always have a / on the end } void FileHTTPHandler::handleRequest(wexus::HTTPRequest &req, wexus::HTTPReply &reply) { const QString &relpath = req.request(); // check the relpath for any . that follow a /, and fail them bool had_slash = false; for (QString::const_iterator ii=relpath.begin(); ii != relpath.end(); ++ii) { if (*ii == '/') had_slash = true; else if (had_slash) { if (*ii == '.') throw FileException("Bad path 1001"); // fail it, potensially bad path had_slash = false; } } processRequest(dm_flags, dm_docdir, relpath, reply); } void FileHTTPHandler::processRequest(int flags, const QString &docdir, const QString &relpath, wexus::HTTPReply &reply) { QString fullpath(docdir + relpath); QFileInfo info(fullpath); qDebug() << "FileHTTPHandler serving " << fullpath; // check if its a dir if (info.isDir()) { QString indexfullpath(fullpath + "/index.html"); QFileInfo indexinfo(indexfullpath); // check if there is a index.html and fall through with that if (flags & IndexHtml && indexinfo.isFile()) { // fall through to file handling below fullpath = indexfullpath; info = indexinfo; } else { // not an indexhtml, see if we need to auto gen if (flags & AutoDirIndex) generateDirIndex(fullpath, relpath, reply); // if were here, that means its a dir but we cant handle it // lets just bail and assume some other handler will take it return; } } // assume its a file if (!info.isFile()) return; QString fileext(info.suffix().toLower()); // check mime type if ((flags & AllowAllMimeTypes) && !MimeTypes::containsMimeType(fileext)) reply.setContentType(MimeTypes::binaryMimeType()); // send binary if I can and don't have a type else reply.setContentType(MimeTypes::mimeType(fileext)); if (!sendFile(fullpath, reply.output().device())) throw FileException("QFile::open failed"); } bool FileHTTPHandler::sendFile(const QString &filename, QIODevice * outputdev) { // open and send the file QFile file(filename); if (!file.open(QIODevice::ReadOnly)) return false; char buf[1024*4]; qint64 num; while ( (num = file.read(buf, sizeof(buf))) > 0) if (num != outputdev->write(buf, num)) throw FileException("QFile::write short-wrote"); return true; } void FileHTTPHandler::generateDirIndex(const QString &fullpath, const QString &relpath, wexus::HTTPReply &reply) { reply.output() << "<h2>Index of: " << relpath << "</h2>\n<UL>\n<LI><A HREF=\"../\">Parent Directory</A></LI><P>\n"; QDir dir(fullpath); QStringList entries(dir.entryList(QDir::Dirs|QDir::Files|QDir::NoDotAndDotDot|QDir::Readable, QDir::DirsFirst|QDir::Name)); for (QStringList::const_iterator ii=entries.begin(); ii != entries.end(); ++ii) { QString curfullpath(fullpath + "/" + *ii); QFileInfo curinfo(curfullpath); bool isdir = curinfo.isDir(); QString escaped(escapeForXML(*ii)); reply.output() << "<LI><A HREF=\"" << escaped; if (isdir) reply.output() << '/'; reply.output() << "\">" << escaped << "</A> "; if (isdir) reply.output() << "(DIRECTORY)"; else reply.output() << (curinfo.size()/1024) << " kbytes"; reply.output() << "</LI>\n"; } reply.output() << "</UL>\n"; }
mit
aspose-note/Aspose.Note-for-.NET
Examples/CSharp/Images/GetInformationOfImages.cs
1655
using System.IO; using Aspose.Note; using System.Collections.Generic; using System; namespace Aspose.Note.Examples.CSharp.Images { public class GetInformationOfImages { public static void Run() { // ExStart:GetInformationOfImages // ExFor:Document // ExFor:CompositeNode`1.GetChildNodes // ExFor:Image // ExFor:Image.Width // ExFor:Image.Height // ExFor:Image.OriginalWidth // ExFor:Image.OriginalHeight // ExFor:Image.FileName // ExFor:Image.LastModifiedTime // ExSummary:Shows how to get image's meta information. // The path to the documents directory. string dataDir = RunExamples.GetDataDir_Images(); // Load the document into Aspose.Note. Document oneFile = new Document(dataDir + "Aspose.one"); // Get all Image nodes IList<Aspose.Note.Image> images = oneFile.GetChildNodes<Aspose.Note.Image>(); foreach (Aspose.Note.Image image in images) { Console.WriteLine("Width: {0}", image.Width); Console.WriteLine("Height: {0}", image.Height); Console.WriteLine("OriginalWidth: {0}", image.OriginalWidth); Console.WriteLine("OriginalHeight: {0}", image.OriginalHeight); Console.WriteLine("FileName: {0}", image.FileName); Console.WriteLine("LastModifiedTime: {0}", image.LastModifiedTime); Console.WriteLine(); } // ExEnd:GetInformationOfImages } } }
mit
okfn-brasil/orcamento.inesc.org.br
app/assets/javascripts/vendor/nv.d3.js
404617
(function(){ var nv = window.nv || {}; nv.version = '0.0.1a'; nv.dev = true //set false when in production window.nv = nv; nv.tooltip = {}; // For the tooltip system nv.utils = {}; // Utility subsystem nv.models = {}; //stores all the possible models/components nv.charts = {}; //stores all the ready to use charts nv.graphs = []; //stores all the graphs currently on the page nv.logs = {}; //stores some statistics and potential error messages nv.dispatch = d3.dispatch('render_start', 'render_end'); // ************************************************************************* // Development render timers - disabled if dev = false if (nv.dev) { nv.dispatch.on('render_start', function(e) { nv.logs.startTime = +new Date(); }); nv.dispatch.on('render_end', function(e) { nv.logs.endTime = +new Date(); nv.logs.totalTime = nv.logs.endTime - nv.logs.startTime; nv.log('total', nv.logs.totalTime); // used for development, to keep track of graph generation times }); } // ******************************************** // Public Core NV functions // Logs all arguments, and returns the last so you can test things in place nv.log = function() { if (nv.dev && console.log && console.log.apply) console.log.apply(console, arguments) else if (nv.dev && console.log && Function.prototype.bind) { var log = Function.prototype.bind.call(console.log, console); log.apply(console, arguments); } return arguments[arguments.length - 1]; }; nv.render = function render(step) { step = step || 1; // number of graphs to generate in each timeout loop nv.render.active = true; nv.dispatch.render_start(); setTimeout(function() { var chart, graph; for (var i = 0; i < step && (graph = nv.render.queue[i]); i++) { chart = graph.generate(); if (typeof graph.callback == typeof(Function)) graph.callback(chart); nv.graphs.push(chart); } nv.render.queue.splice(0, i); if (nv.render.queue.length) setTimeout(arguments.callee, 0); else { nv.render.active = false; nv.dispatch.render_end(); } }, 0); }; nv.render.active = false; nv.render.queue = []; nv.addGraph = function(obj) { if (typeof arguments[0] === typeof(Function)) obj = {generate: arguments[0], callback: arguments[1]}; nv.render.queue.push(obj); if (!nv.render.active) nv.render(); }; nv.identity = function(d) { return d; }; nv.strip = function(s) { return s.replace(/(\s|&)/g,''); }; function daysInMonth(month,year) { return (new Date(year, month+1, 0)).getDate(); } function d3_time_range(floor, step, number) { return function(t0, t1, dt) { var time = floor(t0), times = []; if (time < t0) step(time); if (dt > 1) { while (time < t1) { var date = new Date(+time); if ((number(date) % dt === 0)) times.push(date); step(time); } } else { while (time < t1) { times.push(new Date(+time)); step(time); } } return times; }; } d3.time.monthEnd = function(date) { return new Date(date.getFullYear(), date.getMonth(), 0); }; d3.time.monthEnds = d3_time_range(d3.time.monthEnd, function(date) { date.setUTCDate(date.getUTCDate() + 1); date.setDate(daysInMonth(date.getMonth() + 1, date.getFullYear())); }, function(date) { return date.getMonth(); } ); /***** * A no-frills tooltip implementation. *****/ (function() { var nvtooltip = window.nv.tooltip = {}; nvtooltip.show = function(pos, content, gravity, dist, parentContainer, classes) { var container = document.createElement('div'); container.className = 'nvtooltip ' + (classes ? classes : 'xy-tooltip'); gravity = gravity || 's'; dist = dist || 20; var body = parentContainer; if ( !parentContainer || parentContainer.tagName.match(/g|svg/i)) { //If the parent element is an SVG element, place tooltip in the <body> element. body = document.getElementsByTagName('body')[0]; } container.innerHTML = content; container.style.left = 0; container.style.top = 0; container.style.opacity = 0; body.appendChild(container); var height = parseInt(container.offsetHeight), width = parseInt(container.offsetWidth), windowWidth = nv.utils.windowSize().width, windowHeight = nv.utils.windowSize().height, scrollTop = window.scrollY, scrollLeft = window.scrollX, left, top; windowHeight = window.innerWidth >= document.body.scrollWidth ? windowHeight : windowHeight - 16; windowWidth = window.innerHeight >= document.body.scrollHeight ? windowWidth : windowWidth - 16; var tooltipTop = function ( Elem ) { var offsetTop = top; do { if( !isNaN( Elem.offsetTop ) ) { offsetTop += (Elem.offsetTop); } } while( Elem = Elem.offsetParent ); return offsetTop; } var tooltipLeft = function ( Elem ) { var offsetLeft = left; do { if( !isNaN( Elem.offsetLeft ) ) { offsetLeft += (Elem.offsetLeft); } } while( Elem = Elem.offsetParent ); return offsetLeft; } switch (gravity) { case 'e': left = pos[0] - width - dist; top = pos[1] - (height / 2); var tLeft = tooltipLeft(container); var tTop = tooltipTop(container); if (tLeft < scrollLeft) left = pos[0] + dist > scrollLeft ? pos[0] + dist : scrollLeft - tLeft + left; if (tTop < scrollTop) top = scrollTop - tTop + top; if (tTop + height > scrollTop + windowHeight) top = scrollTop + windowHeight - tTop + top - height; break; case 'w': left = pos[0] + dist; top = pos[1] - (height / 2); if (tLeft + width > windowWidth) left = pos[0] - width - dist; if (tTop < scrollTop) top = scrollTop + 5; if (tTop + height > scrollTop + windowHeight) top = scrollTop - height - 5; break; case 'n': left = pos[0] - (width / 2) - 5; top = pos[1] + dist; var tLeft = tooltipLeft(container); var tTop = tooltipTop(container); if (tLeft < scrollLeft) left = scrollLeft + 5; if (tLeft + width > windowWidth) left = left - width/2 + 5; if (tTop + height > scrollTop + windowHeight) top = scrollTop + windowHeight - tTop + top - height; break; case 's': left = pos[0] - (width / 2); top = pos[1] - height - dist; var tLeft = tooltipLeft(container); var tTop = tooltipTop(container); if (tLeft < scrollLeft) left = scrollLeft + 5; if (tLeft + width > windowWidth) left = left - width/2 + 5; if (scrollTop > tTop) top = scrollTop; break; } container.style.left = left+'px'; container.style.top = top+'px'; container.style.opacity = 1; container.style.position = 'absolute'; //fix scroll bar issue container.style.pointerEvents = 'none'; //fix scroll bar issue return container; }; nvtooltip.cleanup = function() { // Find the tooltips, mark them for removal by this class (so others cleanups won't find it) var tooltips = document.getElementsByClassName('nvtooltip'); var purging = []; while(tooltips.length) { purging.push(tooltips[0]); tooltips[0].style.transitionDelay = '0 !important'; tooltips[0].style.opacity = 0; tooltips[0].className = 'nvtooltip-pending-removal'; } setTimeout(function() { while (purging.length) { var removeMe = purging.pop(); removeMe.parentNode.removeChild(removeMe); } }, 500); }; })(); nv.utils.windowSize = function() { // Sane defaults var size = {width: 640, height: 480}; // Earlier IE uses Doc.body if (document.body && document.body.offsetWidth) { size.width = document.body.offsetWidth; size.height = document.body.offsetHeight; } // IE can use depending on mode it is in if (document.compatMode=='CSS1Compat' && document.documentElement && document.documentElement.offsetWidth ) { size.width = document.documentElement.offsetWidth; size.height = document.documentElement.offsetHeight; } // Most recent browsers use if (window.innerWidth && window.innerHeight) { size.width = window.innerWidth; size.height = window.innerHeight; } return (size); }; // Easy way to bind multiple functions to window.onresize // TODO: give a way to remove a function after its bound, other than removing all of them nv.utils.windowResize = function(fun){ var oldresize = window.onresize; window.onresize = function(e) { if (typeof oldresize == 'function') oldresize(e); fun(e); } } // Backwards compatible way to implement more d3-like coloring of graphs. // If passed an array, wrap it in a function which implements the old default // behavior nv.utils.getColor = function(color) { if (!arguments.length) return nv.utils.defaultColor(); //if you pass in nothing, get default colors back if( Object.prototype.toString.call( color ) === '[object Array]' ) return function(d, i) { return d.color || color[i % color.length]; }; else return color; //can't really help it if someone passes rubbish as color } // Default color chooser uses the index of an object as before. nv.utils.defaultColor = function() { var colors = d3.scale.category20().range(); return function(d, i) { return d.color || colors[i % colors.length] }; } // Returns a color function that takes the result of 'getKey' for each series and // looks for a corresponding color from the dictionary, nv.utils.customTheme = function(dictionary, getKey, defaultColors) { getKey = getKey || function(series) { return series.key }; // use default series.key if getKey is undefined defaultColors = defaultColors || d3.scale.category20().range(); //default color function var defIndex = defaultColors.length; //current default color (going in reverse) return function(series, index) { var key = getKey(series); if (!defIndex) defIndex = defaultColors.length; //used all the default colors, start over if (typeof dictionary[key] !== "undefined") return (typeof dictionary[key] === "function") ? dictionary[key]() : dictionary[key]; else return defaultColors[--defIndex]; // no match in dictionary, use default color } } // From the PJAX example on d3js.org, while this is not really directly needed // it's a very cool method for doing pjax, I may expand upon it a little bit, // open to suggestions on anything that may be useful nv.utils.pjax = function(links, content) { d3.selectAll(links).on("click", function() { history.pushState(this.href, this.textContent, this.href); load(this.href); d3.event.preventDefault(); }); function load(href) { d3.html(href, function(fragment) { var target = d3.select(content).node(); target.parentNode.replaceChild(d3.select(fragment).select(content).node(), target); nv.utils.pjax(links, content); }); } d3.select(window).on("popstate", function() { if (d3.event.state) load(d3.event.state); }); } /* For situations where we want to approximate the width in pixels for an SVG:text element. Most common instance is when the element is in a display:none; container. Forumla is : text.length * font-size * constant_factor */ nv.utils.calcApproxTextWidth = function (svgTextElem) { if (svgTextElem instanceof d3.selection) { var fontSize = parseInt(svgTextElem.style("font-size").replace("px","")); var textLength = svgTextElem.text().length; return textLength * fontSize * 0.5; } return 0; }; nv.models.axis = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var axis = d3.svg.axis() ; var margin = {top: 0, right: 0, bottom: 0, left: 0} , width = 75 //only used for tickLabel currently , height = 60 //only used for tickLabel currently , scale = d3.scale.linear() , axisLabelText = null , showMaxMin = true //TODO: showMaxMin should be disabled on all ordinal scaled axes , highlightZero = true , rotateLabels = 0 , rotateYLabel = true , staggerLabels = false , isOrdinal = false , ticks = null ; axis .scale(scale) .orient('bottom') .tickFormat(function(d) { return d }) ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var scale0; //============================================================ function chart(selection) { selection.each(function(data) { var container = d3.select(this); //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-axis').data([data]); var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-axis'); var gEnter = wrapEnter.append('g'); var g = wrap.select('g') //------------------------------------------------------------ if (ticks !== null) axis.ticks(ticks); else if (axis.orient() == 'top' || axis.orient() == 'bottom') axis.ticks(Math.abs(scale.range()[1] - scale.range()[0]) / 100); //TODO: consider calculating width/height based on whether or not label is added, for reference in charts using this component d3.transition(g) .call(axis); scale0 = scale0 || axis.scale(); var fmt = axis.tickFormat(); if (fmt == null) { fmt = scale0.tickFormat(); } var axisLabel = g.selectAll('text.nv-axislabel') .data([axisLabelText || null]); axisLabel.exit().remove(); switch (axis.orient()) { case 'top': axisLabel.enter().append('text').attr('class', 'nv-axislabel'); var w = (scale.range().length==2) ? scale.range()[1] : (scale.range()[scale.range().length-1]+(scale.range()[1]-scale.range()[0])); axisLabel .attr('text-anchor', 'middle') .attr('y', 0) .attr('x', w/2); if (showMaxMin) { var axisMaxMin = wrap.selectAll('g.nv-axisMaxMin') .data(scale.domain()); axisMaxMin.enter().append('g').attr('class', 'nv-axisMaxMin').append('text'); axisMaxMin.exit().remove(); axisMaxMin .attr('transform', function(d,i) { return 'translate(' + scale(d) + ',0)' }) .select('text') .attr('dy', '0em') .attr('y', -axis.tickPadding()) .attr('text-anchor', 'middle') .text(function(d,i) { var v = fmt(d); return ('' + v).match('NaN') ? '' : v; }); d3.transition(axisMaxMin) .attr('transform', function(d,i) { return 'translate(' + scale.range()[i] + ',0)' }); } break; case 'bottom': var xLabelMargin = 36; var maxTextWidth = 30; var xTicks = g.selectAll('g').select("text"); if (rotateLabels%360) { //Calculate the longest xTick width xTicks.each(function(d,i){ var width = this.getBBox().width; if(width > maxTextWidth) maxTextWidth = width; }); //Convert to radians before calculating sin. Add 30 to margin for healthy padding. var sin = Math.abs(Math.sin(rotateLabels*Math.PI/180)); var xLabelMargin = (sin ? sin*maxTextWidth : maxTextWidth)+30; //Rotate all xTicks xTicks .attr('transform', function(d,i,j) { return 'rotate(' + rotateLabels + ' 0,0)' }) .attr('text-anchor', rotateLabels%360 > 0 ? 'start' : 'end'); } axisLabel.enter().append('text').attr('class', 'nv-axislabel'); var w = (scale.range().length==2) ? scale.range()[1] : (scale.range()[scale.range().length-1]+(scale.range()[1]-scale.range()[0])); axisLabel .attr('text-anchor', 'middle') .attr('y', xLabelMargin) .attr('x', w/2); if (showMaxMin) { //if (showMaxMin && !isOrdinal) { var axisMaxMin = wrap.selectAll('g.nv-axisMaxMin') //.data(scale.domain()) .data([scale.domain()[0], scale.domain()[scale.domain().length - 1]]); axisMaxMin.enter().append('g').attr('class', 'nv-axisMaxMin').append('text'); axisMaxMin.exit().remove(); axisMaxMin .attr('transform', function(d,i) { return 'translate(' + (scale(d) + (isOrdinal ? scale.rangeBand() / 2 : 0)) + ',0)' }) .select('text') .attr('dy', '.71em') .attr('y', axis.tickPadding()) .attr('transform', function(d,i,j) { return 'rotate(' + rotateLabels + ' 0,0)' }) .attr('text-anchor', rotateLabels ? (rotateLabels%360 > 0 ? 'start' : 'end') : 'middle') .text(function(d,i) { var v = fmt(d); return ('' + v).match('NaN') ? '' : v; }); d3.transition(axisMaxMin) .attr('transform', function(d,i) { //return 'translate(' + scale.range()[i] + ',0)' //return 'translate(' + scale(d) + ',0)' return 'translate(' + (scale(d) + (isOrdinal ? scale.rangeBand() / 2 : 0)) + ',0)' }); } if (staggerLabels) xTicks .attr('transform', function(d,i) { return 'translate(0,' + (i % 2 == 0 ? '0' : '12') + ')' }); break; case 'right': axisLabel.enter().append('text').attr('class', 'nv-axislabel'); axisLabel .attr('text-anchor', rotateYLabel ? 'middle' : 'begin') .attr('transform', rotateYLabel ? 'rotate(90)' : '') .attr('y', rotateYLabel ? (-Math.max(margin.right,width) + 12) : -10) //TODO: consider calculating this based on largest tick width... OR at least expose this on chart .attr('x', rotateYLabel ? (scale.range()[0] / 2) : axis.tickPadding()); if (showMaxMin) { var axisMaxMin = wrap.selectAll('g.nv-axisMaxMin') .data(scale.domain()); axisMaxMin.enter().append('g').attr('class', 'nv-axisMaxMin').append('text') .style('opacity', 0); axisMaxMin.exit().remove(); axisMaxMin .attr('transform', function(d,i) { return 'translate(0,' + scale(d) + ')' }) .select('text') .attr('dy', '.32em') .attr('y', 0) .attr('x', axis.tickPadding()) .attr('text-anchor', 'start') .text(function(d,i) { var v = fmt(d); return ('' + v).match('NaN') ? '' : v; }); d3.transition(axisMaxMin) .attr('transform', function(d,i) { return 'translate(0,' + scale.range()[i] + ')' }) .select('text') .style('opacity', 1); } break; case 'left': /* //For dynamically placing the label. Can be used with dynamically-sized chart axis margins var yTicks = g.selectAll('g').select("text"); yTicks.each(function(d,i){ var labelPadding = this.getBBox().width + axis.tickPadding() + 16; if(labelPadding > width) width = labelPadding; }); */ axisLabel.enter().append('text').attr('class', 'nv-axislabel'); axisLabel .attr('text-anchor', rotateYLabel ? 'middle' : 'end') .attr('transform', rotateYLabel ? 'rotate(-90)' : '') .attr('y', rotateYLabel ? (-Math.max(margin.left,width) + 12) : -10) //TODO: consider calculating this based on largest tick width... OR at least expose this on chart .attr('x', rotateYLabel ? (-scale.range()[0] / 2) : -axis.tickPadding()); if (showMaxMin) { var axisMaxMin = wrap.selectAll('g.nv-axisMaxMin') .data(scale.domain()); axisMaxMin.enter().append('g').attr('class', 'nv-axisMaxMin').append('text') .style('opacity', 0); axisMaxMin.exit().remove(); axisMaxMin .attr('transform', function(d,i) { return 'translate(0,' + scale0(d) + ')' }) .select('text') .attr('dy', '.32em') .attr('y', 0) .attr('x', -axis.tickPadding()) .attr('text-anchor', 'end') .text(function(d,i) { var v = fmt(d); return ('' + v).match('NaN') ? '' : v; }); d3.transition(axisMaxMin) .attr('transform', function(d,i) { return 'translate(0,' + scale.range()[i] + ')' }) .select('text') .style('opacity', 1); } break; } axisLabel .text(function(d) { return d }); if (showMaxMin && (axis.orient() === 'left' || axis.orient() === 'right')) { //check if max and min overlap other values, if so, hide the values that overlap g.selectAll('g') // the g's wrapping each tick .each(function(d,i) { d3.select(this).select('text').attr('opacity', 1); if (scale(d) < scale.range()[1] + 10 || scale(d) > scale.range()[0] - 10) { // 10 is assuming text height is 16... if d is 0, leave it! if (d > 1e-10 || d < -1e-10) // accounts for minor floating point errors... though could be problematic if the scale is EXTREMELY SMALL d3.select(this).attr('opacity', 0); d3.select(this).select('text').attr('opacity', 0); // Don't remove the ZERO line!! } }); //if Max and Min = 0 only show min, Issue #281 if (scale.domain()[0] == scale.domain()[1] && scale.domain()[0] == 0) wrap.selectAll('g.nv-axisMaxMin') .style('opacity', function(d,i) { return !i ? 1 : 0 }); } if (showMaxMin && (axis.orient() === 'top' || axis.orient() === 'bottom')) { var maxMinRange = []; wrap.selectAll('g.nv-axisMaxMin') .each(function(d,i) { try { if (i) // i== 1, max position maxMinRange.push(scale(d) - this.getBBox().width - 4) //assuming the max and min labels are as wide as the next tick (with an extra 4 pixels just in case) else // i==0, min position maxMinRange.push(scale(d) + this.getBBox().width + 4) }catch (err) { if (i) // i== 1, max position maxMinRange.push(scale(d) - 4) //assuming the max and min labels are as wide as the next tick (with an extra 4 pixels just in case) else // i==0, min position maxMinRange.push(scale(d) + 4) } }); g.selectAll('g') // the g's wrapping each tick .each(function(d,i) { if (scale(d) < maxMinRange[0] || scale(d) > maxMinRange[1]) { if (d > 1e-10 || d < -1e-10) // accounts for minor floating point errors... though could be problematic if the scale is EXTREMELY SMALL d3.select(this).remove(); else d3.select(this).select('text').remove(); // Don't remove the ZERO line!! } }); } //highlight zero line ... Maybe should not be an option and should just be in CSS? if (highlightZero) g.selectAll('.tick') .filter(function(d) { return !parseFloat(Math.round(d.__data__*100000)/1000000) && (d.__data__ !== undefined) }) //this is because sometimes the 0 tick is a very small fraction, TODO: think of cleaner technique .classed('zero', true); //store old scales for use in transitions on update scale0 = scale.copy(); }); return chart; } //============================================================ // Expose Public Variables //------------------------------------------------------------ // expose chart's sub-components chart.axis = axis; d3.rebind(chart, axis, 'orient', 'tickValues', 'tickSubdivide', 'tickSize', 'tickPadding', 'tickFormat'); d3.rebind(chart, scale, 'domain', 'range', 'rangeBand', 'rangeBands'); //these are also accessible by chart.scale(), but added common ones directly for ease of use chart.margin = function(_) { if(!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; } chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.ticks = function(_) { if (!arguments.length) return ticks; ticks = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.axisLabel = function(_) { if (!arguments.length) return axisLabelText; axisLabelText = _; return chart; } chart.showMaxMin = function(_) { if (!arguments.length) return showMaxMin; showMaxMin = _; return chart; } chart.highlightZero = function(_) { if (!arguments.length) return highlightZero; highlightZero = _; return chart; } chart.scale = function(_) { if (!arguments.length) return scale; scale = _; axis.scale(scale); isOrdinal = typeof scale.rangeBands === 'function'; d3.rebind(chart, scale, 'domain', 'range', 'rangeBand', 'rangeBands'); return chart; } chart.rotateYLabel = function(_) { if(!arguments.length) return rotateYLabel; rotateYLabel = _; return chart; } chart.rotateLabels = function(_) { if(!arguments.length) return rotateLabels; rotateLabels = _; return chart; } chart.staggerLabels = function(_) { if (!arguments.length) return staggerLabels; staggerLabels = _; return chart; }; //============================================================ return chart; } // Chart design based on the recommendations of Stephen Few. Implementation // based on the work of Clint Ivy, Jamie Love, and Jason Davies. // http://projects.instantcognition.com/protovis/bulletchart/ nv.models.bullet = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var margin = {top: 0, right: 0, bottom: 0, left: 0} , orient = 'left' // TODO top & bottom , reverse = false , ranges = function(d) { return d.ranges } , markers = function(d) { return d.markers } , measures = function(d) { return d.measures } , forceX = [0] // List of numbers to Force into the X scale (ie. 0, or a max / min, etc.) , width = 380 , height = 30 , tickFormat = null , color = nv.utils.getColor(['#1f77b4']) , dispatch = d3.dispatch('elementMouseover', 'elementMouseout') ; //============================================================ function chart(selection) { selection.each(function(d, i) { var availableWidth = width - margin.left - margin.right, availableHeight = height - margin.top - margin.bottom, container = d3.select(this); var rangez = ranges.call(this, d, i).slice().sort(d3.descending), markerz = markers.call(this, d, i).slice().sort(d3.descending), measurez = measures.call(this, d, i).slice().sort(d3.descending); //------------------------------------------------------------ // Setup Scales // Compute the new x-scale. var x1 = d3.scale.linear() .domain( d3.extent(d3.merge([forceX, rangez])) ) .range(reverse ? [availableWidth, 0] : [0, availableWidth]); // Retrieve the old x-scale, if this is an update. var x0 = this.__chart__ || d3.scale.linear() .domain([0, Infinity]) .range(x1.range()); // Stash the new scale. this.__chart__ = x1; var rangeMin = d3.min(rangez), //rangez[2] rangeMax = d3.max(rangez), //rangez[0] rangeAvg = rangez[1]; //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-bullet').data([d]); var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-bullet'); var gEnter = wrapEnter.append('g'); var g = wrap.select('g'); gEnter.append('rect').attr('class', 'nv-range nv-rangeMax'); gEnter.append('rect').attr('class', 'nv-range nv-rangeAvg'); gEnter.append('rect').attr('class', 'nv-range nv-rangeMin'); gEnter.append('rect').attr('class', 'nv-measure'); gEnter.append('path').attr('class', 'nv-markerTriangle'); wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ var w0 = function(d) { return Math.abs(x0(d) - x0(0)) }, // TODO: could optimize by precalculating x0(0) and x1(0) w1 = function(d) { return Math.abs(x1(d) - x1(0)) }; var xp0 = function(d) { return d < 0 ? x0(d) : x0(0) }, xp1 = function(d) { return d < 0 ? x1(d) : x1(0) }; g.select('rect.nv-rangeMax') .attr('height', availableHeight) .attr('width', w1(rangeMax > 0 ? rangeMax : rangeMin)) .attr('x', xp1(rangeMax > 0 ? rangeMax : rangeMin)) .datum(rangeMax > 0 ? rangeMax : rangeMin) /* .attr('x', rangeMin < 0 ? rangeMax > 0 ? x1(rangeMin) : x1(rangeMax) : x1(0)) */ g.select('rect.nv-rangeAvg') .attr('height', availableHeight) .attr('width', w1(rangeAvg)) .attr('x', xp1(rangeAvg)) .datum(rangeAvg) /* .attr('width', rangeMax <= 0 ? x1(rangeMax) - x1(rangeAvg) : x1(rangeAvg) - x1(rangeMin)) .attr('x', rangeMax <= 0 ? x1(rangeAvg) : x1(rangeMin)) */ g.select('rect.nv-rangeMin') .attr('height', availableHeight) .attr('width', w1(rangeMax)) .attr('x', xp1(rangeMax)) .attr('width', w1(rangeMax > 0 ? rangeMin : rangeMax)) .attr('x', xp1(rangeMax > 0 ? rangeMin : rangeMax)) .datum(rangeMax > 0 ? rangeMin : rangeMax) /* .attr('width', rangeMax <= 0 ? x1(rangeAvg) - x1(rangeMin) : x1(rangeMax) - x1(rangeAvg)) .attr('x', rangeMax <= 0 ? x1(rangeMin) : x1(rangeAvg)) */ g.select('rect.nv-measure') .style('fill', color) .attr('height', availableHeight / 3) .attr('y', availableHeight / 3) .attr('width', measurez < 0 ? x1(0) - x1(measurez[0]) : x1(measurez[0]) - x1(0)) .attr('x', xp1(measurez)) .on('mouseover', function() { dispatch.elementMouseover({ value: measurez[0], label: 'Current', pos: [x1(measurez[0]), availableHeight/2] }) }) .on('mouseout', function() { dispatch.elementMouseout({ value: measurez[0], label: 'Current' }) }) var h3 = availableHeight / 6; if (markerz[0]) { g.selectAll('path.nv-markerTriangle') .attr('transform', function(d) { return 'translate(' + x1(markerz[0]) + ',' + (availableHeight / 2) + ')' }) .attr('d', 'M0,' + h3 + 'L' + h3 + ',' + (-h3) + ' ' + (-h3) + ',' + (-h3) + 'Z') .on('mouseover', function() { dispatch.elementMouseover({ value: markerz[0], label: 'Previous', pos: [x1(markerz[0]), availableHeight/2] }) }) .on('mouseout', function() { dispatch.elementMouseout({ value: markerz[0], label: 'Previous' }) }); } else { g.selectAll('path.nv-markerTriangle').remove(); } wrap.selectAll('.nv-range') .on('mouseover', function(d,i) { var label = !i ? "Maximum" : i == 1 ? "Mean" : "Minimum"; dispatch.elementMouseover({ value: d, label: label, pos: [x1(d), availableHeight/2] }) }) .on('mouseout', function(d,i) { var label = !i ? "Maximum" : i == 1 ? "Mean" : "Minimum"; dispatch.elementMouseout({ value: d, label: label }) }) /* // THIS IS THE PREVIOUS BULLET IMPLEMENTATION, WILL REMOVE SHORTLY // Update the range rects. var range = g.selectAll('rect.nv-range') .data(rangez); range.enter().append('rect') .attr('class', function(d, i) { return 'nv-range nv-s' + i; }) .attr('width', w0) .attr('height', availableHeight) .attr('x', reverse ? x0 : 0) .on('mouseover', function(d,i) { dispatch.elementMouseover({ value: d, label: (i <= 0) ? 'Maximum' : (i > 1) ? 'Minimum' : 'Mean', //TODO: make these labels a variable pos: [x1(d), availableHeight/2] }) }) .on('mouseout', function(d,i) { dispatch.elementMouseout({ value: d, label: (i <= 0) ? 'Minimum' : (i >=1) ? 'Maximum' : 'Mean' //TODO: make these labels a variable }) }) d3.transition(range) .attr('x', reverse ? x1 : 0) .attr('width', w1) .attr('height', availableHeight); // Update the measure rects. var measure = g.selectAll('rect.nv-measure') .data(measurez); measure.enter().append('rect') .attr('class', function(d, i) { return 'nv-measure nv-s' + i; }) .style('fill', function(d,i) { return color(d,i ) }) .attr('width', w0) .attr('height', availableHeight / 3) .attr('x', reverse ? x0 : 0) .attr('y', availableHeight / 3) .on('mouseover', function(d) { dispatch.elementMouseover({ value: d, label: 'Current', //TODO: make these labels a variable pos: [x1(d), availableHeight/2] }) }) .on('mouseout', function(d) { dispatch.elementMouseout({ value: d, label: 'Current' //TODO: make these labels a variable }) }) d3.transition(measure) .attr('width', w1) .attr('height', availableHeight / 3) .attr('x', reverse ? x1 : 0) .attr('y', availableHeight / 3); // Update the marker lines. var marker = g.selectAll('path.nv-markerTriangle') .data(markerz); var h3 = availableHeight / 6; marker.enter().append('path') .attr('class', 'nv-markerTriangle') .attr('transform', function(d) { return 'translate(' + x0(d) + ',' + (availableHeight / 2) + ')' }) .attr('d', 'M0,' + h3 + 'L' + h3 + ',' + (-h3) + ' ' + (-h3) + ',' + (-h3) + 'Z') .on('mouseover', function(d,i) { dispatch.elementMouseover({ value: d, label: 'Previous', pos: [x1(d), availableHeight/2] }) }) .on('mouseout', function(d,i) { dispatch.elementMouseout({ value: d, label: 'Previous' }) }); d3.transition(marker) .attr('transform', function(d) { return 'translate(' + (x1(d) - x1(0)) + ',' + (availableHeight / 2) + ')' }); marker.exit().remove(); */ }); // d3.timer.flush(); // Not needed? return chart; } //============================================================ // Expose Public Variables //------------------------------------------------------------ chart.dispatch = dispatch; // left, right, top, bottom chart.orient = function(_) { if (!arguments.length) return orient; orient = _; reverse = orient == 'right' || orient == 'bottom'; return chart; }; // ranges (bad, satisfactory, good) chart.ranges = function(_) { if (!arguments.length) return ranges; ranges = _; return chart; }; // markers (previous, goal) chart.markers = function(_) { if (!arguments.length) return markers; markers = _; return chart; }; // measures (actual, forecast) chart.measures = function(_) { if (!arguments.length) return measures; measures = _; return chart; }; chart.forceX = function(_) { if (!arguments.length) return forceX; forceX = _; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.tickFormat = function(_) { if (!arguments.length) return tickFormat; tickFormat = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); return chart; }; //============================================================ return chart; }; // Chart design based on the recommendations of Stephen Few. Implementation // based on the work of Clint Ivy, Jamie Love, and Jason Davies. // http://projects.instantcognition.com/protovis/bulletchart/ nv.models.bulletChart = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var bullet = nv.models.bullet() ; var orient = 'left' // TODO top & bottom , reverse = false , margin = {top: 5, right: 40, bottom: 20, left: 120} , ranges = function(d) { return d.ranges } , markers = function(d) { return d.markers } , measures = function(d) { return d.measures } , width = null , height = 55 , tickFormat = null , tooltips = true , tooltip = function(key, x, y, e, graph) { return '<h3>' + x + '</h3>' + '<p>' + y + '</p>' } , noData = 'No Data Available.' , dispatch = d3.dispatch('tooltipShow', 'tooltipHide') ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var showTooltip = function(e, offsetElement) { var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ) + margin.left, top = e.pos[1] + ( offsetElement.offsetTop || 0) + margin.top, content = tooltip(e.key, e.label, e.value, e, chart); nv.tooltip.show([left, top], content, e.value < 0 ? 'e' : 'w', null, offsetElement); }; //============================================================ function chart(selection) { selection.each(function(d, i) { var container = d3.select(this); var availableWidth = (width || parseInt(container.style('width')) || 960) - margin.left - margin.right, availableHeight = height - margin.top - margin.bottom, that = this; chart.update = function() { chart(selection) }; chart.container = this; //------------------------------------------------------------ // Display No Data message if there's nothing to show. if (!d || !ranges.call(this, d, i)) { var noDataText = container.selectAll('.nv-noData').data([noData]); noDataText.enter().append('text') .attr('class', 'nvd3 nv-noData') .attr('dy', '-.7em') .style('text-anchor', 'middle'); noDataText .attr('x', margin.left + availableWidth / 2) .attr('y', 18 + margin.top + availableHeight / 2) .text(function(d) { return d }); return chart; } else { container.selectAll('.nv-noData').remove(); } //------------------------------------------------------------ var rangez = ranges.call(this, d, i).slice().sort(d3.descending), markerz = markers.call(this, d, i).slice().sort(d3.descending), measurez = measures.call(this, d, i).slice().sort(d3.descending); //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-bulletChart').data([d]); var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-bulletChart'); var gEnter = wrapEnter.append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-bulletWrap'); gEnter.append('g').attr('class', 'nv-titles'); wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ // Compute the new x-scale. var x1 = d3.scale.linear() .domain([0, Math.max(rangez[0], markerz[0], measurez[0])]) // TODO: need to allow forceX and forceY, and xDomain, yDomain .range(reverse ? [availableWidth, 0] : [0, availableWidth]); // Retrieve the old x-scale, if this is an update. var x0 = this.__chart__ || d3.scale.linear() .domain([0, Infinity]) .range(x1.range()); // Stash the new scale. this.__chart__ = x1; /* // Derive width-scales from the x-scales. var w0 = bulletWidth(x0), w1 = bulletWidth(x1); function bulletWidth(x) { var x0 = x(0); return function(d) { return Math.abs(x(d) - x(0)); }; } function bulletTranslate(x) { return function(d) { return 'translate(' + x(d) + ',0)'; }; } */ var w0 = function(d) { return Math.abs(x0(d) - x0(0)) }, // TODO: could optimize by precalculating x0(0) and x1(0) w1 = function(d) { return Math.abs(x1(d) - x1(0)) }; var title = gEnter.select('.nv-titles').append('g') .attr('text-anchor', 'end') .attr('transform', 'translate(-6,' + (height - margin.top - margin.bottom) / 2 + ')'); title.append('text') .attr('class', 'nv-title') .text(function(d) { return d.title; }); title.append('text') .attr('class', 'nv-subtitle') .attr('dy', '1em') .text(function(d) { return d.subtitle; }); bullet .width(availableWidth) .height(availableHeight) var bulletWrap = g.select('.nv-bulletWrap'); d3.transition(bulletWrap).call(bullet); // Compute the tick format. var format = tickFormat || x1.tickFormat( availableWidth / 100 ); // Update the tick groups. var tick = g.selectAll('g.nv-tick') .data(x1.ticks( availableWidth / 50 ), function(d) { return this.textContent || format(d); }); // Initialize the ticks with the old scale, x0. var tickEnter = tick.enter().append('g') .attr('class', 'nv-tick') .attr('transform', function(d) { return 'translate(' + x0(d) + ',0)' }) .style('opacity', 1e-6); tickEnter.append('line') .attr('y1', availableHeight) .attr('y2', availableHeight * 7 / 6); tickEnter.append('text') .attr('text-anchor', 'middle') .attr('dy', '1em') .attr('y', availableHeight * 7 / 6) .text(format); // Transition the updating ticks to the new scale, x1. var tickUpdate = d3.transition(tick) .attr('transform', function(d) { return 'translate(' + x1(d) + ',0)' }) .style('opacity', 1); tickUpdate.select('line') .attr('y1', availableHeight) .attr('y2', availableHeight * 7 / 6); tickUpdate.select('text') .attr('y', availableHeight * 7 / 6); // Transition the exiting ticks to the new scale, x1. d3.transition(tick.exit()) .attr('transform', function(d) { return 'translate(' + x1(d) + ',0)' }) .style('opacity', 1e-6) .remove(); //============================================================ // Event Handling/Dispatching (in chart's scope) //------------------------------------------------------------ dispatch.on('tooltipShow', function(e) { e.key = d.title; if (tooltips) showTooltip(e, that.parentNode); }); //============================================================ }); d3.timer.flush(); return chart; } //============================================================ // Event Handling/Dispatching (out of chart's scope) //------------------------------------------------------------ bullet.dispatch.on('elementMouseover.tooltip', function(e) { dispatch.tooltipShow(e); }); bullet.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); dispatch.on('tooltipHide', function() { if (tooltips) nv.tooltip.cleanup(); }); //============================================================ //============================================================ // Expose Public Variables //------------------------------------------------------------ chart.dispatch = dispatch; chart.bullet = bullet; d3.rebind(chart, bullet, 'color'); // left, right, top, bottom chart.orient = function(x) { if (!arguments.length) return orient; orient = x; reverse = orient == 'right' || orient == 'bottom'; return chart; }; // ranges (bad, satisfactory, good) chart.ranges = function(x) { if (!arguments.length) return ranges; ranges = x; return chart; }; // markers (previous, goal) chart.markers = function(x) { if (!arguments.length) return markers; markers = x; return chart; }; // measures (actual, forecast) chart.measures = function(x) { if (!arguments.length) return measures; measures = x; return chart; }; chart.width = function(x) { if (!arguments.length) return width; width = x; return chart; }; chart.height = function(x) { if (!arguments.length) return height; height = x; return chart; }; chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.tickFormat = function(x) { if (!arguments.length) return tickFormat; tickFormat = x; return chart; }; chart.tooltips = function(_) { if (!arguments.length) return tooltips; tooltips = _; return chart; }; chart.tooltipContent = function(_) { if (!arguments.length) return tooltip; tooltip = _; return chart; }; chart.noData = function(_) { if (!arguments.length) return noData; noData = _; return chart; }; //============================================================ return chart; }; nv.models.cumulativeLineChart = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var lines = nv.models.line() , xAxis = nv.models.axis() , yAxis = nv.models.axis() , legend = nv.models.legend() , controls = nv.models.legend() ; var margin = {top: 30, right: 30, bottom: 50, left: 60} , color = nv.utils.defaultColor() , width = null , height = null , showLegend = true , tooltips = true , showControls = true , rescaleY = true , tooltip = function(key, x, y, e, graph) { return '<h3>' + key + '</h3>' + '<p>' + y + ' at ' + x + '</p>' } , x //can be accessed via chart.xScale() , y //can be accessed via chart.yScale() , id = lines.id() , state = { index: 0, rescaleY: rescaleY } , defaultState = null , noData = 'No Data Available.' , average = function(d) { return d.average } , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState') ; xAxis .orient('bottom') .tickPadding(7) ; yAxis .orient('left') ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var dx = d3.scale.linear() , index = {i: 0, x: 0} ; var showTooltip = function(e, offsetElement) { var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), top = e.pos[1] + ( offsetElement.offsetTop || 0), x = xAxis.tickFormat()(lines.x()(e.point, e.pointIndex)), y = yAxis.tickFormat()(lines.y()(e.point, e.pointIndex)), content = tooltip(e.series.key, x, y, e, chart); nv.tooltip.show([left, top], content, null, null, offsetElement); }; /* //Moved to see if we can get better behavior to fix issue #315 var indexDrag = d3.behavior.drag() .on('dragstart', dragStart) .on('drag', dragMove) .on('dragend', dragEnd); function dragStart(d,i) { d3.select(chart.container) .style('cursor', 'ew-resize'); } function dragMove(d,i) { d.x += d3.event.dx; d.i = Math.round(dx.invert(d.x)); d3.select(this).attr('transform', 'translate(' + dx(d.i) + ',0)'); chart.update(); } function dragEnd(d,i) { d3.select(chart.container) .style('cursor', 'auto'); chart.update(); } */ //============================================================ function chart(selection) { selection.each(function(data) { var container = d3.select(this).classed('nv-chart-' + id, true), that = this; var availableWidth = (width || parseInt(container.style('width')) || 960) - margin.left - margin.right, availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; chart.update = function() { container.transition().call(chart) }; chart.container = this; //set state.disabled state.disabled = data.map(function(d) { return !!d.disabled }); if (!defaultState) { var key; defaultState = {}; for (key in state) { if (state[key] instanceof Array) defaultState[key] = state[key].slice(0); else defaultState[key] = state[key]; } } var indexDrag = d3.behavior.drag() .on('dragstart', dragStart) .on('drag', dragMove) .on('dragend', dragEnd); function dragStart(d,i) { d3.select(chart.container) .style('cursor', 'ew-resize'); } function dragMove(d,i) { index.x = d3.event.x; index.i = Math.round(dx.invert(index.x)); updateZero(); } function dragEnd(d,i) { d3.select(chart.container) .style('cursor', 'auto'); // update state and send stateChange with new index state.index = index.i; dispatch.stateChange(state); } //------------------------------------------------------------ // Display No Data message if there's nothing to show. if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) { var noDataText = container.selectAll('.nv-noData').data([noData]); noDataText.enter().append('text') .attr('class', 'nvd3 nv-noData') .attr('dy', '-.7em') .style('text-anchor', 'middle'); noDataText .attr('x', margin.left + availableWidth / 2) .attr('y', margin.top + availableHeight / 2) .text(function(d) { return d }); return chart; } else { container.selectAll('.nv-noData').remove(); } //------------------------------------------------------------ //------------------------------------------------------------ // Setup Scales x = lines.xScale(); y = lines.yScale(); if (!rescaleY) { var seriesDomains = data .filter(function(series) { return !series.disabled }) .map(function(series,i) { var initialDomain = d3.extent(series.values, lines.y()); //account for series being disabled when losing 95% or more if (initialDomain[0] < -.95) initialDomain[0] = -.95; return [ (initialDomain[0] - initialDomain[1]) / (1 + initialDomain[1]), (initialDomain[1] - initialDomain[0]) / (1 + initialDomain[0]) ]; }); var completeDomain = [ d3.min(seriesDomains, function(d) { return d[0] }), d3.max(seriesDomains, function(d) { return d[1] }) ] lines.yDomain(completeDomain); } else { lines.yDomain(null); } dx .domain([0, data[0].values.length - 1]) //Assumes all series have same length .range([0, availableWidth]) .clamp(true); //------------------------------------------------------------ var data = indexify(index.i, data); //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-cumulativeLine').data([data]); var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-cumulativeLine').append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-x nv-axis'); gEnter.append('g').attr('class', 'nv-y nv-axis'); gEnter.append('g').attr('class', 'nv-background'); gEnter.append('g').attr('class', 'nv-linesWrap'); gEnter.append('g').attr('class', 'nv-avgLinesWrap'); gEnter.append('g').attr('class', 'nv-legendWrap'); gEnter.append('g').attr('class', 'nv-controlsWrap'); //------------------------------------------------------------ //------------------------------------------------------------ // Legend if (showLegend) { legend.width(availableWidth); g.select('.nv-legendWrap') .datum(data) .call(legend); if ( margin.top != legend.height()) { margin.top = legend.height(); availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; } g.select('.nv-legendWrap') .attr('transform', 'translate(0,' + (-margin.top) +')') } //------------------------------------------------------------ //------------------------------------------------------------ // Controls if (showControls) { var controlsData = [ { key: 'Re-scale y-axis', disabled: !rescaleY } ]; controls.width(140).color(['#444', '#444', '#444']); g.select('.nv-controlsWrap') .datum(controlsData) .attr('transform', 'translate(0,' + (-margin.top) +')') .call(controls); } //------------------------------------------------------------ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); // Show error if series goes below 100% var tempDisabled = data.filter(function(d) { return d.tempDisabled }); wrap.select('.tempDisabled').remove(); //clean-up and prevent duplicates if (tempDisabled.length) { wrap.append('text').attr('class', 'tempDisabled') .attr('x', availableWidth / 2) .attr('y', '-.71em') .style('text-anchor', 'end') .text(tempDisabled.map(function(d) { return d.key }).join(', ') + ' values cannot be calculated for this time period.'); } //------------------------------------------------------------ // Main Chart Component(s) gEnter.select('.nv-background') .append('rect'); g.select('.nv-background rect') .attr('width', availableWidth) .attr('height', availableHeight); lines //.x(function(d) { return d.x }) .y(function(d) { return d.display.y }) .width(availableWidth) .height(availableHeight) .color(data.map(function(d,i) { return d.color || color(d, i); }).filter(function(d,i) { return !data[i].disabled && !data[i].tempDisabled; })); var linesWrap = g.select('.nv-linesWrap') .datum(data.filter(function(d) { return !d.disabled && !d.tempDisabled })); //d3.transition(linesWrap).call(lines); linesWrap.call(lines); /*Handle average lines [AN-612] ----------------------------*/ //Store a series index number in the data array. data.forEach(function(d,i) { d.seriesIndex = i; }); var avgLineData = data.filter(function(d) { return !d.disabled && !!average(d); }); var avgLines = g.select(".nv-avgLinesWrap").selectAll("line") .data(avgLineData, function(d) { return d.key; }); avgLines.enter() .append('line') .style('stroke-width',2) .style('stroke-dasharray','10,10') .style('stroke',function (d,i) { return lines.color()(d,d.seriesIndex); }) .attr('x1',0) .attr('x2',availableWidth) .attr('y1', function(d) { return y(average(d)); }) .attr('y2', function(d) { return y(average(d)); }); avgLines .attr('x1',0) .attr('x2',availableWidth) .attr('y1', function(d) { return y(average(d)); }) .attr('y2', function(d) { return y(average(d)); }); avgLines.exit().remove(); //Create index line ----------------------------------------- var indexLine = linesWrap.selectAll('.nv-indexLine') .data([index]); indexLine.enter().append('rect').attr('class', 'nv-indexLine') .attr('width', 3) .attr('x', -2) .attr('fill', 'red') .attr('fill-opacity', .5) .call(indexDrag) indexLine .attr('transform', function(d) { return 'translate(' + dx(d.i) + ',0)' }) .attr('height', availableHeight) //------------------------------------------------------------ //------------------------------------------------------------ // Setup Axes xAxis .scale(x) //Suggest how many ticks based on the chart width and D3 should listen (70 is the optimal number for MM/DD/YY dates) .ticks( Math.min(data[0].values.length,availableWidth/70) ) .tickSize(-availableHeight, 0); g.select('.nv-x.nv-axis') .attr('transform', 'translate(0,' + y.range()[0] + ')'); d3.transition(g.select('.nv-x.nv-axis')) .call(xAxis); yAxis .scale(y) .ticks( availableHeight / 36 ) .tickSize( -availableWidth, 0); d3.transition(g.select('.nv-y.nv-axis')) .call(yAxis); //------------------------------------------------------------ //============================================================ // Event Handling/Dispatching (in chart's scope) //------------------------------------------------------------ function updateZero() { indexLine .data([index]); container.call(chart); } g.select('.nv-background rect') .on('click', function() { index.x = d3.mouse(this)[0]; index.i = Math.round(dx.invert(index.x)); // update state and send stateChange with new index state.index = index.i; dispatch.stateChange(state); updateZero(); }); lines.dispatch.on('elementClick', function(e) { index.i = e.pointIndex; index.x = dx(index.i); // update state and send stateChange with new index state.index = index.i; dispatch.stateChange(state); updateZero(); }); controls.dispatch.on('legendClick', function(d,i) { d.disabled = !d.disabled; rescaleY = !d.disabled; state.rescaleY = rescaleY; dispatch.stateChange(state); //selection.transition().call(chart); chart.update(); }); legend.dispatch.on('legendClick', function(d,i) { d.disabled = !d.disabled; if (!data.filter(function(d) { return !d.disabled }).length) { data.map(function(d) { d.disabled = false; wrap.selectAll('.nv-series').classed('disabled', false); return d; }); } state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); //selection.transition().call(chart); chart.update(); }); legend.dispatch.on('legendDblclick', function(d) { //Double clicking should always enable current series, and disabled all others. data.forEach(function(d) { d.disabled = true; }); d.disabled = false; state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); chart.update(); }); /* // legend.dispatch.on('legendMouseover', function(d, i) { d.hover = true; selection.transition().call(chart) }); legend.dispatch.on('legendMouseout', function(d, i) { d.hover = false; selection.transition().call(chart) }); */ dispatch.on('tooltipShow', function(e) { if (tooltips) showTooltip(e, that.parentNode); }); // Update chart from a state object passed to event handler dispatch.on('changeState', function(e) { if (typeof e.disabled !== 'undefined') { data.forEach(function(series,i) { series.disabled = e.disabled[i]; }); state.disabled = e.disabled; } if (typeof e.index !== 'undefined') { index.i = e.index; index.x = dx(index.i); state.index = e.index; indexLine .data([index]); } if (typeof e.rescaleY !== 'undefined') { rescaleY = e.rescaleY; } chart.update(); }); //============================================================ }); return chart; } //============================================================ // Event Handling/Dispatching (out of chart's scope) //------------------------------------------------------------ lines.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); lines.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); dispatch.on('tooltipHide', function() { if (tooltips) nv.tooltip.cleanup(); }); //============================================================ //============================================================ // Expose Public Variables //------------------------------------------------------------ // expose chart's sub-components chart.dispatch = dispatch; chart.lines = lines; chart.legend = legend; chart.xAxis = xAxis; chart.yAxis = yAxis; d3.rebind(chart, lines, 'defined', 'isArea', 'x', 'y', 'size', 'xDomain', 'yDomain', 'forceX', 'forceY', 'interactive', 'clipEdge', 'clipVoronoi', 'id'); chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); legend.color(color); return chart; }; chart.rescaleY = function(_) { if (!arguments.length) return rescaleY; rescaleY = _ return rescaleY; }; chart.showControls = function(_) { if (!arguments.length) return showControls; showControls = _; return chart; }; chart.showLegend = function(_) { if (!arguments.length) return showLegend; showLegend = _; return chart; }; chart.tooltips = function(_) { if (!arguments.length) return tooltips; tooltips = _; return chart; }; chart.tooltipContent = function(_) { if (!arguments.length) return tooltip; tooltip = _; return chart; }; chart.state = function(_) { if (!arguments.length) return state; state = _; return chart; }; chart.defaultState = function(_) { if (!arguments.length) return defaultState; defaultState = _; return chart; }; chart.noData = function(_) { if (!arguments.length) return noData; noData = _; return chart; }; chart.average = function(_) { if(!arguments.length) return average; average = _; return chart; }; //============================================================ //============================================================ // Functions //------------------------------------------------------------ /* Normalize the data according to an index point. */ function indexify(idx, data) { return data.map(function(line, i) { if (!line.values) { return line; } var v = lines.y()(line.values[idx], idx); //TODO: implement check below, and disable series if series loses 100% or more cause divide by 0 issue if (v < -.95) { //if a series loses more than 100%, calculations fail.. anything close can cause major distortion (but is mathematically correct till it hits 100) line.tempDisabled = true; return line; } line.tempDisabled = false; line.values = line.values.map(function(point, pointIndex) { point.display = {'y': (lines.y()(point, pointIndex) - v) / (1 + v) }; return point; }) return line; }) } //============================================================ return chart; } //TODO: consider deprecating by adding necessary features to multiBar model nv.models.discreteBar = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var margin = {top: 0, right: 0, bottom: 0, left: 0} , width = 960 , height = 500 , id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one , x = d3.scale.ordinal() , y = d3.scale.linear() , getX = function(d) { return d.x } , getY = function(d) { return d.y } , forceY = [0] // 0 is forced by default.. this makes sense for the majority of bar graphs... user can always do chart.forceY([]) to remove , color = nv.utils.defaultColor() , showValues = false , valueFormat = d3.format(',.2f') , xDomain , yDomain , dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout') , rectClass = 'discreteBar' ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var x0, y0; //============================================================ function chart(selection) { selection.each(function(data) { var availableWidth = width - margin.left - margin.right, availableHeight = height - margin.top - margin.bottom, container = d3.select(this); //add series index to each data point for reference data = data.map(function(series, i) { series.values = series.values.map(function(point) { point.series = i; return point; }); return series; }); //------------------------------------------------------------ // Setup Scales // remap and flatten the data for use in calculating the scales' domains var seriesData = (xDomain && yDomain) ? [] : // if we know xDomain and yDomain, no need to calculate data.map(function(d) { return d.values.map(function(d,i) { return { x: getX(d,i), y: getY(d,i), y0: d.y0 } }) }); x .domain(xDomain || d3.merge(seriesData).map(function(d) { return d.x })) .rangeBands([0, availableWidth], .1); y .domain(yDomain || d3.extent(d3.merge(seriesData).map(function(d) { return d.y }).concat(forceY))); // If showValues, pad the Y axis range to account for label height if (showValues) y.range([availableHeight - (y.domain()[0] < 0 ? 12 : 0), y.domain()[1] > 0 ? 12 : 0]); else y.range([availableHeight, 0]); //store old scales if they exist x0 = x0 || x; y0 = y0 || y.copy().range([y(0),y(0)]); //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-discretebar').data([data]); var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-discretebar'); var gEnter = wrapEnter.append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-groups'); wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ //TODO: by definition, the discrete bar should not have multiple groups, will modify/remove later var groups = wrap.select('.nv-groups').selectAll('.nv-group') .data(function(d) { return d }, function(d) { return d.key }); groups.enter().append('g') .style('stroke-opacity', 1e-6) .style('fill-opacity', 1e-6); d3.transition(groups.exit()) .style('stroke-opacity', 1e-6) .style('fill-opacity', 1e-6) .remove(); groups .attr('class', function(d,i) { return 'nv-group nv-series-' + i }) .classed('hover', function(d) { return d.hover }); d3.transition(groups) .style('stroke-opacity', 1) .style('fill-opacity', .75); var bars = groups.selectAll('g.nv-bar') .data(function(d) { return d.values }); bars.exit().remove(); var barsEnter = bars.enter().append('g') .attr('transform', function(d,i,j) { return 'translate(' + (x(getX(d,i)) + x.rangeBand() * .05 ) + ', ' + y(0) + ')' }) .on('mouseover', function(d,i) { //TODO: figure out why j works above, but not here d3.select(this).classed('hover', true); dispatch.elementMouseover({ value: getY(d,i), point: d, series: data[d.series], pos: [x(getX(d,i)) + (x.rangeBand() * (d.series + .5) / data.length), y(getY(d,i))], // TODO: Figure out why the value appears to be shifted pointIndex: i, seriesIndex: d.series, e: d3.event }); }) .on('mouseout', function(d,i) { d3.select(this).classed('hover', false); dispatch.elementMouseout({ value: getY(d,i), point: d, series: data[d.series], pointIndex: i, seriesIndex: d.series, e: d3.event }); }) .on('click', function(d,i) { dispatch.elementClick({ value: getY(d,i), point: d, series: data[d.series], pos: [x(getX(d,i)) + (x.rangeBand() * (d.series + .5) / data.length), y(getY(d,i))], // TODO: Figure out why the value appears to be shifted pointIndex: i, seriesIndex: d.series, e: d3.event }); d3.event.stopPropagation(); }) .on('dblclick', function(d,i) { dispatch.elementDblClick({ value: getY(d,i), point: d, series: data[d.series], pos: [x(getX(d,i)) + (x.rangeBand() * (d.series + .5) / data.length), y(getY(d,i))], // TODO: Figure out why the value appears to be shifted pointIndex: i, seriesIndex: d.series, e: d3.event }); d3.event.stopPropagation(); }); barsEnter.append('rect') .attr('height', 0) .attr('width', x.rangeBand() * .9 / data.length ) if (showValues) { barsEnter.append('text') .attr('text-anchor', 'middle') bars.select('text') .attr('x', x.rangeBand() * .9 / 2) .attr('y', function(d,i) { return getY(d,i) < 0 ? y(getY(d,i)) - y(0) + 12 : -4 }) .text(function(d,i) { return valueFormat(getY(d,i)) }); } else { bars.selectAll('text').remove(); } bars .attr('class', function(d,i) { return getY(d,i) < 0 ? 'nv-bar negative' : 'nv-bar positive' }) .style('fill', function(d,i) { return d.color || color(d,i) }) .style('stroke', function(d,i) { return d.color || color(d,i) }) .select('rect') .attr('class', rectClass) .attr('width', x.rangeBand() * .9 / data.length); d3.transition(bars) //.delay(function(d,i) { return i * 1200 / data[0].values.length }) .attr('transform', function(d,i) { var left = x(getX(d,i)) + x.rangeBand() * .05, top = getY(d,i) < 0 ? y(0) : y(0) - y(getY(d,i)) < 1 ? y(0) - 1 : //make 1 px positive bars show up above y=0 y(getY(d,i)); return 'translate(' + left + ', ' + top + ')' }) .select('rect') .attr('height', function(d,i) { return Math.max(Math.abs(y(getY(d,i)) - y(0)) || 1) }); //store old scales for use in transitions on update x0 = x.copy(); y0 = y.copy(); }); return chart; } //============================================================ // Expose Public Variables //------------------------------------------------------------ chart.dispatch = dispatch; chart.x = function(_) { if (!arguments.length) return getX; getX = _; return chart; }; chart.y = function(_) { if (!arguments.length) return getY; getY = _; return chart; }; chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.xScale = function(_) { if (!arguments.length) return x; x = _; return chart; }; chart.yScale = function(_) { if (!arguments.length) return y; y = _; return chart; }; chart.xDomain = function(_) { if (!arguments.length) return xDomain; xDomain = _; return chart; }; chart.yDomain = function(_) { if (!arguments.length) return yDomain; yDomain = _; return chart; }; chart.forceY = function(_) { if (!arguments.length) return forceY; forceY = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); return chart; }; chart.id = function(_) { if (!arguments.length) return id; id = _; return chart; }; chart.showValues = function(_) { if (!arguments.length) return showValues; showValues = _; return chart; }; chart.valueFormat= function(_) { if (!arguments.length) return valueFormat; valueFormat = _; return chart; }; chart.rectClass= function(_) { if (!arguments.length) return rectClass; rectClass = _; return chart; } //============================================================ return chart; } nv.models.discreteBarChart = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var discretebar = nv.models.discreteBar() , xAxis = nv.models.axis() , yAxis = nv.models.axis() ; var margin = {top: 15, right: 10, bottom: 50, left: 60} , width = null , height = null , color = nv.utils.getColor() , staggerLabels = false , tooltips = true , tooltip = function(key, x, y, e, graph) { return '<h3>' + x + '</h3>' + '<p>' + y + '</p>' } , x , y , noData = "No Data Available." , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'beforeUpdate') ; xAxis .orient('bottom') .highlightZero(false) .showMaxMin(false) .tickFormat(function(d) { return d }) ; yAxis .orient('left') .tickFormat(d3.format(',.1f')) ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var showTooltip = function(e, offsetElement) { var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), top = e.pos[1] + ( offsetElement.offsetTop || 0), x = xAxis.tickFormat()(discretebar.x()(e.point, e.pointIndex)), y = yAxis.tickFormat()(discretebar.y()(e.point, e.pointIndex)), content = tooltip(e.series.key, x, y, e, chart); nv.tooltip.show([left, top], content, e.value < 0 ? 'n' : 's', null, offsetElement); }; //============================================================ function chart(selection) { selection.each(function(data) { var container = d3.select(this), that = this; var availableWidth = (width || parseInt(container.style('width')) || 960) - margin.left - margin.right, availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; chart.update = function() { dispatch.beforeUpdate(); container.transition().call(chart); }; chart.container = this; //------------------------------------------------------------ // Display No Data message if there's nothing to show. if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) { var noDataText = container.selectAll('.nv-noData').data([noData]); noDataText.enter().append('text') .attr('class', 'nvd3 nv-noData') .attr('dy', '-.7em') .style('text-anchor', 'middle'); noDataText .attr('x', margin.left + availableWidth / 2) .attr('y', margin.top + availableHeight / 2) .text(function(d) { return d }); return chart; } else { container.selectAll('.nv-noData').remove(); } //------------------------------------------------------------ //------------------------------------------------------------ // Setup Scales x = discretebar.xScale(); y = discretebar.yScale(); //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-discreteBarWithAxes').data([data]); var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-discreteBarWithAxes').append('g'); var defsEnter = gEnter.append('defs'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-x nv-axis'); gEnter.append('g').attr('class', 'nv-y nv-axis'); gEnter.append('g').attr('class', 'nv-barsWrap'); g.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ //------------------------------------------------------------ // Main Chart Component(s) discretebar .width(availableWidth) .height(availableHeight); var barsWrap = g.select('.nv-barsWrap') .datum(data.filter(function(d) { return !d.disabled })) d3.transition(barsWrap).call(discretebar); //------------------------------------------------------------ defsEnter.append('clipPath') .attr('id', 'nv-x-label-clip-' + discretebar.id()) .append('rect'); g.select('#nv-x-label-clip-' + discretebar.id() + ' rect') .attr('width', x.rangeBand() * (staggerLabels ? 2 : 1)) .attr('height', 16) .attr('x', -x.rangeBand() / (staggerLabels ? 1 : 2 )); //------------------------------------------------------------ // Setup Axes xAxis .scale(x) .ticks( availableWidth / 100 ) .tickSize(-availableHeight, 0); g.select('.nv-x.nv-axis') .attr('transform', 'translate(0,' + (y.range()[0] + ((discretebar.showValues() && y.domain()[0] < 0) ? 16 : 0)) + ')'); //d3.transition(g.select('.nv-x.nv-axis')) g.select('.nv-x.nv-axis').transition().duration(0) .call(xAxis); var xTicks = g.select('.nv-x.nv-axis').selectAll('g'); if (staggerLabels) { xTicks .selectAll('text') .attr('transform', function(d,i,j) { return 'translate(0,' + (j % 2 == 0 ? '5' : '17') + ')' }) } yAxis .scale(y) .ticks( availableHeight / 36 ) .tickSize( -availableWidth, 0); d3.transition(g.select('.nv-y.nv-axis')) .call(yAxis); //------------------------------------------------------------ //============================================================ // Event Handling/Dispatching (in chart's scope) //------------------------------------------------------------ dispatch.on('tooltipShow', function(e) { if (tooltips) showTooltip(e, that.parentNode); }); //============================================================ }); return chart; } //============================================================ // Event Handling/Dispatching (out of chart's scope) //------------------------------------------------------------ discretebar.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); discretebar.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); dispatch.on('tooltipHide', function() { if (tooltips) nv.tooltip.cleanup(); }); //============================================================ //============================================================ // Expose Public Variables //------------------------------------------------------------ // expose chart's sub-components chart.dispatch = dispatch; chart.discretebar = discretebar; chart.xAxis = xAxis; chart.yAxis = yAxis; d3.rebind(chart, discretebar, 'x', 'y', 'xDomain', 'yDomain', 'forceX', 'forceY', 'id', 'showValues', 'valueFormat'); chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); discretebar.color(color); return chart; }; chart.staggerLabels = function(_) { if (!arguments.length) return staggerLabels; staggerLabels = _; return chart; }; chart.tooltips = function(_) { if (!arguments.length) return tooltips; tooltips = _; return chart; }; chart.tooltipContent = function(_) { if (!arguments.length) return tooltip; tooltip = _; return chart; }; chart.noData = function(_) { if (!arguments.length) return noData; noData = _; return chart; }; //============================================================ return chart; } nv.models.distribution = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var margin = {top: 0, right: 0, bottom: 0, left: 0} , width = 400 //technically width or height depending on x or y.... , size = 8 , axis = 'x' // 'x' or 'y'... horizontal or vertical , getData = function(d) { return d[axis] } // defaults d.x or d.y , color = nv.utils.defaultColor() , scale = d3.scale.linear() , domain ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var scale0; //============================================================ function chart(selection) { selection.each(function(data) { var availableLength = width - (axis === 'x' ? margin.left + margin.right : margin.top + margin.bottom), naxis = axis == 'x' ? 'y' : 'x', container = d3.select(this); //------------------------------------------------------------ // Setup Scales scale0 = scale0 || scale; //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-distribution').data([data]); var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-distribution'); var gEnter = wrapEnter.append('g'); var g = wrap.select('g'); wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')') //------------------------------------------------------------ var distWrap = g.selectAll('g.nv-dist') .data(function(d) { return d }, function(d) { return d.key }); distWrap.enter().append('g'); distWrap .attr('class', function(d,i) { return 'nv-dist nv-series-' + i }) .style('stroke', function(d,i) { return color(d, i) }); var dist = distWrap.selectAll('line.nv-dist' + axis) .data(function(d) { return d.values }) dist.enter().append('line') .attr(axis + '1', function(d,i) { return scale0(getData(d,i)) }) .attr(axis + '2', function(d,i) { return scale0(getData(d,i)) }) d3.transition(distWrap.exit().selectAll('line.nv-dist' + axis)) .attr(axis + '1', function(d,i) { return scale(getData(d,i)) }) .attr(axis + '2', function(d,i) { return scale(getData(d,i)) }) .style('stroke-opacity', 0) .remove(); dist .attr('class', function(d,i) { return 'nv-dist' + axis + ' nv-dist' + axis + '-' + i }) .attr(naxis + '1', 0) .attr(naxis + '2', size); d3.transition(dist) .attr(axis + '1', function(d,i) { return scale(getData(d,i)) }) .attr(axis + '2', function(d,i) { return scale(getData(d,i)) }) scale0 = scale.copy(); }); return chart; } //============================================================ // Expose Public Variables //------------------------------------------------------------ chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.axis = function(_) { if (!arguments.length) return axis; axis = _; return chart; }; chart.size = function(_) { if (!arguments.length) return size; size = _; return chart; }; chart.getData = function(_) { if (!arguments.length) return getData; getData = d3.functor(_); return chart; }; chart.scale = function(_) { if (!arguments.length) return scale; scale = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); return chart; }; //============================================================ return chart; } //TODO: consider deprecating and using multibar with single series for this nv.models.historicalBar = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var margin = {top: 0, right: 0, bottom: 0, left: 0} , width = 960 , height = 500 , id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one , x = d3.scale.linear() , y = d3.scale.linear() , getX = function(d) { return d.x } , getY = function(d) { return d.y } , forceX = [] , forceY = [0] , padData = false , clipEdge = true , color = nv.utils.defaultColor() , xDomain , yDomain , dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout') ; //============================================================ function chart(selection) { selection.each(function(data) { var availableWidth = width - margin.left - margin.right, availableHeight = height - margin.top - margin.bottom, container = d3.select(this); //------------------------------------------------------------ // Setup Scales x .domain(xDomain || d3.extent(data[0].values.map(getX).concat(forceX) )) if (padData) x.range([availableWidth * .5 / data[0].values.length, availableWidth * (data[0].values.length - .5) / data[0].values.length ]); else x.range([0, availableWidth]); y .domain(yDomain || d3.extent(data[0].values.map(getY).concat(forceY) )) .range([availableHeight, 0]); // If scale's domain don't have a range, slightly adjust to make one... so a chart can show a single data point if (x.domain()[0] === x.domain()[1] || y.domain()[0] === y.domain()[1]) singlePoint = true; if (x.domain()[0] === x.domain()[1]) x.domain()[0] ? x.domain([x.domain()[0] - x.domain()[0] * 0.01, x.domain()[1] + x.domain()[1] * 0.01]) : x.domain([-1,1]); if (y.domain()[0] === y.domain()[1]) y.domain()[0] ? y.domain([y.domain()[0] + y.domain()[0] * 0.01, y.domain()[1] - y.domain()[1] * 0.01]) : y.domain([-1,1]); //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-bar').data([data[0].values]); var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-bar'); var defsEnter = wrapEnter.append('defs'); var gEnter = wrapEnter.append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-bars'); wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ container .on('click', function(d,i) { dispatch.chartClick({ data: d, index: i, pos: d3.event, id: id }); }); defsEnter.append('clipPath') .attr('id', 'nv-chart-clip-path-' + id) .append('rect'); wrap.select('#nv-chart-clip-path-' + id + ' rect') .attr('width', availableWidth) .attr('height', availableHeight); g .attr('clip-path', clipEdge ? 'url(#nv-chart-clip-path-' + id + ')' : ''); var bars = wrap.select('.nv-bars').selectAll('.nv-bar') .data(function(d) { return d }); bars.exit().remove(); var barsEnter = bars.enter().append('rect') //.attr('class', function(d,i,j) { return (getY(d,i) < 0 ? 'nv-bar negative' : 'nv-bar positive') + ' nv-bar-' + j + '-' + i }) .attr('x', 0 ) .attr('y', function(d,i) { return y(Math.max(0, getY(d,i))) }) .attr('height', function(d,i) { return Math.abs(y(getY(d,i)) - y(0)) }) .on('mouseover', function(d,i) { d3.select(this).classed('hover', true); dispatch.elementMouseover({ point: d, series: data[0], pos: [x(getX(d,i)), y(getY(d,i))], // TODO: Figure out why the value appears to be shifted pointIndex: i, seriesIndex: 0, e: d3.event }); }) .on('mouseout', function(d,i) { d3.select(this).classed('hover', false); dispatch.elementMouseout({ point: d, series: data[0], pointIndex: i, seriesIndex: 0, e: d3.event }); }) .on('click', function(d,i) { dispatch.elementClick({ //label: d[label], value: getY(d,i), data: d, index: i, pos: [x(getX(d,i)), y(getY(d,i))], e: d3.event, id: id }); d3.event.stopPropagation(); }) .on('dblclick', function(d,i) { dispatch.elementDblClick({ //label: d[label], value: getY(d,i), data: d, index: i, pos: [x(getX(d,i)), y(getY(d,i))], e: d3.event, id: id }); d3.event.stopPropagation(); }); bars .attr('fill', function(d,i) { return color(d, i); }) .attr('class', function(d,i,j) { return (getY(d,i) < 0 ? 'nv-bar negative' : 'nv-bar positive') + ' nv-bar-' + j + '-' + i }) .attr('transform', function(d,i) { return 'translate(' + (x(getX(d,i)) - availableWidth / data[0].values.length * .45) + ',0)'; }) //TODO: better width calculations that don't assume always uniform data spacing;w .attr('width', (availableWidth / data[0].values.length) * .9 ) d3.transition(bars) //.attr('y', function(d,i) { return y(Math.max(0, getY(d,i))) }) .attr('y', function(d,i) { return getY(d,i) < 0 ? y(0) : y(0) - y(getY(d,i)) < 1 ? y(0) - 1 : y(getY(d,i)) }) .attr('height', function(d,i) { return Math.max(Math.abs(y(getY(d,i)) - y(0)),1) }); //.order(); // not sure if this makes any sense for this model }); return chart; } //============================================================ // Expose Public Variables //------------------------------------------------------------ chart.dispatch = dispatch; chart.x = function(_) { if (!arguments.length) return getX; getX = _; return chart; }; chart.y = function(_) { if (!arguments.length) return getY; getY = _; return chart; }; chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.xScale = function(_) { if (!arguments.length) return x; x = _; return chart; }; chart.yScale = function(_) { if (!arguments.length) return y; y = _; return chart; }; chart.xDomain = function(_) { if (!arguments.length) return xDomain; xDomain = _; return chart; }; chart.yDomain = function(_) { if (!arguments.length) return yDomain; yDomain = _; return chart; }; chart.forceX = function(_) { if (!arguments.length) return forceX; forceX = _; return chart; }; chart.forceY = function(_) { if (!arguments.length) return forceY; forceY = _; return chart; }; chart.padData = function(_) { if (!arguments.length) return padData; padData = _; return chart; }; chart.clipEdge = function(_) { if (!arguments.length) return clipEdge; clipEdge = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); return chart; }; chart.id = function(_) { if (!arguments.length) return id; id = _; return chart; }; //============================================================ return chart; } nv.models.historicalBarChart = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var bars = nv.models.historicalBar() , xAxis = nv.models.axis() , yAxis = nv.models.axis() , legend = nv.models.legend() ; var margin = {top: 30, right: 90, bottom: 50, left: 90} , color = nv.utils.defaultColor() , width = null , height = null , showLegend = false , showXAxis = true , showYAxis = true , rightAlignYAxis = false , tooltips = true , tooltip = function(key, x, y, e, graph) { return '<h3>' + key + '</h3>' + '<p>' + y + ' at ' + x + '</p>' } , x , y , state = {} , defaultState = null , noData = 'No Data Available.' , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState') ; xAxis .orient('bottom') .tickPadding(7) ; yAxis .orient( (rightAlignYAxis) ? 'right' : 'left') ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var showTooltip = function(e, offsetElement) { // New addition to calculate position if SVG is scaled with viewBox, may move TODO: consider implementing everywhere else if (offsetElement) { var svg = d3.select(offsetElement).select('svg'); var viewBox = (svg.node()) ? svg.attr('viewBox') : null; if (viewBox) { viewBox = viewBox.split(' '); var ratio = parseInt(svg.style('width')) / viewBox[2]; e.pos[0] = e.pos[0] * ratio; e.pos[1] = e.pos[1] * ratio; } } var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), top = e.pos[1] + ( offsetElement.offsetTop || 0), x = xAxis.tickFormat()(bars.x()(e.point, e.pointIndex)), y = yAxis.tickFormat()(bars.y()(e.point, e.pointIndex)), content = tooltip(e.series.key, x, y, e, chart); nv.tooltip.show([left, top], content, null, null, offsetElement); }; //============================================================ function chart(selection) { selection.each(function(data) { var container = d3.select(this), that = this; var availableWidth = (width || parseInt(container.style('width')) || 960) - margin.left - margin.right, availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; chart.update = function() { chart(selection) }; chart.container = this; //set state.disabled state.disabled = data.map(function(d) { return !!d.disabled }); if (!defaultState) { var key; defaultState = {}; for (key in state) { if (state[key] instanceof Array) defaultState[key] = state[key].slice(0); else defaultState[key] = state[key]; } } //------------------------------------------------------------ // Display noData message if there's nothing to show. if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) { var noDataText = container.selectAll('.nv-noData').data([noData]); noDataText.enter().append('text') .attr('class', 'nvd3 nv-noData') .attr('dy', '-.7em') .style('text-anchor', 'middle'); noDataText .attr('x', margin.left + availableWidth / 2) .attr('y', margin.top + availableHeight / 2) .text(function(d) { return d }); return chart; } else { container.selectAll('.nv-noData').remove(); } //------------------------------------------------------------ //------------------------------------------------------------ // Setup Scales x = bars.xScale(); y = bars.yScale(); //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-lineChart').data([data]); var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-lineChart').append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-x nv-axis'); gEnter.append('g').attr('class', 'nv-y nv-axis'); gEnter.append('g').attr('class', 'nv-barsWrap'); gEnter.append('g').attr('class', 'nv-legendWrap'); //------------------------------------------------------------ //------------------------------------------------------------ // Legend if (showLegend) { legend.width(availableWidth); g.select('.nv-legendWrap') .datum(data) .call(legend); if ( margin.top != legend.height()) { margin.top = legend.height(); availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; } wrap.select('.nv-legendWrap') .attr('transform', 'translate(0,' + (-margin.top) +')') } //------------------------------------------------------------ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); if (rightAlignYAxis) { g.select(".nv-y.nv-axis") .attr("transform", "translate(" + availableWidth + ",0)"); } //------------------------------------------------------------ // Main Chart Component(s) bars .width(availableWidth) .height(availableHeight) .color(data.map(function(d,i) { return d.color || color(d, i); }).filter(function(d,i) { return !data[i].disabled })); var barsWrap = g.select('.nv-barsWrap') .datum(data.filter(function(d) { return !d.disabled })) d3.transition(barsWrap).call(bars); //------------------------------------------------------------ //------------------------------------------------------------ // Setup Axes if (showXAxis) { xAxis .scale(x) .tickSize(-availableHeight, 0); g.select('.nv-x.nv-axis') .attr('transform', 'translate(0,' + y.range()[0] + ')'); g.select('.nv-x.nv-axis') .transition() .call(xAxis); } if (showYAxis) { yAxis .scale(y) .ticks( availableHeight / 36 ) .tickSize( -availableWidth, 0); g.select('.nv-y.nv-axis') .transition().duration(0) .call(yAxis); } //------------------------------------------------------------ //============================================================ // Event Handling/Dispatching (in chart's scope) //------------------------------------------------------------ legend.dispatch.on('legendClick', function(d,i) { d.disabled = !d.disabled; if (!data.filter(function(d) { return !d.disabled }).length) { data.map(function(d) { d.disabled = false; wrap.selectAll('.nv-series').classed('disabled', false); return d; }); } state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); selection.transition().call(chart); }); legend.dispatch.on('legendDblclick', function(d) { //Double clicking should always enable current series, and disabled all others. data.forEach(function(d) { d.disabled = true; }); d.disabled = false; state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); chart.update(); }); /* legend.dispatch.on('legendMouseover', function(d, i) { d.hover = true; selection.transition().call(chart) }); legend.dispatch.on('legendMouseout', function(d, i) { d.hover = false; selection.transition().call(chart) }); */ dispatch.on('tooltipShow', function(e) { if (tooltips) showTooltip(e, that.parentNode); }); dispatch.on('changeState', function(e) { if (typeof e.disabled !== 'undefined') { data.forEach(function(series,i) { series.disabled = e.disabled[i]; }); state.disabled = e.disabled; } selection.call(chart); }); //============================================================ }); return chart; } //============================================================ // Event Handling/Dispatching (out of chart's scope) //------------------------------------------------------------ bars.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); bars.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); dispatch.on('tooltipHide', function() { if (tooltips) nv.tooltip.cleanup(); }); //============================================================ //============================================================ // Expose Public Variables //------------------------------------------------------------ // expose chart's sub-components chart.dispatch = dispatch; chart.bars = bars; chart.legend = legend; chart.xAxis = xAxis; chart.yAxis = yAxis; d3.rebind(chart, bars, 'defined', 'isArea', 'x', 'y', 'size', 'xScale', 'yScale', 'xDomain', 'yDomain', 'forceX', 'forceY', 'interactive', 'clipEdge', 'clipVoronoi', 'id', 'interpolate'); chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); legend.color(color); return chart; }; chart.showLegend = function(_) { if (!arguments.length) return showLegend; showLegend = _; return chart; }; chart.showXAxis = function(_) { if (!arguments.length) return showXAxis; showXAxis = _; return chart; }; chart.showYAxis = function(_) { if (!arguments.length) return showYAxis; showYAxis = _; return chart; }; chart.rightAlignYAxis = function(_) { if(!arguments.length) return rightAlignYAxis; rightAlignYAxis = _; yAxis.orient( (_) ? 'right' : 'left'); return chart; }; chart.tooltips = function(_) { if (!arguments.length) return tooltips; tooltips = _; return chart; }; chart.tooltipContent = function(_) { if (!arguments.length) return tooltip; tooltip = _; return chart; }; chart.state = function(_) { if (!arguments.length) return state; state = _; return chart; }; chart.defaultState = function(_) { if (!arguments.length) return defaultState; defaultState = _; return chart; }; chart.noData = function(_) { if (!arguments.length) return noData; noData = _; return chart; }; //============================================================ return chart; } nv.models.indentedTree = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var margin = {top: 0, right: 0, bottom: 0, left: 0} //TODO: implement, maybe as margin on the containing div , width = 960 , height = 500 , color = nv.utils.defaultColor() , id = Math.floor(Math.random() * 10000) , header = true , filterZero = false , noData = "No Data Available." , childIndent = 20 , columns = [{key:'key', label: 'Name', type:'text'}] //TODO: consider functions like chart.addColumn, chart.removeColumn, instead of a block like this , tableClass = null , iconOpen = 'images/grey-plus.png' //TODO: consider removing this and replacing with a '+' or '-' unless user defines images , iconClose = 'images/grey-minus.png' , dispatch = d3.dispatch('elementClick', 'elementDblclick', 'elementMouseover', 'elementMouseout') ; //============================================================ var idx = 0; function chart(selection) { selection.each(function(data) { var depth = 1, container = d3.select(this); var tree = d3.layout.tree() .children(function(d) { return d.values }) .size([height, childIndent]); //Not sure if this is needed now that the result is HTML chart.update = function() { container.transition().duration(600).call(chart) }; //------------------------------------------------------------ // Display No Data message if there's nothing to show. if (!data[0]) data[0] = {key: noData}; //------------------------------------------------------------ var nodes = tree.nodes(data[0]); // nodes.map(function(d) { // d.id = i++; // }) //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = d3.select(this).selectAll('div').data([[nodes]]); var wrapEnter = wrap.enter().append('div').attr('class', 'nvd3 nv-wrap nv-indentedtree'); var tableEnter = wrapEnter.append('table'); var table = wrap.select('table').attr('width', '100%').attr('class', tableClass); //------------------------------------------------------------ if (header) { var thead = tableEnter.append('thead'); var theadRow1 = thead.append('tr'); columns.forEach(function(column) { theadRow1 .append('th') .attr('width', column.width ? column.width : '10%') .style('text-align', column.type == 'numeric' ? 'right' : 'left') .append('span') .text(column.label); }); } var tbody = table.selectAll('tbody') .data(function(d) { return d }); tbody.enter().append('tbody'); //compute max generations depth = d3.max(nodes, function(node) { return node.depth }); tree.size([height, depth * childIndent]); //TODO: see if this is necessary at all // Update the nodes… var node = tbody.selectAll('tr') // .data(function(d) { return d; }, function(d) { return d.id || (d.id == ++i)}); .data(function(d) { return d.filter(function(d) { return (filterZero && !d.children) ? filterZero(d) : true; } )}, function(d,i) { return d.id || (d.id || ++idx)}); //.style('display', 'table-row'); //TODO: see if this does anything node.exit().remove(); node.select('img.nv-treeicon') .attr('src', icon) .classed('folded', folded); var nodeEnter = node.enter().append('tr'); columns.forEach(function(column, index) { var nodeName = nodeEnter.append('td') .style('padding-left', function(d) { return (index ? 0 : d.depth * childIndent + 12 + (icon(d) ? 0 : 16)) + 'px' }, 'important') //TODO: check why I did the ternary here .style('text-align', column.type == 'numeric' ? 'right' : 'left'); if (index == 0) { nodeName.append('img') .classed('nv-treeicon', true) .classed('nv-folded', folded) .attr('src', icon) .style('width', '14px') .style('height', '14px') .style('padding', '0 1px') .style('display', function(d) { return icon(d) ? 'inline-block' : 'none'; }) .on('click', click); } nodeName.append('span') .attr('class', d3.functor(column.classes) ) .text(function(d) { return column.format ? column.format(d) : (d[column.key] || '-') }); if (column.showCount) { nodeName.append('span') .attr('class', 'nv-childrenCount'); node.selectAll('span.nv-childrenCount').text(function(d) { return ((d.values && d.values.length) || (d._values && d._values.length)) ? //If this is a parent '(' + ((d.values && (d.values.filter(function(d) { return filterZero ? filterZero(d) : true; }).length)) //If children are in values check its children and filter || (d._values && d._values.filter(function(d) { return filterZero ? filterZero(d) : true; }).length) //Otherwise, do the same, but with the other name, _values... || 0) + ')' //This is the catch-all in case there are no children after a filter : '' //If this is not a parent, just give an empty string }); } if (column.click) nodeName.select('span').on('click', column.click); }); node .order() .on('click', function(d) { dispatch.elementClick({ row: this, //TODO: decide whether or not this should be consistent with scatter/line events or should be an html link (a href) data: d, pos: [d.x, d.y] }); }) .on('dblclick', function(d) { dispatch.elementDblclick({ row: this, data: d, pos: [d.x, d.y] }); }) .on('mouseover', function(d) { dispatch.elementMouseover({ row: this, data: d, pos: [d.x, d.y] }); }) .on('mouseout', function(d) { dispatch.elementMouseout({ row: this, data: d, pos: [d.x, d.y] }); }); // Toggle children on click. function click(d, _, unshift) { d3.event.stopPropagation(); if(d3.event.shiftKey && !unshift) { //If you shift-click, it'll toggle fold all the children, instead of itself d3.event.shiftKey = false; d.values && d.values.forEach(function(node){ if (node.values || node._values) { click(node, 0, true); } }); return true; } if(!hasChildren(d)) { //download file //window.location.href = d.url; return true; } if (d.values) { d._values = d.values; d.values = null; } else { d.values = d._values; d._values = null; } chart.update(); } function icon(d) { return (d._values && d._values.length) ? iconOpen : (d.values && d.values.length) ? iconClose : ''; } function folded(d) { return (d._values && d._values.length); } function hasChildren(d) { var values = d.values || d._values; return (values && values.length); } }); return chart; } //============================================================ // Expose Public Variables //------------------------------------------------------------ chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); scatter.color(color); return chart; }; chart.id = function(_) { if (!arguments.length) return id; id = _; return chart; }; chart.header = function(_) { if (!arguments.length) return header; header = _; return chart; }; chart.noData = function(_) { if (!arguments.length) return noData; noData = _; return chart; }; chart.filterZero = function(_) { if (!arguments.length) return filterZero; filterZero = _; return chart; }; chart.columns = function(_) { if (!arguments.length) return columns; columns = _; return chart; }; chart.tableClass = function(_) { if (!arguments.length) return tableClass; tableClass = _; return chart; }; chart.iconOpen = function(_){ if (!arguments.length) return iconOpen; iconOpen = _; return chart; } chart.iconClose = function(_){ if (!arguments.length) return iconClose; iconClose = _; return chart; } //============================================================ return chart; };nv.models.legend = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var margin = {top: 5, right: 0, bottom: 5, left: 0} , width = 400 , height = 20 , getKey = function(d) { return d.key } , color = nv.utils.defaultColor() , align = true , dispatch = d3.dispatch('legendClick', 'legendDblclick', 'legendMouseover', 'legendMouseout') ; //============================================================ function chart(selection) { selection.each(function(data) { var availableWidth = width - margin.left - margin.right, container = d3.select(this); //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-legend').data([data]); var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-legend').append('g'); var g = wrap.select('g'); wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ var series = g.selectAll('.nv-series') .data(function(d) { return d }); var seriesEnter = series.enter().append('g').attr('class', 'nv-series') .on('mouseover', function(d,i) { dispatch.legendMouseover(d,i); //TODO: Make consistent with other event objects }) .on('mouseout', function(d,i) { dispatch.legendMouseout(d,i); }) .on('click', function(d,i) { dispatch.legendClick(d,i); }) .on('dblclick', function(d,i) { dispatch.legendDblclick(d,i); }); seriesEnter.append('circle') .style('stroke-width', 2) .attr('r', 5); seriesEnter.append('text') .attr('text-anchor', 'start') .attr('dy', '.32em') .attr('dx', '8'); series.classed('disabled', function(d) { return d.disabled }); series.exit().remove(); series.select('circle') .style('fill', function(d,i) { return d.color || color(d,i)}) .style('stroke', function(d,i) { return d.color || color(d, i) }); series.select('text').text(getKey); //TODO: implement fixed-width and max-width options (max-width is especially useful with the align option) // NEW ALIGNING CODE, TODO: clean up if (align) { var seriesWidths = []; series.each(function(d,i) { var legendText = d3.select(this).select('text'); var svgComputedTextLength = legendText.node().getComputedTextLength() || nv.utils.calcApproxTextWidth(legendText); seriesWidths.push(svgComputedTextLength + 28); // 28 is ~ the width of the circle plus some padding }); //nv.log('Series Widths: ', JSON.stringify(seriesWidths)); var seriesPerRow = 0; var legendWidth = 0; var columnWidths = []; while ( legendWidth < availableWidth && seriesPerRow < seriesWidths.length) { columnWidths[seriesPerRow] = seriesWidths[seriesPerRow]; legendWidth += seriesWidths[seriesPerRow++]; } while ( legendWidth > availableWidth && seriesPerRow > 1 ) { columnWidths = []; seriesPerRow--; for (k = 0; k < seriesWidths.length; k++) { if (seriesWidths[k] > (columnWidths[k % seriesPerRow] || 0) ) columnWidths[k % seriesPerRow] = seriesWidths[k]; } legendWidth = columnWidths.reduce(function(prev, cur, index, array) { return prev + cur; }); } //console.log(columnWidths, legendWidth, seriesPerRow); var xPositions = []; for (var i = 0, curX = 0; i < seriesPerRow; i++) { xPositions[i] = curX; curX += columnWidths[i]; } series .attr('transform', function(d, i) { return 'translate(' + xPositions[i % seriesPerRow] + ',' + (5 + Math.floor(i / seriesPerRow) * 20) + ')'; }); //position legend as far right as possible within the total width g.attr('transform', 'translate(' + (width - margin.right - legendWidth) + ',' + margin.top + ')'); height = margin.top + margin.bottom + (Math.ceil(seriesWidths.length / seriesPerRow) * 20); } else { var ypos = 5, newxpos = 5, maxwidth = 0, xpos; series .attr('transform', function(d, i) { var length = d3.select(this).select('text').node().getComputedTextLength() + 28; xpos = newxpos; if (width < margin.left + margin.right + xpos + length) { newxpos = xpos = 5; ypos += 20; } newxpos += length; if (newxpos > maxwidth) maxwidth = newxpos; return 'translate(' + xpos + ',' + ypos + ')'; }); //position legend as far right as possible within the total width g.attr('transform', 'translate(' + (width - margin.right - maxwidth) + ',' + margin.top + ')'); height = margin.top + margin.bottom + ypos + 15; } }); return chart; } //============================================================ // Expose Public Variables //------------------------------------------------------------ chart.dispatch = dispatch; chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.key = function(_) { if (!arguments.length) return getKey; getKey = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); return chart; }; chart.align = function(_) { if (!arguments.length) return align; align = _; return chart; }; //============================================================ return chart; } nv.models.line = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var scatter = nv.models.scatter() ; var margin = {top: 0, right: 0, bottom: 0, left: 0} , width = 960 , height = 500 , color = nv.utils.defaultColor() // a function that returns a color , getX = function(d) { return d.x } // accessor to get the x value from a data point , getY = function(d) { return d.y } // accessor to get the y value from a data point , defined = function(d,i) { return !isNaN(getY(d,i)) && getY(d,i) !== null } // allows a line to be not continuous when it is not defined , isArea = function(d) { return d.area } // decides if a line is an area or just a line , clipEdge = false // if true, masks lines within x and y scale , x //can be accessed via chart.xScale() , y //can be accessed via chart.yScale() , interpolate = "linear" // controls the line interpolation ; scatter .size(16) // default size .sizeDomain([16,256]) //set to speed up calculation, needs to be unset if there is a custom size accessor ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var x0, y0 //used to store previous scales ; //============================================================ function chart(selection) { selection.each(function(data) { var availableWidth = width - margin.left - margin.right, availableHeight = height - margin.top - margin.bottom, container = d3.select(this); //------------------------------------------------------------ // Setup Scales x = scatter.xScale(); y = scatter.yScale(); x0 = x0 || x; y0 = y0 || y; //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-line').data([data]); var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-line'); var defsEnter = wrapEnter.append('defs'); var gEnter = wrapEnter.append('g'); var g = wrap.select('g') gEnter.append('g').attr('class', 'nv-groups'); gEnter.append('g').attr('class', 'nv-scatterWrap'); wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ scatter .width(availableWidth) .height(availableHeight) var scatterWrap = wrap.select('.nv-scatterWrap'); //.datum(data); // Data automatically trickles down from the wrap d3.transition(scatterWrap).call(scatter); defsEnter.append('clipPath') .attr('id', 'nv-edge-clip-' + scatter.id()) .append('rect'); wrap.select('#nv-edge-clip-' + scatter.id() + ' rect') .attr('width', availableWidth) .attr('height', availableHeight); g .attr('clip-path', clipEdge ? 'url(#nv-edge-clip-' + scatter.id() + ')' : ''); scatterWrap .attr('clip-path', clipEdge ? 'url(#nv-edge-clip-' + scatter.id() + ')' : ''); var groups = wrap.select('.nv-groups').selectAll('.nv-group') .data(function(d) { return d }, function(d) { return d.key }); groups.enter().append('g') .style('stroke-opacity', 1e-6) .style('fill-opacity', 1e-6); d3.transition(groups.exit()) .style('stroke-opacity', 1e-6) .style('fill-opacity', 1e-6) .remove(); groups .attr('class', function(d,i) { return 'nv-group nv-series-' + i }) .classed('hover', function(d) { return d.hover }) .style('fill', function(d,i){ return color(d, i) }) .style('stroke', function(d,i){ return color(d, i)}); d3.transition(groups) .style('stroke-opacity', 1) .style('fill-opacity', .5); var areaPaths = groups.selectAll('path.nv-area') .data(function(d) { return isArea(d) ? [d] : [] }); // this is done differently than lines because I need to check if series is an area areaPaths.enter().append('path') .attr('class', 'nv-area') .attr('d', function(d) { return d3.svg.area() .interpolate(interpolate) .defined(defined) .x(function(d,i) { return x0(getX(d,i)) }) .y0(function(d,i) { return y0(getY(d,i)) }) .y1(function(d,i) { return y0( y.domain()[0] <= 0 ? y.domain()[1] >= 0 ? 0 : y.domain()[1] : y.domain()[0] ) }) //.y1(function(d,i) { return y0(0) }) //assuming 0 is within y domain.. may need to tweak this .apply(this, [d.values]) }); d3.transition(groups.exit().selectAll('path.nv-area')) .attr('d', function(d) { return d3.svg.area() .interpolate(interpolate) .defined(defined) .x(function(d,i) { return x(getX(d,i)) }) .y0(function(d,i) { return y(getY(d,i)) }) .y1(function(d,i) { return y( y.domain()[0] <= 0 ? y.domain()[1] >= 0 ? 0 : y.domain()[1] : y.domain()[0] ) }) //.y1(function(d,i) { return y0(0) }) //assuming 0 is within y domain.. may need to tweak this .apply(this, [d.values]) }); d3.transition(areaPaths) .attr('d', function(d) { return d3.svg.area() .interpolate(interpolate) .defined(defined) .x(function(d,i) { return x(getX(d,i)) }) .y0(function(d,i) { return y(getY(d,i)) }) .y1(function(d,i) { return y( y.domain()[0] <= 0 ? y.domain()[1] >= 0 ? 0 : y.domain()[1] : y.domain()[0] ) }) //.y1(function(d,i) { return y0(0) }) //assuming 0 is within y domain.. may need to tweak this .apply(this, [d.values]) }); var linePaths = groups.selectAll('path.nv-line') .data(function(d) { return [d.values] }); linePaths.enter().append('path') .attr('class', 'nv-line') .attr('d', d3.svg.line() .interpolate(interpolate) .defined(defined) .x(function(d,i) { return x0(getX(d,i)) }) .y(function(d,i) { return y0(getY(d,i)) }) ); d3.transition(groups.exit().selectAll('path.nv-line')) .attr('d', d3.svg.line() .interpolate(interpolate) .defined(defined) .x(function(d,i) { return x(getX(d,i)) }) .y(function(d,i) { return y(getY(d,i)) }) ); d3.transition(linePaths) .attr('d', d3.svg.line() .interpolate(interpolate) .defined(defined) .x(function(d,i) { return x(getX(d,i)) }) .y(function(d,i) { return y(getY(d,i)) }) ); //store old scales for use in transitions on update x0 = x.copy(); y0 = y.copy(); }); return chart; } //============================================================ // Expose Public Variables //------------------------------------------------------------ chart.dispatch = scatter.dispatch; chart.scatter = scatter; d3.rebind(chart, scatter, 'id', 'interactive', 'size', 'xScale', 'yScale', 'zScale', 'xDomain', 'yDomain', 'sizeDomain', 'forceX', 'forceY', 'forceSize', 'clipVoronoi', 'clipRadius', 'padData'); chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.x = function(_) { if (!arguments.length) return getX; getX = _; scatter.x(_); return chart; }; chart.y = function(_) { if (!arguments.length) return getY; getY = _; scatter.y(_); return chart; }; chart.clipEdge = function(_) { if (!arguments.length) return clipEdge; clipEdge = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); scatter.color(color); return chart; }; chart.interpolate = function(_) { if (!arguments.length) return interpolate; interpolate = _; return chart; }; chart.defined = function(_) { if (!arguments.length) return defined; defined = _; return chart; }; chart.isArea = function(_) { if (!arguments.length) return isArea; isArea = d3.functor(_); return chart; }; //============================================================ return chart; } nv.models.lineChart = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var lines = nv.models.line() , xAxis = nv.models.axis() , yAxis = nv.models.axis() , legend = nv.models.legend() ; //set margin.right to 23 to fit dates on the x-axis within the chart var margin = {top: 30, right: 20, bottom: 50, left: 60} , color = nv.utils.defaultColor() , width = null , height = null , showLegend = true , showXAxis = true , showYAxis = true , rightAlignYAxis = false , tooltips = true , tooltip = function(key, x, y, e, graph) { return '<h3>' + key + '</h3>' + '<p>' + y + ' at ' + x + '</p>' } , x , y , state = {} , defaultState = null , noData = 'No Data Available.' , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState') ; xAxis .orient('bottom') .tickPadding(7) ; yAxis .orient((rightAlignYAxis) ? 'right' : 'left') ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var showTooltip = function(e, offsetElement) { // New addition to calculate position if SVG is scaled with viewBox, may move TODO: consider implementing everywhere else if (offsetElement) { var svg = d3.select(offsetElement).select('svg'); var viewBox = (svg.node()) ? svg.attr('viewBox') : null; if (viewBox) { viewBox = viewBox.split(' '); var ratio = parseInt(svg.style('width')) / viewBox[2]; e.pos[0] = e.pos[0] * ratio; e.pos[1] = e.pos[1] * ratio; } } var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), top = e.pos[1] + ( offsetElement.offsetTop || 0), x = xAxis.tickFormat()(lines.x()(e.point, e.pointIndex)), y = yAxis.tickFormat()(lines.y()(e.point, e.pointIndex)), content = tooltip(e.series.key, x, y, e, chart); nv.tooltip.show([left, top], content, null, null, offsetElement); }; //============================================================ function chart(selection) { selection.each(function(data) { var container = d3.select(this), that = this; var availableWidth = (width || parseInt(container.style('width')) || 960) - margin.left - margin.right, availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; chart.update = function() { container.transition().call(chart) }; chart.container = this; //set state.disabled state.disabled = data.map(function(d) { return !!d.disabled }); if (!defaultState) { var key; defaultState = {}; for (key in state) { if (state[key] instanceof Array) defaultState[key] = state[key].slice(0); else defaultState[key] = state[key]; } } //------------------------------------------------------------ // Display noData message if there's nothing to show. if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) { var noDataText = container.selectAll('.nv-noData').data([noData]); noDataText.enter().append('text') .attr('class', 'nvd3 nv-noData') .attr('dy', '-.7em') .style('text-anchor', 'middle'); noDataText .attr('x', margin.left + availableWidth / 2) .attr('y', margin.top + availableHeight / 2) .text(function(d) { return d }); return chart; } else { container.selectAll('.nv-noData').remove(); } //------------------------------------------------------------ //------------------------------------------------------------ // Setup Scales x = lines.xScale(); y = lines.yScale(); //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-lineChart').data([data]); var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-lineChart').append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-x nv-axis'); gEnter.append('g').attr('class', 'nv-y nv-axis'); gEnter.append('g').attr('class', 'nv-linesWrap'); gEnter.append('g').attr('class', 'nv-legendWrap'); //------------------------------------------------------------ //------------------------------------------------------------ // Legend if (showLegend) { legend.width(availableWidth); g.select('.nv-legendWrap') .datum(data) .call(legend); if ( margin.top != legend.height()) { margin.top = legend.height(); availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; } wrap.select('.nv-legendWrap') .attr('transform', 'translate(0,' + (-margin.top) +')') } //------------------------------------------------------------ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); if (rightAlignYAxis) { g.select(".nv-y.nv-axis") .attr("transform", "translate(" + availableWidth + ",0)"); } //------------------------------------------------------------ // Main Chart Component(s) lines .width(availableWidth) .height(availableHeight) .color(data.map(function(d,i) { return d.color || color(d, i); }).filter(function(d,i) { return !data[i].disabled })); var linesWrap = g.select('.nv-linesWrap') .datum(data.filter(function(d) { return !d.disabled })) d3.transition(linesWrap).call(lines); //------------------------------------------------------------ //------------------------------------------------------------ // Setup Axes if (showXAxis) { xAxis .scale(x) .ticks( availableWidth / 100 ) .tickSize(-availableHeight, 0); g.select('.nv-x.nv-axis') .attr('transform', 'translate(0,' + y.range()[0] + ')'); d3.transition(g.select('.nv-x.nv-axis')) .call(xAxis); } if (showYAxis) { yAxis .scale(y) .ticks( availableHeight / 36 ) .tickSize( -availableWidth, 0); d3.transition(g.select('.nv-y.nv-axis')) .call(yAxis); } //------------------------------------------------------------ //============================================================ // Event Handling/Dispatching (in chart's scope) //------------------------------------------------------------ legend.dispatch.on('legendClick', function(d,i) { d.disabled = !d.disabled; if (!data.filter(function(d) { return !d.disabled }).length) { data.map(function(d) { d.disabled = false; wrap.selectAll('.nv-series').classed('disabled', false); return d; }); } state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); // container.transition().call(chart); chart.update(); }); legend.dispatch.on('legendDblclick', function(d) { //Double clicking should always enable current series, and disabled all others. data.forEach(function(d) { d.disabled = true; }); d.disabled = false; state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); chart.update(); }); /* legend.dispatch.on('legendMouseover', function(d, i) { d.hover = true; selection.transition().call(chart) }); legend.dispatch.on('legendMouseout', function(d, i) { d.hover = false; selection.transition().call(chart) }); */ dispatch.on('tooltipShow', function(e) { if (tooltips) showTooltip(e, that.parentNode); }); dispatch.on('changeState', function(e) { if (typeof e.disabled !== 'undefined') { data.forEach(function(series,i) { series.disabled = e.disabled[i]; }); state.disabled = e.disabled; } chart.update(); }); //============================================================ }); return chart; } //============================================================ // Event Handling/Dispatching (out of chart's scope) //------------------------------------------------------------ lines.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); lines.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); dispatch.on('tooltipHide', function() { if (tooltips) nv.tooltip.cleanup(); }); //============================================================ //============================================================ // Expose Public Variables //------------------------------------------------------------ // expose chart's sub-components chart.dispatch = dispatch; chart.lines = lines; chart.legend = legend; chart.xAxis = xAxis; chart.yAxis = yAxis; d3.rebind(chart, lines, 'defined', 'isArea', 'x', 'y', 'size', 'xScale', 'yScale', 'xDomain', 'yDomain', 'forceX', 'forceY', 'interactive', 'clipEdge', 'clipVoronoi', 'id', 'interpolate'); chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); legend.color(color); return chart; }; chart.showLegend = function(_) { if (!arguments.length) return showLegend; showLegend = _; return chart; }; chart.showXAxis = function(_) { if (!arguments.length) return showXAxis; showXAxis = _; return chart; }; chart.showYAxis = function(_) { if (!arguments.length) return showYAxis; showYAxis = _; return chart; }; chart.rightAlignYAxis = function(_) { if(!arguments.length) return rightAlignYAxis; rightAlignYAxis = _; yAxis.orient( (_) ? 'right' : 'left'); return chart; }; chart.tooltips = function(_) { if (!arguments.length) return tooltips; tooltips = _; return chart; }; chart.tooltipContent = function(_) { if (!arguments.length) return tooltip; tooltip = _; return chart; }; chart.state = function(_) { if (!arguments.length) return state; state = _; return chart; }; chart.defaultState = function(_) { if (!arguments.length) return defaultState; defaultState = _; return chart; }; chart.noData = function(_) { if (!arguments.length) return noData; noData = _; return chart; }; //============================================================ return chart; } nv.models.linePlusBarChart = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var lines = nv.models.line() , bars = nv.models.historicalBar() , xAxis = nv.models.axis() , y1Axis = nv.models.axis() , y2Axis = nv.models.axis() , legend = nv.models.legend() ; var margin = {top: 30, right: 60, bottom: 50, left: 60} , width = null , height = null , getX = function(d) { return d.x } , getY = function(d) { return d.y } , color = nv.utils.defaultColor() , showLegend = true , tooltips = true , tooltip = function(key, x, y, e, graph) { return '<h3>' + key + '</h3>' + '<p>' + y + ' at ' + x + '</p>'; } , x , y1 , y2 , state = {} , defaultState = null , noData = "No Data Available." , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState') ; bars .padData(true) ; lines .clipEdge(false) .padData(true) ; xAxis .orient('bottom') .tickPadding(7) .highlightZero(false) ; y1Axis .orient('left') ; y2Axis .orient('right') ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var showTooltip = function(e, offsetElement) { var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), top = e.pos[1] + ( offsetElement.offsetTop || 0), x = xAxis.tickFormat()(lines.x()(e.point, e.pointIndex)), y = (e.series.bar ? y1Axis : y2Axis).tickFormat()(lines.y()(e.point, e.pointIndex)), content = tooltip(e.series.key, x, y, e, chart); nv.tooltip.show([left, top], content, e.value < 0 ? 'n' : 's', null, offsetElement); } ; //------------------------------------------------------------ function chart(selection) { selection.each(function(data) { var container = d3.select(this), that = this; var availableWidth = (width || parseInt(container.style('width')) || 960) - margin.left - margin.right, availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; chart.update = function() { container.transition().call(chart); }; // chart.container = this; //set state.disabled state.disabled = data.map(function(d) { return !!d.disabled }); if (!defaultState) { var key; defaultState = {}; for (key in state) { if (state[key] instanceof Array) defaultState[key] = state[key].slice(0); else defaultState[key] = state[key]; } } //------------------------------------------------------------ // Display No Data message if there's nothing to show. if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) { var noDataText = container.selectAll('.nv-noData').data([noData]); noDataText.enter().append('text') .attr('class', 'nvd3 nv-noData') .attr('dy', '-.7em') .style('text-anchor', 'middle'); noDataText .attr('x', margin.left + availableWidth / 2) .attr('y', margin.top + availableHeight / 2) .text(function(d) { return d }); return chart; } else { container.selectAll('.nv-noData').remove(); } //------------------------------------------------------------ //------------------------------------------------------------ // Setup Scales var dataBars = data.filter(function(d) { return !d.disabled && d.bar }); var dataLines = data.filter(function(d) { return !d.bar }); // removed the !d.disabled clause here to fix Issue #240 //x = xAxis.scale(); x = dataLines.filter(function(d) { return !d.disabled; }).length && dataLines.filter(function(d) { return !d.disabled; })[0].values.length ? lines.xScale() : bars.xScale(); //x = dataLines.filter(function(d) { return !d.disabled; }).length ? lines.xScale() : bars.xScale(); //old code before change above y1 = bars.yScale(); y2 = lines.yScale(); //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = d3.select(this).selectAll('g.nv-wrap.nv-linePlusBar').data([data]); var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-linePlusBar').append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-x nv-axis'); gEnter.append('g').attr('class', 'nv-y1 nv-axis'); gEnter.append('g').attr('class', 'nv-y2 nv-axis'); gEnter.append('g').attr('class', 'nv-barsWrap'); gEnter.append('g').attr('class', 'nv-linesWrap'); gEnter.append('g').attr('class', 'nv-legendWrap'); //------------------------------------------------------------ //------------------------------------------------------------ // Legend if (showLegend) { legend.width( availableWidth / 2 ); g.select('.nv-legendWrap') .datum(data.map(function(series) { series.originalKey = series.originalKey === undefined ? series.key : series.originalKey; series.key = series.originalKey + (series.bar ? ' (left axis)' : ' (right axis)'); return series; })) .call(legend); if ( margin.top != legend.height()) { margin.top = legend.height(); availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; } g.select('.nv-legendWrap') .attr('transform', 'translate(' + ( availableWidth / 2 ) + ',' + (-margin.top) +')'); } //------------------------------------------------------------ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ // Main Chart Component(s) lines .width(availableWidth) .height(availableHeight) .color(data.map(function(d,i) { return d.color || color(d, i); }).filter(function(d,i) { return !data[i].disabled && !data[i].bar })) bars .width(availableWidth) .height(availableHeight) .color(data.map(function(d,i) { return d.color || color(d, i); }).filter(function(d,i) { return !data[i].disabled && data[i].bar })) var barsWrap = g.select('.nv-barsWrap') .datum(dataBars.length ? dataBars : [{values:[]}]) var linesWrap = g.select('.nv-linesWrap') .datum(dataLines[0] && !dataLines[0].disabled ? dataLines : [{values:[]}] ); //.datum(!dataLines[0].disabled ? dataLines : [{values:dataLines[0].values.map(function(d) { return [d[0], null] }) }] ); d3.transition(barsWrap).call(bars); d3.transition(linesWrap).call(lines); //------------------------------------------------------------ //------------------------------------------------------------ // Setup Axes xAxis .scale(x) .ticks( availableWidth / 100 ) .tickSize(-availableHeight, 0); g.select('.nv-x.nv-axis') .attr('transform', 'translate(0,' + y1.range()[0] + ')'); d3.transition(g.select('.nv-x.nv-axis')) .call(xAxis); y1Axis .scale(y1) .ticks( availableHeight / 36 ) .tickSize(-availableWidth, 0); d3.transition(g.select('.nv-y1.nv-axis')) .style('opacity', dataBars.length ? 1 : 0) .call(y1Axis); y2Axis .scale(y2) .ticks( availableHeight / 36 ) .tickSize(dataBars.length ? 0 : -availableWidth, 0); // Show the y2 rules only if y1 has none g.select('.nv-y2.nv-axis') .style('opacity', dataLines.length ? 1 : 0) .attr('transform', 'translate(' + availableWidth + ',0)'); //.attr('transform', 'translate(' + x.range()[1] + ',0)'); d3.transition(g.select('.nv-y2.nv-axis')) .call(y2Axis); //------------------------------------------------------------ //============================================================ // Event Handling/Dispatching (in chart's scope) //------------------------------------------------------------ legend.dispatch.on('legendClick', function(d,i) { d.disabled = !d.disabled; if (!data.filter(function(d) { return !d.disabled }).length) { data.map(function(d) { d.disabled = false; wrap.selectAll('.nv-series').classed('disabled', false); return d; }); } state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); chart.update(); }); legend.dispatch.on('legendDblclick', function(d) { //Double clicking should always enable current series, and disabled all others. data.forEach(function(d) { d.disabled = true; }); d.disabled = false; state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); chart.update(); }); dispatch.on('tooltipShow', function(e) { if (tooltips) showTooltip(e, that.parentNode); }); // Update chart from a state object passed to event handler dispatch.on('changeState', function(e) { if (typeof e.disabled !== 'undefined') { data.forEach(function(series,i) { series.disabled = e.disabled[i]; }); state.disabled = e.disabled; } chart.update(); }); //============================================================ }); return chart; } //============================================================ // Event Handling/Dispatching (out of chart's scope) //------------------------------------------------------------ lines.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); lines.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); bars.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); bars.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); dispatch.on('tooltipHide', function() { if (tooltips) nv.tooltip.cleanup(); }); //============================================================ //============================================================ // Expose Public Variables //------------------------------------------------------------ // expose chart's sub-components chart.dispatch = dispatch; chart.legend = legend; chart.lines = lines; chart.bars = bars; chart.xAxis = xAxis; chart.y1Axis = y1Axis; chart.y2Axis = y2Axis; d3.rebind(chart, lines, 'defined', 'size', 'clipVoronoi', 'interpolate'); //TODO: consider rebinding x, y and some other stuff, and simply do soemthign lile bars.x(lines.x()), etc. //d3.rebind(chart, lines, 'x', 'y', 'size', 'xDomain', 'yDomain', 'forceX', 'forceY', 'interactive', 'clipEdge', 'clipVoronoi', 'id'); chart.x = function(_) { if (!arguments.length) return getX; getX = _; lines.x(_); bars.x(_); return chart; }; chart.y = function(_) { if (!arguments.length) return getY; getY = _; lines.y(_); bars.y(_); return chart; }; chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); legend.color(color); return chart; }; chart.showLegend = function(_) { if (!arguments.length) return showLegend; showLegend = _; return chart; }; chart.tooltips = function(_) { if (!arguments.length) return tooltips; tooltips = _; return chart; }; chart.tooltipContent = function(_) { if (!arguments.length) return tooltip; tooltip = _; return chart; }; chart.state = function(_) { if (!arguments.length) return state; state = _; return chart; }; chart.defaultState = function(_) { if (!arguments.length) return defaultState; defaultState = _; return chart; }; chart.noData = function(_) { if (!arguments.length) return noData; noData = _; return chart; }; //============================================================ return chart; } nv.models.lineWithFocusChart = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var lines = nv.models.line() , lines2 = nv.models.line() , xAxis = nv.models.axis() , yAxis = nv.models.axis() , x2Axis = nv.models.axis() , y2Axis = nv.models.axis() , legend = nv.models.legend() , brush = d3.svg.brush() ; var margin = {top: 30, right: 30, bottom: 30, left: 60} , margin2 = {top: 0, right: 30, bottom: 20, left: 60} , color = nv.utils.defaultColor() , width = null , height = null , height2 = 100 , x , y , x2 , y2 , showLegend = true , brushExtent = null , tooltips = true , tooltip = function(key, x, y, e, graph) { return '<h3>' + key + '</h3>' + '<p>' + y + ' at ' + x + '</p>' } , noData = "No Data Available." , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'brush') ; lines .clipEdge(true) ; lines2 .interactive(false) ; xAxis .orient('bottom') .tickPadding(5) ; yAxis .orient('left') ; x2Axis .orient('bottom') .tickPadding(5) ; y2Axis .orient('left') ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var showTooltip = function(e, offsetElement) { var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), top = e.pos[1] + ( offsetElement.offsetTop || 0), x = xAxis.tickFormat()(lines.x()(e.point, e.pointIndex)), y = yAxis.tickFormat()(lines.y()(e.point, e.pointIndex)), content = tooltip(e.series.key, x, y, e, chart); nv.tooltip.show([left, top], content, null, null, offsetElement); }; //============================================================ function chart(selection) { selection.each(function(data) { var container = d3.select(this), that = this; var availableWidth = (width || parseInt(container.style('width')) || 960) - margin.left - margin.right, availableHeight1 = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom - height2, availableHeight2 = height2 - margin2.top - margin2.bottom; chart.update = function() { container.transition().call(chart) }; chart.container = this; //------------------------------------------------------------ // Display No Data message if there's nothing to show. if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) { var noDataText = container.selectAll('.nv-noData').data([noData]); noDataText.enter().append('text') .attr('class', 'nvd3 nv-noData') .attr('dy', '-.7em') .style('text-anchor', 'middle'); noDataText .attr('x', margin.left + availableWidth / 2) .attr('y', margin.top + availableHeight1 / 2) .text(function(d) { return d }); return chart; } else { container.selectAll('.nv-noData').remove(); } //------------------------------------------------------------ //------------------------------------------------------------ // Setup Scales x = lines.xScale(); y = lines.yScale(); x2 = lines2.xScale(); y2 = lines2.yScale(); //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-lineWithFocusChart').data([data]); var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-lineWithFocusChart').append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-legendWrap'); var focusEnter = gEnter.append('g').attr('class', 'nv-focus'); focusEnter.append('g').attr('class', 'nv-x nv-axis'); focusEnter.append('g').attr('class', 'nv-y nv-axis'); focusEnter.append('g').attr('class', 'nv-linesWrap'); var contextEnter = gEnter.append('g').attr('class', 'nv-context'); contextEnter.append('g').attr('class', 'nv-x nv-axis'); contextEnter.append('g').attr('class', 'nv-y nv-axis'); contextEnter.append('g').attr('class', 'nv-linesWrap'); contextEnter.append('g').attr('class', 'nv-brushBackground'); contextEnter.append('g').attr('class', 'nv-x nv-brush'); //------------------------------------------------------------ //------------------------------------------------------------ // Legend if (showLegend) { legend.width(availableWidth); g.select('.nv-legendWrap') .datum(data) .call(legend); if ( margin.top != legend.height()) { margin.top = legend.height(); availableHeight1 = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom - height2; } g.select('.nv-legendWrap') .attr('transform', 'translate(0,' + (-margin.top) +')') } //------------------------------------------------------------ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ // Main Chart Component(s) lines .width(availableWidth) .height(availableHeight1) .color( data .map(function(d,i) { return d.color || color(d, i); }) .filter(function(d,i) { return !data[i].disabled; }) ); lines2 .defined(lines.defined()) .width(availableWidth) .height(availableHeight2) .color( data .map(function(d,i) { return d.color || color(d, i); }) .filter(function(d,i) { return !data[i].disabled; }) ); g.select('.nv-context') .attr('transform', 'translate(0,' + ( availableHeight1 + margin.bottom + margin2.top) + ')') var contextLinesWrap = g.select('.nv-context .nv-linesWrap') .datum(data.filter(function(d) { return !d.disabled })) d3.transition(contextLinesWrap).call(lines2); //------------------------------------------------------------ /* var focusLinesWrap = g.select('.nv-focus .nv-linesWrap') .datum(data.filter(function(d) { return !d.disabled })) d3.transition(focusLinesWrap).call(lines); */ //------------------------------------------------------------ // Setup Main (Focus) Axes xAxis .scale(x) .ticks( availableWidth / 100 ) .tickSize(-availableHeight1, 0); yAxis .scale(y) .ticks( availableHeight1 / 36 ) .tickSize( -availableWidth, 0); g.select('.nv-focus .nv-x.nv-axis') .attr('transform', 'translate(0,' + availableHeight1 + ')'); //------------------------------------------------------------ //------------------------------------------------------------ // Setup Brush brush .x(x2) .on('brush', onBrush); if (brushExtent) brush.extent(brushExtent); var brushBG = g.select('.nv-brushBackground').selectAll('g') .data([brushExtent || brush.extent()]) var brushBGenter = brushBG.enter() .append('g'); brushBGenter.append('rect') .attr('class', 'left') .attr('x', 0) .attr('y', 0) .attr('height', availableHeight2); brushBGenter.append('rect') .attr('class', 'right') .attr('x', 0) .attr('y', 0) .attr('height', availableHeight2); gBrush = g.select('.nv-x.nv-brush') .call(brush); gBrush.selectAll('rect') //.attr('y', -5) .attr('height', availableHeight2); gBrush.selectAll('.resize').append('path').attr('d', resizePath); onBrush(); //------------------------------------------------------------ //------------------------------------------------------------ // Setup Secondary (Context) Axes x2Axis .scale(x2) .ticks( availableWidth / 100 ) .tickSize(-availableHeight2, 0); g.select('.nv-context .nv-x.nv-axis') .attr('transform', 'translate(0,' + y2.range()[0] + ')'); d3.transition(g.select('.nv-context .nv-x.nv-axis')) .call(x2Axis); y2Axis .scale(y2) .ticks( availableHeight2 / 36 ) .tickSize( -availableWidth, 0); d3.transition(g.select('.nv-context .nv-y.nv-axis')) .call(y2Axis); g.select('.nv-context .nv-x.nv-axis') .attr('transform', 'translate(0,' + y2.range()[0] + ')'); //------------------------------------------------------------ //============================================================ // Event Handling/Dispatching (in chart's scope) //------------------------------------------------------------ legend.dispatch.on('legendClick', function(d,i) { d.disabled = !d.disabled; if (!data.filter(function(d) { return !d.disabled }).length) { data.map(function(d) { d.disabled = false; wrap.selectAll('.nv-series').classed('disabled', false); return d; }); } container.transition().call(chart); }); dispatch.on('tooltipShow', function(e) { if (tooltips) showTooltip(e, that.parentNode); }); //============================================================ //============================================================ // Functions //------------------------------------------------------------ // Taken from crossfilter (http://square.github.com/crossfilter/) function resizePath(d) { var e = +(d == 'e'), x = e ? 1 : -1, y = availableHeight2 / 3; return 'M' + (.5 * x) + ',' + y + 'A6,6 0 0 ' + e + ' ' + (6.5 * x) + ',' + (y + 6) + 'V' + (2 * y - 6) + 'A6,6 0 0 ' + e + ' ' + (.5 * x) + ',' + (2 * y) + 'Z' + 'M' + (2.5 * x) + ',' + (y + 8) + 'V' + (2 * y - 8) + 'M' + (4.5 * x) + ',' + (y + 8) + 'V' + (2 * y - 8); } function updateBrushBG() { if (!brush.empty()) brush.extent(brushExtent); brushBG .data([brush.empty() ? x2.domain() : brushExtent]) .each(function(d,i) { var leftWidth = x2(d[0]) - x.range()[0], rightWidth = x.range()[1] - x2(d[1]); d3.select(this).select('.left') .attr('width', leftWidth < 0 ? 0 : leftWidth); d3.select(this).select('.right') .attr('x', x2(d[1])) .attr('width', rightWidth < 0 ? 0 : rightWidth); }); } function onBrush() { brushExtent = brush.empty() ? null : brush.extent(); extent = brush.empty() ? x2.domain() : brush.extent(); dispatch.brush({extent: extent, brush: brush}); updateBrushBG(); // Update Main (Focus) var focusLinesWrap = g.select('.nv-focus .nv-linesWrap') .datum( data .filter(function(d) { return !d.disabled }) .map(function(d,i) { return { key: d.key, values: d.values.filter(function(d,i) { return lines.x()(d,i) >= extent[0] && lines.x()(d,i) <= extent[1]; }) } }) ); d3.transition(focusLinesWrap).call(lines); // Update Main (Focus) Axes d3.transition(g.select('.nv-focus .nv-x.nv-axis')) .call(xAxis); d3.transition(g.select('.nv-focus .nv-y.nv-axis')) .call(yAxis); } //============================================================ }); return chart; } //============================================================ // Event Handling/Dispatching (out of chart's scope) //------------------------------------------------------------ lines.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); lines.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); dispatch.on('tooltipHide', function() { if (tooltips) nv.tooltip.cleanup(); }); //============================================================ //============================================================ // Expose Public Variables //------------------------------------------------------------ // expose chart's sub-components chart.dispatch = dispatch; chart.legend = legend; chart.lines = lines; chart.lines2 = lines2; chart.xAxis = xAxis; chart.yAxis = yAxis; chart.x2Axis = x2Axis; chart.y2Axis = y2Axis; d3.rebind(chart, lines, 'defined', 'isArea', 'size', 'xDomain', 'yDomain', 'forceX', 'forceY', 'interactive', 'clipEdge', 'clipVoronoi', 'id'); chart.x = function(_) { if (!arguments.length) return lines.x; lines.x(_); lines2.x(_); return chart; }; chart.y = function(_) { if (!arguments.length) return lines.y; lines.y(_); lines2.y(_); return chart; }; chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.margin2 = function(_) { if (!arguments.length) return margin2; margin2 = _; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.height2 = function(_) { if (!arguments.length) return height2; height2 = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color =nv.utils.getColor(_); legend.color(color); return chart; }; chart.showLegend = function(_) { if (!arguments.length) return showLegend; showLegend = _; return chart; }; chart.tooltips = function(_) { if (!arguments.length) return tooltips; tooltips = _; return chart; }; chart.tooltipContent = function(_) { if (!arguments.length) return tooltip; tooltip = _; return chart; }; chart.interpolate = function(_) { if (!arguments.length) return lines.interpolate(); lines.interpolate(_); lines2.interpolate(_); return chart; }; chart.noData = function(_) { if (!arguments.length) return noData; noData = _; return chart; }; // Chart has multiple similar Axes, to prevent code duplication, probably need to link all axis functions manually like below chart.xTickFormat = function(_) { if (!arguments.length) return xAxis.tickFormat(); xAxis.tickFormat(_); x2Axis.tickFormat(_); return chart; }; chart.yTickFormat = function(_) { if (!arguments.length) return yAxis.tickFormat(); yAxis.tickFormat(_); y2Axis.tickFormat(_); return chart; }; //============================================================ return chart; } nv.models.linePlusBarWithFocusChart = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var lines = nv.models.line() , lines2 = nv.models.line() , bars = nv.models.historicalBar() , bars2 = nv.models.historicalBar() , xAxis = nv.models.axis() , x2Axis = nv.models.axis() , y1Axis = nv.models.axis() , y2Axis = nv.models.axis() , y3Axis = nv.models.axis() , y4Axis = nv.models.axis() , legend = nv.models.legend() , brush = d3.svg.brush() ; var margin = {top: 30, right: 30, bottom: 30, left: 60} , margin2 = {top: 0, right: 30, bottom: 20, left: 60} , width = null , height = null , height2 = 100 , getX = function(d) { return d.x } , getY = function(d) { return d.y } , color = nv.utils.defaultColor() , showLegend = true , extent , brushExtent = null , tooltips = true , tooltip = function(key, x, y, e, graph) { return '<h3>' + key + '</h3>' + '<p>' + y + ' at ' + x + '</p>'; } , x , x2 , y1 , y2 , y3 , y4 , noData = "No Data Available." , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'brush') ; lines .clipEdge(true) ; lines2 .interactive(false) ; xAxis .orient('bottom') .tickPadding(5) ; y1Axis .orient('left') ; y2Axis .orient('right') ; x2Axis .orient('bottom') .tickPadding(5) ; y3Axis .orient('left') ; y4Axis .orient('right') ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var showTooltip = function(e, offsetElement) { if (extent) { e.pointIndex += Math.ceil(extent[0]); } var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), top = e.pos[1] + ( offsetElement.offsetTop || 0), x = xAxis.tickFormat()(lines.x()(e.point, e.pointIndex)), y = (e.series.bar ? y1Axis : y2Axis).tickFormat()(lines.y()(e.point, e.pointIndex)), content = tooltip(e.series.key, x, y, e, chart); nv.tooltip.show([left, top], content, e.value < 0 ? 'n' : 's', null, offsetElement); }; //------------------------------------------------------------ function chart(selection) { selection.each(function(data) { var container = d3.select(this), that = this; var availableWidth = (width || parseInt(container.style('width')) || 960) - margin.left - margin.right, availableHeight1 = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom - height2, availableHeight2 = height2 - margin2.top - margin2.bottom; chart.update = function() { container.transition().call(chart); }; chart.container = this; //------------------------------------------------------------ // Display No Data message if there's nothing to show. if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) { var noDataText = container.selectAll('.nv-noData').data([noData]); noDataText.enter().append('text') .attr('class', 'nvd3 nv-noData') .attr('dy', '-.7em') .style('text-anchor', 'middle'); noDataText .attr('x', margin.left + availableWidth / 2) .attr('y', margin.top + availableHeight1 / 2) .text(function(d) { return d }); return chart; } else { container.selectAll('.nv-noData').remove(); } //------------------------------------------------------------ //------------------------------------------------------------ // Setup Scales var dataBars = data.filter(function(d) { return !d.disabled && d.bar }); var dataLines = data.filter(function(d) { return !d.bar }); // removed the !d.disabled clause here to fix Issue #240 x = bars.xScale(); x2 = x2Axis.scale(); y1 = bars.yScale(); y2 = lines.yScale(); y3 = bars2.yScale(); y4 = lines2.yScale(); var series1 = data .filter(function(d) { return !d.disabled && d.bar }) .map(function(d) { return d.values.map(function(d,i) { return { x: getX(d,i), y: getY(d,i) } }) }); var series2 = data .filter(function(d) { return !d.disabled && !d.bar }) .map(function(d) { return d.values.map(function(d,i) { return { x: getX(d,i), y: getY(d,i) } }) }); x .range([0, availableWidth]); x2 .domain(d3.extent(d3.merge(series1.concat(series2)), function(d) { return d.x } )) .range([0, availableWidth]); //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-linePlusBar').data([data]); var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-linePlusBar').append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-legendWrap'); var focusEnter = gEnter.append('g').attr('class', 'nv-focus'); focusEnter.append('g').attr('class', 'nv-x nv-axis'); focusEnter.append('g').attr('class', 'nv-y1 nv-axis'); focusEnter.append('g').attr('class', 'nv-y2 nv-axis'); focusEnter.append('g').attr('class', 'nv-barsWrap'); focusEnter.append('g').attr('class', 'nv-linesWrap'); var contextEnter = gEnter.append('g').attr('class', 'nv-context'); contextEnter.append('g').attr('class', 'nv-x nv-axis'); contextEnter.append('g').attr('class', 'nv-y1 nv-axis'); contextEnter.append('g').attr('class', 'nv-y2 nv-axis'); contextEnter.append('g').attr('class', 'nv-barsWrap'); contextEnter.append('g').attr('class', 'nv-linesWrap'); contextEnter.append('g').attr('class', 'nv-brushBackground'); contextEnter.append('g').attr('class', 'nv-x nv-brush'); //------------------------------------------------------------ //------------------------------------------------------------ // Legend if (showLegend) { legend.width( availableWidth / 2 ); g.select('.nv-legendWrap') .datum(data.map(function(series) { series.originalKey = series.originalKey === undefined ? series.key : series.originalKey; series.key = series.originalKey + (series.bar ? ' (left axis)' : ' (right axis)'); return series; })) .call(legend); if ( margin.top != legend.height()) { margin.top = legend.height(); availableHeight1 = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom - height2; } g.select('.nv-legendWrap') .attr('transform', 'translate(' + ( availableWidth / 2 ) + ',' + (-margin.top) +')'); } //------------------------------------------------------------ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ // Context Components bars2 .width(availableWidth) .height(availableHeight2) .color(data.map(function(d,i) { return d.color || color(d, i); }).filter(function(d,i) { return !data[i].disabled && data[i].bar })); lines2 .width(availableWidth) .height(availableHeight2) .color(data.map(function(d,i) { return d.color || color(d, i); }).filter(function(d,i) { return !data[i].disabled && !data[i].bar })); var bars2Wrap = g.select('.nv-context .nv-barsWrap') .datum(dataBars.length ? dataBars : [{values:[]}]); var lines2Wrap = g.select('.nv-context .nv-linesWrap') .datum(!dataLines[0].disabled ? dataLines : [{values:[]}]); g.select('.nv-context') .attr('transform', 'translate(0,' + ( availableHeight1 + margin.bottom + margin2.top) + ')') d3.transition(bars2Wrap).call(bars2); d3.transition(lines2Wrap).call(lines2); //------------------------------------------------------------ //------------------------------------------------------------ // Setup Brush brush .x(x2) .on('brush', onBrush); if (brushExtent) brush.extent(brushExtent); var brushBG = g.select('.nv-brushBackground').selectAll('g') .data([brushExtent || brush.extent()]) var brushBGenter = brushBG.enter() .append('g'); brushBGenter.append('rect') .attr('class', 'left') .attr('x', 0) .attr('y', 0) .attr('height', availableHeight2); brushBGenter.append('rect') .attr('class', 'right') .attr('x', 0) .attr('y', 0) .attr('height', availableHeight2); var gBrush = g.select('.nv-x.nv-brush') .call(brush); gBrush.selectAll('rect') //.attr('y', -5) .attr('height', availableHeight2); gBrush.selectAll('.resize').append('path').attr('d', resizePath); //------------------------------------------------------------ //------------------------------------------------------------ // Setup Secondary (Context) Axes x2Axis .ticks( availableWidth / 100 ) .tickSize(-availableHeight2, 0); g.select('.nv-context .nv-x.nv-axis') .attr('transform', 'translate(0,' + y3.range()[0] + ')'); d3.transition(g.select('.nv-context .nv-x.nv-axis')) .call(x2Axis); y3Axis .scale(y3) .ticks( availableHeight2 / 36 ) .tickSize( -availableWidth, 0); g.select('.nv-context .nv-y1.nv-axis') .style('opacity', dataBars.length ? 1 : 0) .attr('transform', 'translate(0,' + x2.range()[0] + ')'); d3.transition(g.select('.nv-context .nv-y1.nv-axis')) .call(y3Axis); y4Axis .scale(y4) .ticks( availableHeight2 / 36 ) .tickSize(dataBars.length ? 0 : -availableWidth, 0); // Show the y2 rules only if y1 has none g.select('.nv-context .nv-y2.nv-axis') .style('opacity', dataLines.length ? 1 : 0) .attr('transform', 'translate(' + x2.range()[1] + ',0)'); d3.transition(g.select('.nv-context .nv-y2.nv-axis')) .call(y4Axis); //------------------------------------------------------------ //============================================================ // Event Handling/Dispatching (in chart's scope) //------------------------------------------------------------ legend.dispatch.on('legendClick', function(d,i) { d.disabled = !d.disabled; if (!data.filter(function(d) { return !d.disabled }).length) { data.map(function(d) { d.disabled = false; wrap.selectAll('.nv-series').classed('disabled', false); return d; }); } chart.update(); }); dispatch.on('tooltipShow', function(e) { if (tooltips) showTooltip(e, that.parentNode); }); //============================================================ //============================================================ // Functions //------------------------------------------------------------ // Taken from crossfilter (http://square.github.com/crossfilter/) function resizePath(d) { var e = +(d == 'e'), x = e ? 1 : -1, y = availableHeight2 / 3; return 'M' + (.5 * x) + ',' + y + 'A6,6 0 0 ' + e + ' ' + (6.5 * x) + ',' + (y + 6) + 'V' + (2 * y - 6) + 'A6,6 0 0 ' + e + ' ' + (.5 * x) + ',' + (2 * y) + 'Z' + 'M' + (2.5 * x) + ',' + (y + 8) + 'V' + (2 * y - 8) + 'M' + (4.5 * x) + ',' + (y + 8) + 'V' + (2 * y - 8); } function updateBrushBG() { if (!brush.empty()) brush.extent(brushExtent); brushBG .data([brush.empty() ? x2.domain() : brushExtent]) .each(function(d,i) { var leftWidth = x2(d[0]) - x2.range()[0], rightWidth = x2.range()[1] - x2(d[1]); d3.select(this).select('.left') .attr('width', leftWidth < 0 ? 0 : leftWidth); d3.select(this).select('.right') .attr('x', x2(d[1])) .attr('width', rightWidth < 0 ? 0 : rightWidth); }); } function onBrush() { brushExtent = brush.empty() ? null : brush.extent(); extent = brush.empty() ? x2.domain() : brush.extent(); dispatch.brush({extent: extent, brush: brush}); updateBrushBG(); //------------------------------------------------------------ // Prepare Main (Focus) Bars and Lines bars .width(availableWidth) .height(availableHeight1) .color(data.map(function(d,i) { return d.color || color(d, i); }).filter(function(d,i) { return !data[i].disabled && data[i].bar })); lines .width(availableWidth) .height(availableHeight1) .color(data.map(function(d,i) { return d.color || color(d, i); }).filter(function(d,i) { return !data[i].disabled && !data[i].bar })); var focusBarsWrap = g.select('.nv-focus .nv-barsWrap') .datum(!dataBars.length ? [{values:[]}] : dataBars .map(function(d,i) { return { key: d.key, values: d.values.filter(function(d,i) { return bars.x()(d,i) >= extent[0] && bars.x()(d,i) <= extent[1]; }) } }) ); var focusLinesWrap = g.select('.nv-focus .nv-linesWrap') .datum(dataLines[0].disabled ? [{values:[]}] : dataLines .map(function(d,i) { return { key: d.key, values: d.values.filter(function(d,i) { return lines.x()(d,i) >= extent[0] && lines.x()(d,i) <= extent[1]; }) } }) ); //------------------------------------------------------------ //------------------------------------------------------------ // Update Main (Focus) X Axis if (dataBars.length) { x = bars.xScale(); } else { x = lines.xScale(); } xAxis .scale(x) .ticks( availableWidth / 100 ) .tickSize(-availableHeight1, 0); xAxis.domain([Math.ceil(extent[0]), Math.floor(extent[1])]); d3.transition(g.select('.nv-x.nv-axis')) .call(xAxis); //------------------------------------------------------------ //------------------------------------------------------------ // Update Main (Focus) Bars and Lines d3.transition(focusBarsWrap).call(bars); d3.transition(focusLinesWrap).call(lines); //------------------------------------------------------------ //------------------------------------------------------------ // Setup and Update Main (Focus) Y Axes g.select('.nv-focus .nv-x.nv-axis') .attr('transform', 'translate(0,' + y1.range()[0] + ')'); y1Axis .scale(y1) .ticks( availableHeight1 / 36 ) .tickSize(-availableWidth, 0); g.select('.nv-focus .nv-y1.nv-axis') .style('opacity', dataBars.length ? 1 : 0); y2Axis .scale(y2) .ticks( availableHeight1 / 36 ) .tickSize(dataBars.length ? 0 : -availableWidth, 0); // Show the y2 rules only if y1 has none g.select('.nv-focus .nv-y2.nv-axis') .style('opacity', dataLines.length ? 1 : 0) .attr('transform', 'translate(' + x.range()[1] + ',0)'); d3.transition(g.select('.nv-focus .nv-y1.nv-axis')) .call(y1Axis); d3.transition(g.select('.nv-focus .nv-y2.nv-axis')) .call(y2Axis); } //============================================================ onBrush(); }); return chart; } //============================================================ // Event Handling/Dispatching (out of chart's scope) //------------------------------------------------------------ lines.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); lines.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); bars.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); bars.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); dispatch.on('tooltipHide', function() { if (tooltips) nv.tooltip.cleanup(); }); //============================================================ //============================================================ // Expose Public Variables //------------------------------------------------------------ // expose chart's sub-components chart.dispatch = dispatch; chart.legend = legend; chart.lines = lines; chart.lines2 = lines2; chart.bars = bars; chart.bars2 = bars2; chart.xAxis = xAxis; chart.x2Axis = x2Axis; chart.y1Axis = y1Axis; chart.y2Axis = y2Axis; chart.y3Axis = y3Axis; chart.y4Axis = y4Axis; d3.rebind(chart, lines, 'defined', 'size', 'clipVoronoi', 'interpolate'); //TODO: consider rebinding x, y and some other stuff, and simply do soemthign lile bars.x(lines.x()), etc. //d3.rebind(chart, lines, 'x', 'y', 'size', 'xDomain', 'yDomain', 'forceX', 'forceY', 'interactive', 'clipEdge', 'clipVoronoi', 'id'); chart.x = function(_) { if (!arguments.length) return getX; getX = _; lines.x(_); bars.x(_); return chart; }; chart.y = function(_) { if (!arguments.length) return getY; getY = _; lines.y(_); bars.y(_); return chart; }; chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); legend.color(color); return chart; }; chart.showLegend = function(_) { if (!arguments.length) return showLegend; showLegend = _; return chart; }; chart.tooltips = function(_) { if (!arguments.length) return tooltips; tooltips = _; return chart; }; chart.tooltipContent = function(_) { if (!arguments.length) return tooltip; tooltip = _; return chart; }; chart.noData = function(_) { if (!arguments.length) return noData; noData = _; return chart; }; chart.brushExtent = function(_) { if (!arguments.length) return brushExtent; brushExtent = _; return chart; }; //============================================================ return chart; } nv.models.multiBar = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var margin = {top: 0, right: 0, bottom: 0, left: 0} , width = 960 , height = 500 , x = d3.scale.ordinal() , y = d3.scale.linear() , id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one , getX = function(d) { return d.x } , getY = function(d) { return d.y } , forceY = [0] // 0 is forced by default.. this makes sense for the majority of bar graphs... user can always do chart.forceY([]) to remove , clipEdge = true , stacked = false , color = nv.utils.defaultColor() , hideable = false , barColor = null // adding the ability to set the color for each rather than the whole group , disabled // used in conjunction with barColor to communicate from multiBarHorizontalChart what series are disabled , delay = 1200 , drawTime = 500 , xDomain , yDomain , dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout') ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var x0, y0 //used to store previous scales ; //============================================================ function chart(selection) { selection.each(function(data) { var availableWidth = width - margin.left - margin.right, availableHeight = height - margin.top - margin.bottom, container = d3.select(this); if(hideable && data.length) hideable = [{ values: data[0].values.map(function(d) { return { x: d.x, y: 0, series: d.series, size: 0.01 };} )}]; if (stacked) data = d3.layout.stack() .offset('zero') .values(function(d){ return d.values }) .y(getY) (!data.length && hideable ? hideable : data); //add series index to each data point for reference data = data.map(function(series, i) { series.values = series.values.map(function(point) { point.series = i; return point; }); return series; }); //------------------------------------------------------------ // HACK for negative value stacking if (stacked) data[0].values.map(function(d,i) { var posBase = 0, negBase = 0; data.map(function(d) { var f = d.values[i] f.size = Math.abs(f.y); if (f.y<0) { f.y1 = negBase; negBase = negBase - f.size; } else { f.y1 = f.size + posBase; posBase = posBase + f.size; } }); }); //------------------------------------------------------------ // Setup Scales // remap and flatten the data for use in calculating the scales' domains var seriesData = (xDomain && yDomain) ? [] : // if we know xDomain and yDomain, no need to calculate data.map(function(d) { return d.values.map(function(d,i) { return { x: getX(d,i), y: getY(d,i), y0: d.y0, y1: d.y1 } }) }); x .domain(d3.merge(seriesData).map(function(d) { return d.x })) .rangeBands([0, availableWidth], .1); //y .domain(yDomain || d3.extent(d3.merge(seriesData).map(function(d) { return d.y + (stacked ? d.y1 : 0) }).concat(forceY))) y .domain(yDomain || d3.extent(d3.merge(seriesData).map(function(d) { return stacked ? (d.y > 0 ? d.y1 : d.y1 + d.y ) : d.y }).concat(forceY))) .range([availableHeight, 0]); // If scale's domain don't have a range, slightly adjust to make one... so a chart can show a single data point if (x.domain()[0] === x.domain()[1] || y.domain()[0] === y.domain()[1]) singlePoint = true; if (x.domain()[0] === x.domain()[1]) x.domain()[0] ? x.domain([x.domain()[0] - x.domain()[0] * 0.01, x.domain()[1] + x.domain()[1] * 0.01]) : x.domain([-1,1]); if (y.domain()[0] === y.domain()[1]) y.domain()[0] ? y.domain([y.domain()[0] + y.domain()[0] * 0.01, y.domain()[1] - y.domain()[1] * 0.01]) : y.domain([-1,1]); x0 = x0 || x; y0 = y0 || y; //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-multibar').data([data]); var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-multibar'); var defsEnter = wrapEnter.append('defs'); var gEnter = wrapEnter.append('g'); var g = wrap.select('g') gEnter.append('g').attr('class', 'nv-groups'); wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ defsEnter.append('clipPath') .attr('id', 'nv-edge-clip-' + id) .append('rect'); wrap.select('#nv-edge-clip-' + id + ' rect') .attr('width', availableWidth) .attr('height', availableHeight); g .attr('clip-path', clipEdge ? 'url(#nv-edge-clip-' + id + ')' : ''); var groups = wrap.select('.nv-groups').selectAll('.nv-group') .data(function(d) { return d }, function(d) { return d.key }); groups.enter().append('g') .style('stroke-opacity', 1e-6) .style('fill-opacity', 1e-6); groups.exit() .selectAll('rect.nv-bar') .transition() .delay(function(d,i) { return i * delay/ data[0].values.length }) .attr('y', function(d) { return stacked ? y0(d.y0) : y0(0) }) .attr('height', 0) .remove(); groups .attr('class', function(d,i) { return 'nv-group nv-series-' + i }) .classed('hover', function(d) { return d.hover }) .style('fill', function(d,i){ return color(d, i) }) .style('stroke', function(d,i){ return color(d, i) }); d3.transition(groups) .style('stroke-opacity', 1) .style('fill-opacity', .75); var bars = groups.selectAll('rect.nv-bar') .data(function(d) { return (hideable && !data.length) ? hideable.values : d.values }); bars.exit().remove(); var barsEnter = bars.enter().append('rect') .attr('class', function(d,i) { return getY(d,i) < 0 ? 'nv-bar negative' : 'nv-bar positive'}) .attr('x', function(d,i,j) { return stacked ? 0 : (j * x.rangeBand() / data.length ) }) .attr('y', function(d) { return y0(stacked ? d.y0 : 0) }) .attr('height', 0) .attr('width', x.rangeBand() / (stacked ? 1 : data.length) ); bars .style('fill', function(d,i,j){ return color(d, j, i); }) .style('stroke', function(d,i,j){ return color(d, j, i); }) .on('mouseover', function(d,i) { //TODO: figure out why j works above, but not here d3.select(this).classed('hover', true); dispatch.elementMouseover({ value: getY(d,i), point: d, series: data[d.series], pos: [x(getX(d,i)) + (x.rangeBand() * (stacked ? data.length / 2 : d.series + .5) / data.length), y(getY(d,i) + (stacked ? d.y0 : 0))], // TODO: Figure out why the value appears to be shifted pointIndex: i, seriesIndex: d.series, e: d3.event }); }) .on('mouseout', function(d,i) { d3.select(this).classed('hover', false); dispatch.elementMouseout({ value: getY(d,i), point: d, series: data[d.series], pointIndex: i, seriesIndex: d.series, e: d3.event }); }) .on('click', function(d,i) { dispatch.elementClick({ value: getY(d,i), point: d, series: data[d.series], pos: [x(getX(d,i)) + (x.rangeBand() * (stacked ? data.length / 2 : d.series + .5) / data.length), y(getY(d,i) + (stacked ? d.y0 : 0))], // TODO: Figure out why the value appears to be shifted pointIndex: i, seriesIndex: d.series, e: d3.event }); d3.event.stopPropagation(); }) .on('dblclick', function(d,i) { dispatch.elementDblClick({ value: getY(d,i), point: d, series: data[d.series], pos: [x(getX(d,i)) + (x.rangeBand() * (stacked ? data.length / 2 : d.series + .5) / data.length), y(getY(d,i) + (stacked ? d.y0 : 0))], // TODO: Figure out why the value appears to be shifted pointIndex: i, seriesIndex: d.series, e: d3.event }); d3.event.stopPropagation(); }); bars .attr('class', function(d,i) { return getY(d,i) < 0 ? 'nv-bar negative' : 'nv-bar positive'}) .attr('transform', function(d,i) { return 'translate(' + x(getX(d,i)) + ',0)'; }) if (barColor) { if (!disabled) disabled = data.map(function() { return true }); bars //.style('fill', barColor) //.style('stroke', barColor) //.style('fill', function(d,i,j) { return d3.rgb(barColor(d,i)).darker(j).toString(); }) //.style('stroke', function(d,i,j) { return d3.rgb(barColor(d,i)).darker(j).toString(); }) .style('fill', function(d,i,j) { return d3.rgb(barColor(d,i)).darker( disabled.map(function(d,i) { return i }).filter(function(d,i){ return !disabled[i] })[j] ).toString(); }) .style('stroke', function(d,i,j) { return d3.rgb(barColor(d,i)).darker( disabled.map(function(d,i) { return i }).filter(function(d,i){ return !disabled[i] })[j] ).toString(); }); } if (stacked) bars.transition() .delay(function(d,i) { return i * delay / data[0].values.length }) .attr('y', function(d,i) { return y((stacked ? d.y1 : 0)); }) .attr('height', function(d,i) { return Math.max(Math.abs(y(d.y + (stacked ? d.y0 : 0)) - y((stacked ? d.y0 : 0))),1); }) .each('end', function() { d3.select(this).transition().duration(drawTime) .attr('x', function(d,i) { return stacked ? 0 : (d.series * x.rangeBand() / data.length ) }) .attr('width', x.rangeBand() / (stacked ? 1 : data.length) ); }) else d3.transition(bars).duration(drawTime) .delay(function(d,i) { return i * delay/ data[0].values.length }) .attr('x', function(d,i) { return d.series * x.rangeBand() / data.length }) .attr('width', x.rangeBand() / data.length) .each('end', function() { d3.select(this).transition().duration(drawTime) .attr('y', function(d,i) { return getY(d,i) < 0 ? y(0) : y(0) - y(getY(d,i)) < 1 ? y(0) - 1 : y(getY(d,i)) || 0; }) .attr('height', function(d,i) { return Math.max(Math.abs(y(getY(d,i)) - y(0)),1) || 0; }); }) //store old scales for use in transitions on update x0 = x.copy(); y0 = y.copy(); }); return chart; } //============================================================ // Expose Public Variables //------------------------------------------------------------ chart.dispatch = dispatch; chart.x = function(_) { if (!arguments.length) return getX; getX = _; return chart; }; chart.y = function(_) { if (!arguments.length) return getY; getY = _; return chart; }; chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.xScale = function(_) { if (!arguments.length) return x; x = _; return chart; }; chart.yScale = function(_) { if (!arguments.length) return y; y = _; return chart; }; chart.xDomain = function(_) { if (!arguments.length) return xDomain; xDomain = _; return chart; }; chart.yDomain = function(_) { if (!arguments.length) return yDomain; yDomain = _; return chart; }; chart.forceY = function(_) { if (!arguments.length) return forceY; forceY = _; return chart; }; chart.stacked = function(_) { if (!arguments.length) return stacked; stacked = _; return chart; }; chart.clipEdge = function(_) { if (!arguments.length) return clipEdge; clipEdge = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); return chart; }; chart.barColor = function(_) { if (!arguments.length) return barColor; barColor = nv.utils.getColor(_); return chart; }; chart.disabled = function(_) { if (!arguments.length) return disabled; disabled = _; return chart; }; chart.id = function(_) { if (!arguments.length) return id; id = _; return chart; }; chart.hideable = function(_) { if (!arguments.length) return hideable; hideable = _; return chart; }; chart.delay = function(_) { if (!arguments.length) return delay; delay = _; return chart; }; chart.drawTime = function(_) { if (!arguments.length) return drawTime; drawTime = _; return chart; }; //============================================================ return chart; } nv.models.multiBarChart = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var multibar = nv.models.multiBar() , xAxis = nv.models.axis() , yAxis = nv.models.axis() , legend = nv.models.legend() , controls = nv.models.legend() ; var margin = {top: 30, right: 20, bottom: 50, left: 60} , width = null , height = null , color = nv.utils.defaultColor() , showControls = true , showLegend = true , reduceXTicks = true // if false a tick will show for every data point , staggerLabels = false , rotateLabels = 0 , tooltips = true , tooltip = function(key, x, y, e, graph) { return '<h3>' + key + '</h3>' + '<p>' + y + ' on ' + x + '</p>' } , x //can be accessed via chart.xScale() , y //can be accessed via chart.yScale() , state = { stacked: false } , defaultState = null , noData = "No Data Available." , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState') , controlWidth = function() { return showControls ? 180 : 0 } ; multibar .stacked(false) ; xAxis .orient('bottom') .tickPadding(7) .highlightZero(true) .showMaxMin(false) .tickFormat(function(d) { return d }) ; yAxis .orient('left') .tickFormat(d3.format(',.1f')) ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var showTooltip = function(e, offsetElement) { var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), top = e.pos[1] + ( offsetElement.offsetTop || 0), x = xAxis.tickFormat()(multibar.x()(e.point, e.pointIndex)), y = yAxis.tickFormat()(multibar.y()(e.point, e.pointIndex)), content = tooltip(e.series.key, x, y, e, chart); nv.tooltip.show([left, top], content, e.value < 0 ? 'n' : 's', null, offsetElement); }; //============================================================ function chart(selection) { selection.each(function(data) { var container = d3.select(this), that = this; var availableWidth = (width || parseInt(container.style('width')) || 960) - margin.left - margin.right, availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; chart.update = function() { container.transition().call(chart) }; chart.container = this; //set state.disabled state.disabled = data.map(function(d) { return !!d.disabled }); if (!defaultState) { var key; defaultState = {}; for (key in state) { if (state[key] instanceof Array) defaultState[key] = state[key].slice(0); else defaultState[key] = state[key]; } } //------------------------------------------------------------ // Display noData message if there's nothing to show. if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) { var noDataText = container.selectAll('.nv-noData').data([noData]); noDataText.enter().append('text') .attr('class', 'nvd3 nv-noData') .attr('dy', '-.7em') .style('text-anchor', 'middle'); noDataText .attr('x', margin.left + availableWidth / 2) .attr('y', margin.top + availableHeight / 2) .text(function(d) { return d }); return chart; } else { container.selectAll('.nv-noData').remove(); } //------------------------------------------------------------ //------------------------------------------------------------ // Setup Scales x = multibar.xScale(); y = multibar.yScale(); //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-multiBarWithLegend').data([data]); var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-multiBarWithLegend').append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-x nv-axis'); gEnter.append('g').attr('class', 'nv-y nv-axis'); gEnter.append('g').attr('class', 'nv-barsWrap'); gEnter.append('g').attr('class', 'nv-legendWrap'); gEnter.append('g').attr('class', 'nv-controlsWrap'); //------------------------------------------------------------ //------------------------------------------------------------ // Legend if (showLegend) { legend.width(availableWidth - controlWidth()); if (multibar.barColor()) data.forEach(function(series,i) { series.color = d3.rgb('#ccc').darker(i * 1.5).toString(); }) g.select('.nv-legendWrap') .datum(data) .call(legend); if ( margin.top != legend.height()) { margin.top = legend.height(); availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; } g.select('.nv-legendWrap') .attr('transform', 'translate(' + controlWidth() + ',' + (-margin.top) +')'); } //------------------------------------------------------------ //------------------------------------------------------------ // Controls if (showControls) { var controlsData = [ { key: 'Grouped', disabled: multibar.stacked() }, { key: 'Stacked', disabled: !multibar.stacked() } ]; controls.width(controlWidth()).color(['#444', '#444', '#444']); g.select('.nv-controlsWrap') .datum(controlsData) .attr('transform', 'translate(0,' + (-margin.top) +')') .call(controls); } //------------------------------------------------------------ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ // Main Chart Component(s) multibar .disabled(data.map(function(series) { return series.disabled })) .width(availableWidth) .height(availableHeight) .color(data.map(function(d,i) { return d.color || color(d, i); }).filter(function(d,i) { return !data[i].disabled })) var barsWrap = g.select('.nv-barsWrap') .datum(data.filter(function(d) { return !d.disabled })) d3.transition(barsWrap).call(multibar); //------------------------------------------------------------ //------------------------------------------------------------ // Setup Axes xAxis .scale(x) .ticks( availableWidth / 100 ) .tickSize(-availableHeight, 0); g.select('.nv-x.nv-axis') .attr('transform', 'translate(0,' + y.range()[0] + ')'); d3.transition(g.select('.nv-x.nv-axis')) .call(xAxis); var xTicks = g.select('.nv-x.nv-axis > g').selectAll('g'); xTicks .selectAll('line, text') .style('opacity', 1) if (staggerLabels) { var getTranslate = function(x,y) { return "translate(" + x + "," + y + ")"; }; var staggerUp = 5, staggerDown = 17; //pixels to stagger by // Issue #140 xTicks .selectAll("text") .attr('transform', function(d,i,j) { return getTranslate(0, (j % 2 == 0 ? staggerUp : staggerDown)); }); var totalInBetweenTicks = d3.selectAll(".nv-x.nv-axis .nv-wrap g g text")[0].length; g.selectAll(".nv-x.nv-axis .nv-axisMaxMin text") .attr("transform", function(d,i) { return getTranslate(0, (i === 0 || totalInBetweenTicks % 2 !== 0) ? staggerDown : staggerUp); }); } if (reduceXTicks) xTicks .filter(function(d,i) { return i % Math.ceil(data[0].values.length / (availableWidth / 100)) !== 0; }) .selectAll('text, line') .style('opacity', 0); if(rotateLabels) xTicks .selectAll('text') .attr('transform', 'rotate(' + rotateLabels + ' 0,0)') .attr('text-anchor', rotateLabels > 0 ? 'start' : 'end'); g.select('.nv-x.nv-axis').selectAll('g.nv-axisMaxMin text') .style('opacity', 1); yAxis .scale(y) .ticks( availableHeight / 36 ) .tickSize( -availableWidth, 0); d3.transition(g.select('.nv-y.nv-axis')) .call(yAxis); //------------------------------------------------------------ //============================================================ // Event Handling/Dispatching (in chart's scope) //------------------------------------------------------------ legend.dispatch.on('legendClick', function(d,i) { d.disabled = !d.disabled; if (!data.filter(function(d) { return !d.disabled }).length) { data.map(function(d) { d.disabled = false; wrap.selectAll('.nv-series').classed('disabled', false); return d; }); } state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); chart.update(); }); legend.dispatch.on('legendDblclick', function(d) { //Double clicking should always enable current series, and disabled all others. data.forEach(function(d) { d.disabled = true; }); d.disabled = false; state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); chart.update(); }); controls.dispatch.on('legendClick', function(d,i) { if (!d.disabled) return; controlsData = controlsData.map(function(s) { s.disabled = true; return s; }); d.disabled = false; switch (d.key) { case 'Grouped': multibar.stacked(false); break; case 'Stacked': multibar.stacked(true); break; } state.stacked = multibar.stacked(); dispatch.stateChange(state); chart.update(); }); dispatch.on('tooltipShow', function(e) { if (tooltips) showTooltip(e, that.parentNode) }); // Update chart from a state object passed to event handler dispatch.on('changeState', function(e) { if (typeof e.disabled !== 'undefined') { data.forEach(function(series,i) { series.disabled = e.disabled[i]; }); state.disabled = e.disabled; } if (typeof e.stacked !== 'undefined') { multibar.stacked(e.stacked); state.stacked = e.stacked; } chart.update(); }); //============================================================ }); return chart; } //============================================================ // Event Handling/Dispatching (out of chart's scope) //------------------------------------------------------------ multibar.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); multibar.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); dispatch.on('tooltipHide', function() { if (tooltips) nv.tooltip.cleanup(); }); //============================================================ //============================================================ // Expose Public Variables //------------------------------------------------------------ // expose chart's sub-components chart.dispatch = dispatch; chart.multibar = multibar; chart.legend = legend; chart.xAxis = xAxis; chart.yAxis = yAxis; d3.rebind(chart, multibar, 'x', 'y', 'xDomain', 'yDomain', 'forceX', 'forceY', 'clipEdge', 'id', 'stacked', 'delay', 'barColor'); chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); legend.color(color); return chart; }; chart.showControls = function(_) { if (!arguments.length) return showControls; showControls = _; return chart; }; chart.showLegend = function(_) { if (!arguments.length) return showLegend; showLegend = _; return chart; }; chart.reduceXTicks= function(_) { if (!arguments.length) return reduceXTicks; reduceXTicks = _; return chart; }; chart.rotateLabels = function(_) { if (!arguments.length) return rotateLabels; rotateLabels = _; return chart; } chart.staggerLabels = function(_) { if (!arguments.length) return staggerLabels; staggerLabels = _; return chart; }; chart.tooltip = function(_) { if (!arguments.length) return tooltip; tooltip = _; return chart; }; chart.tooltips = function(_) { if (!arguments.length) return tooltips; tooltips = _; return chart; }; chart.tooltipContent = function(_) { if (!arguments.length) return tooltip; tooltip = _; return chart; }; chart.state = function(_) { if (!arguments.length) return state; state = _; return chart; }; chart.defaultState = function(_) { if (!arguments.length) return defaultState; defaultState = _; return chart; }; chart.noData = function(_) { if (!arguments.length) return noData; noData = _; return chart; }; //============================================================ return chart; } nv.models.multiBarHorizontal = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var margin = {top: 0, right: 0, bottom: 0, left: 0} , width = 960 , height = 500 , id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one , x = d3.scale.ordinal() , y = d3.scale.linear() , getX = function(d) { return d.x } , getY = function(d) { return d.y } , forceY = [0] // 0 is forced by default.. this makes sense for the majority of bar graphs... user can always do chart.forceY([]) to remove , color = nv.utils.defaultColor() , barColor = null // adding the ability to set the color for each rather than the whole group , disabled // used in conjunction with barColor to communicate from multiBarHorizontalChart what series are disabled , stacked = false , showValues = false , valuePadding = 60 , valueFormat = d3.format(',.2f') , delay = 1200 , xDomain , yDomain , dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout') ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var x0, y0 //used to store previous scales ; //============================================================ function chart(selection) { selection.each(function(data) { var availableWidth = width - margin.left - margin.right, availableHeight = height - margin.top - margin.bottom, container = d3.select(this); if (stacked) data = d3.layout.stack() .offset('zero') .values(function(d){ return d.values }) .y(getY) (data); //add series index to each data point for reference data = data.map(function(series, i) { series.values = series.values.map(function(point) { point.series = i; return point; }); return series; }); //------------------------------------------------------------ // HACK for negative value stacking if (stacked) data[0].values.map(function(d,i) { var posBase = 0, negBase = 0; data.map(function(d) { var f = d.values[i] f.size = Math.abs(f.y); if (f.y<0) { f.y1 = negBase - f.size; negBase = negBase - f.size; } else { f.y1 = posBase; posBase = posBase + f.size; } }); }); //------------------------------------------------------------ // Setup Scales // remap and flatten the data for use in calculating the scales' domains var seriesData = (xDomain && yDomain) ? [] : // if we know xDomain and yDomain, no need to calculate data.map(function(d) { return d.values.map(function(d,i) { return { x: getX(d,i), y: getY(d,i), y0: d.y0, y1: d.y1 } }) }); x .domain(xDomain || d3.merge(seriesData).map(function(d) { return d.x })) .rangeBands([0, availableHeight], .1); //y .domain(yDomain || d3.extent(d3.merge(seriesData).map(function(d) { return d.y + (stacked ? d.y0 : 0) }).concat(forceY))) y .domain(yDomain || d3.extent(d3.merge(seriesData).map(function(d) { return stacked ? (d.y > 0 ? d.y1 + d.y : d.y1 ) : d.y }).concat(forceY))) if (showValues && !stacked) y.range([(y.domain()[0] < 0 ? valuePadding : 0), availableWidth - (y.domain()[1] > 0 ? valuePadding : 0) ]); else y.range([0, availableWidth]); x0 = x0 || x; y0 = y0 || d3.scale.linear().domain(y.domain()).range([y(0),y(0)]); //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = d3.select(this).selectAll('g.nv-wrap.nv-multibarHorizontal').data([data]); var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-multibarHorizontal'); var defsEnter = wrapEnter.append('defs'); var gEnter = wrapEnter.append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-groups'); wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ var groups = wrap.select('.nv-groups').selectAll('.nv-group') .data(function(d) { return d }, function(d) { return d.key }); groups.enter().append('g') .style('stroke-opacity', 1e-6) .style('fill-opacity', 1e-6); d3.transition(groups.exit()) .style('stroke-opacity', 1e-6) .style('fill-opacity', 1e-6) .remove(); groups .attr('class', function(d,i) { return 'nv-group nv-series-' + i }) .classed('hover', function(d) { return d.hover }) .style('fill', function(d,i){ return color(d, i) }) .style('stroke', function(d,i){ return color(d, i) }); d3.transition(groups) .style('stroke-opacity', 1) .style('fill-opacity', .75); var bars = groups.selectAll('g.nv-bar') .data(function(d) { return d.values }); bars.exit().remove(); var barsEnter = bars.enter().append('g') .attr('transform', function(d,i,j) { return 'translate(' + y0(stacked ? d.y0 : 0) + ',' + (stacked ? 0 : (j * x.rangeBand() / data.length ) + x(getX(d,i))) + ')' }); barsEnter.append('rect') .attr('width', 0) .attr('height', x.rangeBand() / (stacked ? 1 : data.length) ) bars .on('mouseover', function(d,i) { //TODO: figure out why j works above, but not here d3.select(this).classed('hover', true); dispatch.elementMouseover({ value: getY(d,i), point: d, series: data[d.series], pos: [ y(getY(d,i) + (stacked ? d.y0 : 0)), x(getX(d,i)) + (x.rangeBand() * (stacked ? data.length / 2 : d.series + .5) / data.length) ], pointIndex: i, seriesIndex: d.series, e: d3.event }); }) .on('mouseout', function(d,i) { d3.select(this).classed('hover', false); dispatch.elementMouseout({ value: getY(d,i), point: d, series: data[d.series], pointIndex: i, seriesIndex: d.series, e: d3.event }); }) .on('click', function(d,i) { dispatch.elementClick({ value: getY(d,i), point: d, series: data[d.series], pos: [x(getX(d,i)) + (x.rangeBand() * (stacked ? data.length / 2 : d.series + .5) / data.length), y(getY(d,i) + (stacked ? d.y0 : 0))], // TODO: Figure out why the value appears to be shifted pointIndex: i, seriesIndex: d.series, e: d3.event }); d3.event.stopPropagation(); }) .on('dblclick', function(d,i) { dispatch.elementDblClick({ value: getY(d,i), point: d, series: data[d.series], pos: [x(getX(d,i)) + (x.rangeBand() * (stacked ? data.length / 2 : d.series + .5) / data.length), y(getY(d,i) + (stacked ? d.y0 : 0))], // TODO: Figure out why the value appears to be shifted pointIndex: i, seriesIndex: d.series, e: d3.event }); d3.event.stopPropagation(); }); barsEnter.append('text'); if (showValues && !stacked) { bars.select('text') .attr('text-anchor', function(d,i) { return getY(d,i) < 0 ? 'end' : 'start' }) .attr('y', x.rangeBand() / (data.length * 2)) .attr('dy', '.32em') .text(function(d,i) { return valueFormat(getY(d,i)) }) d3.transition(bars) //.delay(function(d,i) { return i * delay / data[0].values.length }) .select('text') .attr('x', function(d,i) { return getY(d,i) < 0 ? -4 : y(getY(d,i)) - y(0) + 4 }) } else { //bars.selectAll('text').remove(); bars.selectAll('text').text(''); } bars .attr('class', function(d,i) { return getY(d,i) < 0 ? 'nv-bar negative' : 'nv-bar positive'}) if (barColor) { if (!disabled) disabled = data.map(function() { return true }); bars //.style('fill', barColor) //.style('stroke', barColor) //.style('fill', function(d,i,j) { return d3.rgb(barColor(d,i)).darker(j).toString(); }) //.style('stroke', function(d,i,j) { return d3.rgb(barColor(d,i)).darker(j).toString(); }) .style('fill', function(d,i,j) { return d3.rgb(barColor(d,i)).darker( disabled.map(function(d,i) { return i }).filter(function(d,i){ return !disabled[i] })[j] ).toString(); }) .style('stroke', function(d,i,j) { return d3.rgb(barColor(d,i)).darker( disabled.map(function(d,i) { return i }).filter(function(d,i){ return !disabled[i] })[j] ).toString(); }); } if (stacked) d3.transition(bars) //.delay(function(d,i) { return i * delay / data[0].values.length }) .attr('transform', function(d,i) { //return 'translate(' + y(d.y0) + ',0)' //return 'translate(' + y(d.y0) + ',' + x(getX(d,i)) + ')' return 'translate(' + y(d.y1) + ',' + x(getX(d,i)) + ')' }) .select('rect') .attr('width', function(d,i) { return Math.abs(y(getY(d,i) + d.y0) - y(d.y0)) }) .attr('height', x.rangeBand() ); else d3.transition(bars) //.delay(function(d,i) { return i * delay / data[0].values.length }) .attr('transform', function(d,i) { //TODO: stacked must be all positive or all negative, not both? return 'translate(' + (getY(d,i) < 0 ? y(getY(d,i)) : y(0)) + ',' + (d.series * x.rangeBand() / data.length + x(getX(d,i)) ) + ')' }) .select('rect') .attr('height', x.rangeBand() / data.length ) .attr('width', function(d,i) { return Math.max(Math.abs(y(getY(d,i)) - y(0)),1) }); //store old scales for use in transitions on update x0 = x.copy(); y0 = y.copy(); }); return chart; } //============================================================ // Expose Public Variables //------------------------------------------------------------ chart.dispatch = dispatch; chart.x = function(_) { if (!arguments.length) return getX; getX = _; return chart; }; chart.y = function(_) { if (!arguments.length) return getY; getY = _; return chart; }; chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.xScale = function(_) { if (!arguments.length) return x; x = _; return chart; }; chart.yScale = function(_) { if (!arguments.length) return y; y = _; return chart; }; chart.xDomain = function(_) { if (!arguments.length) return xDomain; xDomain = _; return chart; }; chart.yDomain = function(_) { if (!arguments.length) return yDomain; yDomain = _; return chart; }; chart.forceY = function(_) { if (!arguments.length) return forceY; forceY = _; return chart; }; chart.stacked = function(_) { if (!arguments.length) return stacked; stacked = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); return chart; }; chart.barColor = function(_) { if (!arguments.length) return barColor; barColor = nv.utils.getColor(_); return chart; }; chart.disabled = function(_) { if (!arguments.length) return disabled; disabled = _; return chart; }; chart.id = function(_) { if (!arguments.length) return id; id = _; return chart; }; chart.delay = function(_) { if (!arguments.length) return delay; delay = _; return chart; }; chart.showValues = function(_) { if (!arguments.length) return showValues; showValues = _; return chart; }; chart.valueFormat= function(_) { if (!arguments.length) return valueFormat; valueFormat = _; return chart; }; chart.valuePadding = function(_) { if (!arguments.length) return valuePadding; valuePadding = _; return chart; }; //============================================================ return chart; } nv.models.multiBarHorizontalChart = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var multibar = nv.models.multiBarHorizontal() , xAxis = nv.models.axis() , yAxis = nv.models.axis() , legend = nv.models.legend().height(30) , controls = nv.models.legend().height(30) ; var margin = {top: 30, right: 20, bottom: 50, left: 60} , width = null , height = null , color = nv.utils.defaultColor() , showControls = true , showLegend = true , stacked = false , tooltips = true , tooltip = function(key, x, y, e, graph) { return '<h3>' + key + ' - ' + x + '</h3>' + '<p>' + y + '</p>' } , x //can be accessed via chart.xScale() , y //can be accessed via chart.yScale() , state = { stacked: stacked } , defaultState = null , noData = 'No Data Available.' , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState') , controlWidth = function() { return showControls ? 180 : 0 } ; multibar .stacked(stacked) ; xAxis .orient('left') .tickPadding(5) .highlightZero(false) .showMaxMin(false) .tickFormat(function(d) { return d }) ; yAxis .orient('bottom') .tickFormat(d3.format(',.1f')) ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var showTooltip = function(e, offsetElement) { var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), top = e.pos[1] + ( offsetElement.offsetTop || 0), x = xAxis.tickFormat()(multibar.x()(e.point, e.pointIndex)), y = yAxis.tickFormat()(multibar.y()(e.point, e.pointIndex)), content = tooltip(e.series.key, x, y, e, chart); nv.tooltip.show([left, top], content, e.value < 0 ? 'e' : 'w', null, offsetElement); }; //============================================================ function chart(selection) { selection.each(function(data) { var container = d3.select(this), that = this; var availableWidth = (width || parseInt(container.style('width')) || 960) - margin.left - margin.right, availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; chart.update = function() { container.transition().call(chart) }; chart.container = this; //set state.disabled state.disabled = data.map(function(d) { return !!d.disabled }); if (!defaultState) { var key; defaultState = {}; for (key in state) { if (state[key] instanceof Array) defaultState[key] = state[key].slice(0); else defaultState[key] = state[key]; } } //------------------------------------------------------------ // Display No Data message if there's nothing to show. if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) { var noDataText = container.selectAll('.nv-noData').data([noData]); noDataText.enter().append('text') .attr('class', 'nvd3 nv-noData') .attr('dy', '-.7em') .style('text-anchor', 'middle'); noDataText .attr('x', margin.left + availableWidth / 2) .attr('y', margin.top + availableHeight / 2) .text(function(d) { return d }); return chart; } else { container.selectAll('.nv-noData').remove(); } //------------------------------------------------------------ //------------------------------------------------------------ // Setup Scales x = multibar.xScale(); y = multibar.yScale(); //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-multiBarHorizontalChart').data([data]); var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-multiBarHorizontalChart').append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-x nv-axis'); gEnter.append('g').attr('class', 'nv-y nv-axis'); gEnter.append('g').attr('class', 'nv-barsWrap'); gEnter.append('g').attr('class', 'nv-legendWrap'); gEnter.append('g').attr('class', 'nv-controlsWrap'); //------------------------------------------------------------ //------------------------------------------------------------ // Legend if (showLegend) { legend.width(availableWidth - controlWidth()); if (multibar.barColor()) data.forEach(function(series,i) { series.color = d3.rgb('#ccc').darker(i * 1.5).toString(); }) g.select('.nv-legendWrap') .datum(data) .call(legend); if ( margin.top != legend.height()) { margin.top = legend.height(); availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; } g.select('.nv-legendWrap') .attr('transform', 'translate(' + controlWidth() + ',' + (-margin.top) +')'); } //------------------------------------------------------------ //------------------------------------------------------------ // Controls if (showControls) { var controlsData = [ { key: 'Grouped', disabled: multibar.stacked() }, { key: 'Stacked', disabled: !multibar.stacked() } ]; controls.width(controlWidth()).color(['#444', '#444', '#444']); g.select('.nv-controlsWrap') .datum(controlsData) .attr('transform', 'translate(0,' + (-margin.top) +')') .call(controls); } //------------------------------------------------------------ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ // Main Chart Component(s) multibar .disabled(data.map(function(series) { return series.disabled })) .width(availableWidth) .height(availableHeight) .color(data.map(function(d,i) { return d.color || color(d, i); }).filter(function(d,i) { return !data[i].disabled })) var barsWrap = g.select('.nv-barsWrap') .datum(data.filter(function(d) { return !d.disabled })) d3.transition(barsWrap).call(multibar); //------------------------------------------------------------ //------------------------------------------------------------ // Setup Axes xAxis .scale(x) .ticks( availableHeight / 24 ) .tickSize(-availableWidth, 0); d3.transition(g.select('.nv-x.nv-axis')) .call(xAxis); var xTicks = g.select('.nv-x.nv-axis').selectAll('g'); xTicks .selectAll('line, text') .style('opacity', 1) yAxis .scale(y) .ticks( availableWidth / 100 ) .tickSize( -availableHeight, 0); g.select('.nv-y.nv-axis') .attr('transform', 'translate(0,' + availableHeight + ')'); d3.transition(g.select('.nv-y.nv-axis')) .call(yAxis); //------------------------------------------------------------ //============================================================ // Event Handling/Dispatching (in chart's scope) //------------------------------------------------------------ legend.dispatch.on('legendClick', function(d,i) { d.disabled = !d.disabled; if (!data.filter(function(d) { return !d.disabled }).length) { data.map(function(d) { d.disabled = false; wrap.selectAll('.nv-series').classed('disabled', false); return d; }); } state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); chart.update(); }); legend.dispatch.on('legendDblclick', function(d) { //Double clicking should always enable current series, and disabled all others. data.forEach(function(d) { d.disabled = true; }); d.disabled = false; state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); chart.update(); }); controls.dispatch.on('legendClick', function(d,i) { if (!d.disabled) return; controlsData = controlsData.map(function(s) { s.disabled = true; return s; }); d.disabled = false; switch (d.key) { case 'Grouped': multibar.stacked(false); break; case 'Stacked': multibar.stacked(true); break; } state.stacked = multibar.stacked(); dispatch.stateChange(state); chart.update(); }); dispatch.on('tooltipShow', function(e) { if (tooltips) showTooltip(e, that.parentNode); }); // Update chart from a state object passed to event handler dispatch.on('changeState', function(e) { if (typeof e.disabled !== 'undefined') { data.forEach(function(series,i) { series.disabled = e.disabled[i]; }); state.disabled = e.disabled; } if (typeof e.stacked !== 'undefined') { multibar.stacked(e.stacked); state.stacked = e.stacked; } selection.call(chart); }); //============================================================ }); return chart; } //============================================================ // Event Handling/Dispatching (out of chart's scope) //------------------------------------------------------------ multibar.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); multibar.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); dispatch.on('tooltipHide', function() { if (tooltips) nv.tooltip.cleanup(); }); //============================================================ //============================================================ // Expose Public Variables //------------------------------------------------------------ // expose chart's sub-components chart.dispatch = dispatch; chart.multibar = multibar; chart.legend = legend; chart.xAxis = xAxis; chart.yAxis = yAxis; d3.rebind(chart, multibar, 'x', 'y', 'xDomain', 'yDomain', 'forceX', 'forceY', 'clipEdge', 'id', 'delay', 'showValues', 'valueFormat', 'stacked', 'barColor'); chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); legend.color(color); return chart; }; chart.showControls = function(_) { if (!arguments.length) return showControls; showControls = _; return chart; }; chart.showLegend = function(_) { if (!arguments.length) return showLegend; showLegend = _; return chart; }; chart.tooltip = function(_) { if (!arguments.length) return tooltip; tooltip = _; return chart; }; chart.tooltips = function(_) { if (!arguments.length) return tooltips; tooltips = _; return chart; }; chart.tooltipContent = function(_) { if (!arguments.length) return tooltip; tooltip = _; return chart; }; chart.state = function(_) { if (!arguments.length) return state; state = _; return chart; }; chart.defaultState = function(_) { if (!arguments.length) return defaultState; defaultState = _; return chart; }; chart.noData = function(_) { if (!arguments.length) return noData; noData = _; return chart; }; //============================================================ return chart; } nv.models.multiChart = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var margin = {top: 30, right: 20, bottom: 50, left: 60}, color = d3.scale.category20().range(), width = null, height = null, showLegend = true, tooltips = true, tooltip = function(key, x, y, e, graph) { return '<h3>' + key + '</h3>' + '<p>' + y + ' at ' + x + '</p>' }, x, y; //can be accessed via chart.lines.[x/y]Scale() //============================================================ // Private Variables //------------------------------------------------------------ var x = d3.scale.linear(), yScale1 = d3.scale.linear(), yScale2 = d3.scale.linear(), lines1 = nv.models.line().yScale(yScale1), lines2 = nv.models.line().yScale(yScale2), bars1 = nv.models.multiBar().stacked(false).yScale(yScale1), bars2 = nv.models.multiBar().stacked(false).yScale(yScale2), stack1 = nv.models.stackedArea().yScale(yScale1), stack2 = nv.models.stackedArea().yScale(yScale2), xAxis = nv.models.axis().scale(x).orient('bottom').tickPadding(5), yAxis1 = nv.models.axis().scale(yScale1).orient('left'), yAxis2 = nv.models.axis().scale(yScale2).orient('right'), legend = nv.models.legend().height(30), dispatch = d3.dispatch('tooltipShow', 'tooltipHide'); var showTooltip = function(e, offsetElement) { var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), top = e.pos[1] + ( offsetElement.offsetTop || 0), x = xAxis.tickFormat()(lines1.x()(e.point, e.pointIndex)), y = ((e.series.yAxis == 2) ? yAxis2 : yAxis1).tickFormat()(lines1.y()(e.point, e.pointIndex)), content = tooltip(e.series.key, x, y, e, chart); nv.tooltip.show([left, top], content, undefined, undefined, offsetElement.offsetParent); }; function chart(selection) { selection.each(function(data) { var container = d3.select(this), that = this; chart.update = function() { container.transition().call(chart); }; chart.container = this; var availableWidth = (width || parseInt(container.style('width')) || 960) - margin.left - margin.right, availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; var dataLines1 = data.filter(function(d) {return !d.disabled && d.type == 'line' && d.yAxis == 1}) var dataLines2 = data.filter(function(d) {return !d.disabled && d.type == 'line' && d.yAxis == 2}) var dataBars1 = data.filter(function(d) {return !d.disabled && d.type == 'bar' && d.yAxis == 1}) var dataBars2 = data.filter(function(d) {return !d.disabled && d.type == 'bar' && d.yAxis == 2}) var dataStack1 = data.filter(function(d) {return !d.disabled && d.type == 'area' && d.yAxis == 1}) var dataStack2 = data.filter(function(d) {return !d.disabled && d.type == 'area' && d.yAxis == 2}) var series1 = data.filter(function(d) {return !d.disabled && d.yAxis == 1}) .map(function(d) { return d.values.map(function(d,i) { return { x: d.x, y: d.y } }) }) var series2 = data.filter(function(d) {return !d.disabled && d.yAxis == 2}) .map(function(d) { return d.values.map(function(d,i) { return { x: d.x, y: d.y } }) }) x .domain(d3.extent(d3.merge(series1.concat(series2)), function(d) { return d.x } )) .range([0, availableWidth]); var wrap = container.selectAll('g.wrap.multiChart').data([data]); var gEnter = wrap.enter().append('g').attr('class', 'wrap nvd3 multiChart').append('g'); gEnter.append('g').attr('class', 'x axis'); gEnter.append('g').attr('class', 'y1 axis'); gEnter.append('g').attr('class', 'y2 axis'); gEnter.append('g').attr('class', 'stack1Wrap'); gEnter.append('g').attr('class', 'stack2Wrap'); gEnter.append('g').attr('class', 'bars1Wrap'); gEnter.append('g').attr('class', 'bars2Wrap'); gEnter.append('g').attr('class', 'lines1Wrap'); gEnter.append('g').attr('class', 'lines2Wrap'); gEnter.append('g').attr('class', 'legendWrap'); var g = wrap.select('g'); if (showLegend) { legend.width( availableWidth / 2 ); g.select('.legendWrap') .datum(data.map(function(series) { series.originalKey = series.originalKey === undefined ? series.key : series.originalKey; series.key = series.originalKey + (series.yAxis == 1 ? '' : ' (right axis)'); return series; })) .call(legend); if ( margin.top != legend.height()) { margin.top = legend.height(); availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; } g.select('.legendWrap') .attr('transform', 'translate(' + ( availableWidth / 2 ) + ',' + (-margin.top) +')'); } lines1 .width(availableWidth) .height(availableHeight) .interpolate("monotone") .color(data.map(function(d,i) { return d.color || color[i % color.length]; }).filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 1 && data[i].type == 'line'})); lines2 .width(availableWidth) .height(availableHeight) .interpolate("monotone") .color(data.map(function(d,i) { return d.color || color[i % color.length]; }).filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 2 && data[i].type == 'line'})); bars1 .width(availableWidth) .height(availableHeight) .color(data.map(function(d,i) { return d.color || color[i % color.length]; }).filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 1 && data[i].type == 'bar'})); bars2 .width(availableWidth) .height(availableHeight) .color(data.map(function(d,i) { return d.color || color[i % color.length]; }).filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 2 && data[i].type == 'bar'})); stack1 .width(availableWidth) .height(availableHeight) .color(data.map(function(d,i) { return d.color || color[i % color.length]; }).filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 1 && data[i].type == 'area'})); stack2 .width(availableWidth) .height(availableHeight) .color(data.map(function(d,i) { return d.color || color[i % color.length]; }).filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 2 && data[i].type == 'area'})); g.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); var lines1Wrap = g.select('.lines1Wrap') .datum(dataLines1.length ? dataLines1 : [{values:[]}]) var bars1Wrap = g.select('.bars1Wrap') .datum(dataBars1.length ? dataBars1 : [{values:[]}]) var stack1Wrap = g.select('.stack1Wrap') .datum(dataStack1.length ? dataStack1 : [{values:[]}]) var lines2Wrap = g.select('.lines2Wrap') .datum(dataLines2.length ? dataLines2 : [{values:[]}]) var bars2Wrap = g.select('.bars2Wrap') .datum(dataBars2.length ? dataBars2 : [{values:[]}]) var stack2Wrap = g.select('.stack2Wrap') .datum(dataStack2.length ? dataStack2 : [{values:[]}]) var extraValue1 = dataStack1.length ? dataStack1.map(function(a){return a.values}).reduce(function(a,b){ return a.map(function(aVal,i){return {x: aVal.x, y: aVal.y + b[i].y}}) }).concat([{x:0, y:0}]) : [{x:0, y:0}] var extraValue2 = dataStack2.length ? dataStack2.map(function(a){return a.values}).reduce(function(a,b){ return a.map(function(aVal,i){return {x: aVal.x, y: aVal.y + b[i].y}}) }).concat([{x:0, y:0}]) : [{x:0, y:0}] yScale1 .domain(d3.extent(d3.merge(series1).concat(extraValue1), function(d) { return d.y } )) .range([0, availableHeight]) yScale2 .domain(d3.extent(d3.merge(series2).concat(extraValue2), function(d) { return d.y } )) .range([0, availableHeight]) lines1.yDomain(yScale1.domain()) bars1.yDomain(yScale1.domain()) stack1.yDomain(yScale1.domain()) lines2.yDomain(yScale2.domain()) bars2.yDomain(yScale2.domain()) stack2.yDomain(yScale2.domain()) d3.transition(stack1Wrap).call(stack1); d3.transition(stack2Wrap).call(stack2); d3.transition(bars1Wrap).call(bars1); d3.transition(bars2Wrap).call(bars2); d3.transition(lines1Wrap).call(lines1); d3.transition(lines2Wrap).call(lines2); xAxis .ticks( availableWidth / 100 ) .tickSize(-availableHeight, 0); g.select('.x.axis') .attr('transform', 'translate(0,' + availableHeight + ')'); d3.transition(g.select('.x.axis')) .call(xAxis); yAxis1 .ticks( availableHeight / 36 ) .tickSize( -availableWidth, 0); d3.transition(g.select('.y1.axis')) .call(yAxis1); yAxis2 .ticks( availableHeight / 36 ) .tickSize( -availableWidth, 0); d3.transition(g.select('.y2.axis')) .call(yAxis2); g.select('.y2.axis') .style('opacity', series2.length ? 1 : 0) .attr('transform', 'translate(' + x.range()[1] + ',0)'); legend.dispatch.on('legendClick', function(d,i) { d.disabled = !d.disabled; if (!data.filter(function(d) { return !d.disabled }).length) { data.map(function(d) { d.disabled = false; wrap.selectAll('.series').classed('disabled', false); return d; }); } chart.update(); }); dispatch.on('tooltipShow', function(e) { if (tooltips) showTooltip(e, that.parentNode); }); }); return chart; } //============================================================ // Event Handling/Dispatching (out of chart's scope) //------------------------------------------------------------ lines1.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); lines1.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); lines2.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); lines2.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); bars1.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); bars1.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); bars2.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); bars2.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); stack1.dispatch.on('tooltipShow', function(e) { //disable tooltips when value ~= 0 //// TODO: consider removing points from voronoi that have 0 value instead of this hack if (!Math.round(stack1.y()(e.point) * 100)) { // 100 will not be good for very small numbers... will have to think about making this valu dynamic, based on data range setTimeout(function() { d3.selectAll('.point.hover').classed('hover', false) }, 0); return false; } e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top], dispatch.tooltipShow(e); }); stack1.dispatch.on('tooltipHide', function(e) { dispatch.tooltipHide(e); }); stack2.dispatch.on('tooltipShow', function(e) { //disable tooltips when value ~= 0 //// TODO: consider removing points from voronoi that have 0 value instead of this hack if (!Math.round(stack2.y()(e.point) * 100)) { // 100 will not be good for very small numbers... will have to think about making this valu dynamic, based on data range setTimeout(function() { d3.selectAll('.point.hover').classed('hover', false) }, 0); return false; } e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top], dispatch.tooltipShow(e); }); stack2.dispatch.on('tooltipHide', function(e) { dispatch.tooltipHide(e); }); lines1.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); lines1.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); lines2.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); lines2.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); dispatch.on('tooltipHide', function() { if (tooltips) nv.tooltip.cleanup(); }); //============================================================ // Global getters and setters //------------------------------------------------------------ chart.dispatch = dispatch; chart.lines1 = lines1; chart.lines2 = lines2; chart.bars1 = bars1; chart.bars2 = bars2; chart.stack1 = stack1; chart.stack2 = stack2; chart.xAxis = xAxis; chart.yAxis1 = yAxis1; chart.yAxis2 = yAxis2; chart.x = function(_) { if (!arguments.length) return getX; getX = _; lines1.x(_); bars1.x(_); return chart; }; chart.y = function(_) { if (!arguments.length) return getY; getY = _; lines1.y(_); bars1.y(_); return chart; }; chart.margin = function(_) { if (!arguments.length) return margin; margin = _; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = _; legend.color(_); return chart; }; chart.showLegend = function(_) { if (!arguments.length) return showLegend; showLegend = _; return chart; }; chart.tooltips = function(_) { if (!arguments.length) return tooltips; tooltips = _; return chart; }; chart.tooltipContent = function(_) { if (!arguments.length) return tooltip; tooltip = _; return chart; }; return chart; } nv.models.ohlcBar = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var margin = {top: 0, right: 0, bottom: 0, left: 0} , width = 960 , height = 500 , id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one , x = d3.scale.linear() , y = d3.scale.linear() , getX = function(d) { return d.x } , getY = function(d) { return d.y } , getOpen = function(d) { return d.open } , getClose = function(d) { return d.close } , getHigh = function(d) { return d.high } , getLow = function(d) { return d.low } , forceX = [] , forceY = [] , padData = false // If true, adds half a data points width to front and back, for lining up a line chart with a bar chart , clipEdge = true , color = nv.utils.defaultColor() , xDomain , yDomain , dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout') ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ //TODO: store old scales for transitions //============================================================ function chart(selection) { selection.each(function(data) { var availableWidth = width - margin.left - margin.right, availableHeight = height - margin.top - margin.bottom, container = d3.select(this); //------------------------------------------------------------ // Setup Scales x .domain(xDomain || d3.extent(data[0].values.map(getX).concat(forceX) )); if (padData) x.range([availableWidth * .5 / data[0].values.length, availableWidth * (data[0].values.length - .5) / data[0].values.length ]); else x.range([0, availableWidth]); y .domain(yDomain || [ d3.min(data[0].values.map(getLow).concat(forceY)), d3.max(data[0].values.map(getHigh).concat(forceY)) ]) .range([availableHeight, 0]); // If scale's domain don't have a range, slightly adjust to make one... so a chart can show a single data point if (x.domain()[0] === x.domain()[1] || y.domain()[0] === y.domain()[1]) singlePoint = true; if (x.domain()[0] === x.domain()[1]) x.domain()[0] ? x.domain([x.domain()[0] - x.domain()[0] * 0.01, x.domain()[1] + x.domain()[1] * 0.01]) : x.domain([-1,1]); if (y.domain()[0] === y.domain()[1]) y.domain()[0] ? y.domain([y.domain()[0] + y.domain()[0] * 0.01, y.domain()[1] - y.domain()[1] * 0.01]) : y.domain([-1,1]); //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = d3.select(this).selectAll('g.nv-wrap.nv-ohlcBar').data([data[0].values]); var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-ohlcBar'); var defsEnter = wrapEnter.append('defs'); var gEnter = wrapEnter.append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-ticks'); wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ container .on('click', function(d,i) { dispatch.chartClick({ data: d, index: i, pos: d3.event, id: id }); }); defsEnter.append('clipPath') .attr('id', 'nv-chart-clip-path-' + id) .append('rect'); wrap.select('#nv-chart-clip-path-' + id + ' rect') .attr('width', availableWidth) .attr('height', availableHeight); g .attr('clip-path', clipEdge ? 'url(#nv-chart-clip-path-' + id + ')' : ''); var ticks = wrap.select('.nv-ticks').selectAll('.nv-tick') .data(function(d) { return d }); ticks.exit().remove(); var ticksEnter = ticks.enter().append('path') .attr('class', function(d,i,j) { return (getOpen(d,i) > getClose(d,i) ? 'nv-tick negative' : 'nv-tick positive') + ' nv-tick-' + j + '-' + i }) .attr('d', function(d,i) { var w = (availableWidth / data[0].values.length) * .9; return 'm0,0l0,' + (y(getOpen(d,i)) - y(getHigh(d,i))) + 'l' + (-w/2) + ',0l' + (w/2) + ',0l0,' + (y(getLow(d,i)) - y(getOpen(d,i))) + 'l0,' + (y(getClose(d,i)) - y(getLow(d,i))) + 'l' + (w/2) + ',0l' + (-w/2) + ',0z'; }) .attr('transform', function(d,i) { return 'translate(' + x(getX(d,i)) + ',' + y(getHigh(d,i)) + ')'; }) //.attr('fill', function(d,i) { return color[0]; }) //.attr('stroke', function(d,i) { return color[0]; }) //.attr('x', 0 ) //.attr('y', function(d,i) { return y(Math.max(0, getY(d,i))) }) //.attr('height', function(d,i) { return Math.abs(y(getY(d,i)) - y(0)) }) .on('mouseover', function(d,i) { d3.select(this).classed('hover', true); dispatch.elementMouseover({ point: d, series: data[0], pos: [x(getX(d,i)), y(getY(d,i))], // TODO: Figure out why the value appears to be shifted pointIndex: i, seriesIndex: 0, e: d3.event }); }) .on('mouseout', function(d,i) { d3.select(this).classed('hover', false); dispatch.elementMouseout({ point: d, series: data[0], pointIndex: i, seriesIndex: 0, e: d3.event }); }) .on('click', function(d,i) { dispatch.elementClick({ //label: d[label], value: getY(d,i), data: d, index: i, pos: [x(getX(d,i)), y(getY(d,i))], e: d3.event, id: id }); d3.event.stopPropagation(); }) .on('dblclick', function(d,i) { dispatch.elementDblClick({ //label: d[label], value: getY(d,i), data: d, index: i, pos: [x(getX(d,i)), y(getY(d,i))], e: d3.event, id: id }); d3.event.stopPropagation(); }); ticks .attr('class', function(d,i,j) { return (getOpen(d,i) > getClose(d,i) ? 'nv-tick negative' : 'nv-tick positive') + ' nv-tick-' + j + '-' + i }) d3.transition(ticks) .attr('transform', function(d,i) { return 'translate(' + x(getX(d,i)) + ',' + y(getHigh(d,i)) + ')'; }) .attr('d', function(d,i) { var w = (availableWidth / data[0].values.length) * .9; return 'm0,0l0,' + (y(getOpen(d,i)) - y(getHigh(d,i))) + 'l' + (-w/2) + ',0l' + (w/2) + ',0l0,' + (y(getLow(d,i)) - y(getOpen(d,i))) + 'l0,' + (y(getClose(d,i)) - y(getLow(d,i))) + 'l' + (w/2) + ',0l' + (-w/2) + ',0z'; }) //.attr('width', (availableWidth / data[0].values.length) * .9 ) //d3.transition(ticks) //.attr('y', function(d,i) { return y(Math.max(0, getY(d,i))) }) //.attr('height', function(d,i) { return Math.abs(y(getY(d,i)) - y(0)) }); //.order(); // not sure if this makes any sense for this model }); return chart; } //============================================================ // Expose Public Variables //------------------------------------------------------------ chart.dispatch = dispatch; chart.x = function(_) { if (!arguments.length) return getX; getX = _; return chart; }; chart.y = function(_) { if (!arguments.length) return getY; getY = _; return chart; }; chart.open = function(_) { if (!arguments.length) return getOpen; getOpen = _; return chart; }; chart.close = function(_) { if (!arguments.length) return getClose; getClose = _; return chart; }; chart.high = function(_) { if (!arguments.length) return getHigh; getHigh = _; return chart; }; chart.low = function(_) { if (!arguments.length) return getLow; getLow = _; return chart; }; chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.xScale = function(_) { if (!arguments.length) return x; x = _; return chart; }; chart.yScale = function(_) { if (!arguments.length) return y; y = _; return chart; }; chart.xDomain = function(_) { if (!arguments.length) return xDomain; xDomain = _; return chart; }; chart.yDomain = function(_) { if (!arguments.length) return yDomain; yDomain = _; return chart; }; chart.forceX = function(_) { if (!arguments.length) return forceX; forceX = _; return chart; }; chart.forceY = function(_) { if (!arguments.length) return forceY; forceY = _; return chart; }; chart.padData = function(_) { if (!arguments.length) return padData; padData = _; return chart; }; chart.clipEdge = function(_) { if (!arguments.length) return clipEdge; clipEdge = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); return chart; }; chart.id = function(_) { if (!arguments.length) return id; id = _; return chart; }; //============================================================ return chart; } nv.models.pie = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var margin = {top: 0, right: 0, bottom: 0, left: 0} , width = 500 , height = 500 , getValues = function(d) { return d.values } , getX = function(d) { return d.x } , getY = function(d) { return d.y } , getDescription = function(d) { return d.description } , id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one , color = nv.utils.defaultColor() , valueFormat = d3.format(',.2f') , showLabels = true , pieLabelsOutside = true , donutLabelsOutside = false , labelThreshold = .02 //if slice percentage is under this, don't show label , donut = false , labelSunbeamLayout = false , startAngle = false , endAngle = false , donutRatio = 0.5 , dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout') ; //============================================================ function chart(selection) { selection.each(function(data) { var availableWidth = width - margin.left - margin.right, availableHeight = height - margin.top - margin.bottom, radius = Math.min(availableWidth, availableHeight) / 2, arcRadius = radius-(radius / 5), container = d3.select(this); //------------------------------------------------------------ // Setup containers and skeleton of chart //var wrap = container.selectAll('.nv-wrap.nv-pie').data([data]); var wrap = container.selectAll('.nv-wrap.nv-pie').data([getValues(data[0])]); var wrapEnter = wrap.enter().append('g').attr('class','nvd3 nv-wrap nv-pie nv-chart-' + id); var gEnter = wrapEnter.append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-pie'); wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); g.select('.nv-pie').attr('transform', 'translate(' + availableWidth / 2 + ',' + availableHeight / 2 + ')'); //------------------------------------------------------------ container .on('click', function(d,i) { dispatch.chartClick({ data: d, index: i, pos: d3.event, id: id }); }); var arc = d3.svg.arc() .outerRadius(arcRadius); if (startAngle) arc.startAngle(startAngle) if (endAngle) arc.endAngle(endAngle); if (donut) arc.innerRadius(radius * donutRatio); // Setup the Pie chart and choose the data element var pie = d3.layout.pie() .sort(null) .value(function(d) { return d.disabled ? 0 : getY(d) }); var slices = wrap.select('.nv-pie').selectAll('.nv-slice') .data(pie); slices.exit().remove(); var ae = slices.enter().append('g') .attr('class', 'nv-slice') .on('mouseover', function(d,i){ d3.select(this).classed('hover', true); dispatch.elementMouseover({ label: getX(d.data), value: getY(d.data), point: d.data, pointIndex: i, pos: [d3.event.pageX, d3.event.pageY], id: id }); }) .on('mouseout', function(d,i){ d3.select(this).classed('hover', false); dispatch.elementMouseout({ label: getX(d.data), value: getY(d.data), point: d.data, index: i, id: id }); }) .on('click', function(d,i) { dispatch.elementClick({ label: getX(d.data), value: getY(d.data), point: d.data, index: i, pos: d3.event, id: id }); d3.event.stopPropagation(); }) .on('dblclick', function(d,i) { dispatch.elementDblClick({ label: getX(d.data), value: getY(d.data), point: d.data, index: i, pos: d3.event, id: id }); d3.event.stopPropagation(); }); slices .attr('fill', function(d,i) { return color(d, i); }) .attr('stroke', function(d,i) { return color(d, i); }); var paths = ae.append('path') .each(function(d) { this._current = d; }); //.attr('d', arc); d3.transition(slices.select('path')) .attr('d', arc) .attrTween('d', arcTween); if (showLabels) { // This does the normal label var labelsArc = d3.svg.arc().innerRadius(0); if (pieLabelsOutside){ labelsArc = arc; } if (donutLabelsOutside) { labelsArc = d3.svg.arc().outerRadius(arc.outerRadius()); } ae.append("g").classed("nv-label", true) .each(function(d, i) { var group = d3.select(this); group .attr('transform', function(d) { if (labelSunbeamLayout) { d.outerRadius = arcRadius + 10; // Set Outer Coordinate d.innerRadius = arcRadius + 15; // Set Inner Coordinate var rotateAngle = (d.startAngle + d.endAngle) / 2 * (180 / Math.PI); if ((d.startAngle+d.endAngle)/2 < Math.PI) { rotateAngle -= 90; } else { rotateAngle += 90; } return 'translate(' + labelsArc.centroid(d) + ') rotate(' + rotateAngle + ')'; } else { d.outerRadius = radius + 10; // Set Outer Coordinate d.innerRadius = radius + 15; // Set Inner Coordinate return 'translate(' + labelsArc.centroid(d) + ')' } }); group.append('rect') .style('stroke', '#fff') .style('fill', '#fff') .attr("rx", 3) .attr("ry", 3); group.append('text') .style('text-anchor', labelSunbeamLayout ? ((d.startAngle + d.endAngle) / 2 < Math.PI ? 'start' : 'end') : 'middle') //center the text on it's origin or begin/end if orthogonal aligned .style('fill', '#000') }); slices.select(".nv-label").transition() .attr('transform', function(d) { if (labelSunbeamLayout) { d.outerRadius = arcRadius + 10; // Set Outer Coordinate d.innerRadius = arcRadius + 15; // Set Inner Coordinate var rotateAngle = (d.startAngle + d.endAngle) / 2 * (180 / Math.PI); if ((d.startAngle+d.endAngle)/2 < Math.PI) { rotateAngle -= 90; } else { rotateAngle += 90; } return 'translate(' + labelsArc.centroid(d) + ') rotate(' + rotateAngle + ')'; } else { d.outerRadius = radius + 10; // Set Outer Coordinate d.innerRadius = radius + 15; // Set Inner Coordinate return 'translate(' + labelsArc.centroid(d) + ')' } }); slices.each(function(d, i) { var slice = d3.select(this); slice .select(".nv-label text") .style('text-anchor', labelSunbeamLayout ? ((d.startAngle + d.endAngle) / 2 < Math.PI ? 'start' : 'end') : 'middle') //center the text on it's origin or begin/end if orthogonal aligned .text(function(d, i) { var percent = (d.endAngle - d.startAngle) / (2 * Math.PI); return (d.value && percent > labelThreshold) ? getX(d.data) : ''; }); var textBox = slice.select('text').node().getBBox(); slice.select(".nv-label rect") .attr("width", textBox.width + 10) .attr("height", textBox.height + 10) .attr("transform", function() { return "translate(" + [textBox.x - 5, textBox.y - 5] + ")"; }); }); } // Computes the angle of an arc, converting from radians to degrees. function angle(d) { var a = (d.startAngle + d.endAngle) * 90 / Math.PI - 90; return a > 90 ? a - 180 : a; } function arcTween(a) { a.endAngle = isNaN(a.endAngle) ? 0 : a.endAngle; a.startAngle = isNaN(a.startAngle) ? 0 : a.startAngle; if (!donut) a.innerRadius = 0; var i = d3.interpolate(this._current, a); this._current = i(0); return function(t) { return arc(i(t)); }; } function tweenPie(b) { b.innerRadius = 0; var i = d3.interpolate({startAngle: 0, endAngle: 0}, b); return function(t) { return arc(i(t)); }; } }); return chart; } //============================================================ // Expose Public Variables //------------------------------------------------------------ chart.dispatch = dispatch; chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.values = function(_) { if (!arguments.length) return getValues; getValues = _; return chart; }; chart.x = function(_) { if (!arguments.length) return getX; getX = _; return chart; }; chart.y = function(_) { if (!arguments.length) return getY; getY = d3.functor(_); return chart; }; chart.description = function(_) { if (!arguments.length) return getDescription; getDescription = _; return chart; }; chart.showLabels = function(_) { if (!arguments.length) return showLabels; showLabels = _; return chart; }; chart.labelSunbeamLayout = function(_) { if (!arguments.length) return labelSunbeamLayout; labelSunbeamLayout = _; return chart; }; chart.donutLabelsOutside = function(_) { if (!arguments.length) return donutLabelsOutside; donutLabelsOutside = _; return chart; }; chart.pieLabelsOutside = function(_) { if (!arguments.length) return pieLabelsOutside; pieLabelsOutside = _; return chart; }; chart.donut = function(_) { if (!arguments.length) return donut; donut = _; return chart; }; chart.donutRatio = function(_) { if (!arguments.length) return donutRatio; donutRatio = _; return chart; }; chart.startAngle = function(_) { if (!arguments.length) return startAngle; startAngle = _; return chart; }; chart.endAngle = function(_) { if (!arguments.length) return endAngle; endAngle = _; return chart; }; chart.id = function(_) { if (!arguments.length) return id; id = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); return chart; }; chart.valueFormat = function(_) { if (!arguments.length) return valueFormat; valueFormat = _; return chart; }; chart.labelThreshold = function(_) { if (!arguments.length) return labelThreshold; labelThreshold = _; return chart; }; //============================================================ return chart; } nv.models.pieChart = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var pie = nv.models.pie() , legend = nv.models.legend() ; var margin = {top: 30, right: 20, bottom: 20, left: 20} , width = null , height = null , showLegend = true , color = nv.utils.defaultColor() , tooltips = true , tooltip = function(key, y, e, graph) { return '<h3>' + key + '</h3>' + '<p>' + y + '</p>' } , state = {} , defaultState = null , noData = "No Data Available." , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState') ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var showTooltip = function(e, offsetElement) { var tooltipLabel = pie.description()(e.point) || pie.x()(e.point) var left = e.pos[0] + ( (offsetElement && offsetElement.offsetLeft) || 0 ), top = e.pos[1] + ( (offsetElement && offsetElement.offsetTop) || 0), y = pie.valueFormat()(pie.y()(e.point)), content = tooltip(tooltipLabel, y, e, chart); nv.tooltip.show([left, top], content, e.value < 0 ? 'n' : 's', null, offsetElement); }; //============================================================ function chart(selection) { selection.each(function(data) { var container = d3.select(this), that = this; var availableWidth = (width || parseInt(container.style('width')) || 960) - margin.left - margin.right, availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; chart.update = function() { container.transition().call(chart); }; chart.container = this; //set state.disabled state.disabled = data[0].map(function(d) { return !!d.disabled }); if (!defaultState) { var key; defaultState = {}; for (key in state) { if (state[key] instanceof Array) defaultState[key] = state[key].slice(0); else defaultState[key] = state[key]; } } //------------------------------------------------------------ // Display No Data message if there's nothing to show. if (!data[0] || !data[0].length) { var noDataText = container.selectAll('.nv-noData').data([noData]); noDataText.enter().append('text') .attr('class', 'nvd3 nv-noData') .attr('dy', '-.7em') .style('text-anchor', 'middle'); noDataText .attr('x', margin.left + availableWidth / 2) .attr('y', margin.top + availableHeight / 2) .text(function(d) { return d }); return chart; } else { container.selectAll('.nv-noData').remove(); } //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-pieChart').data([data]); var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-pieChart').append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-pieWrap'); gEnter.append('g').attr('class', 'nv-legendWrap'); //------------------------------------------------------------ //------------------------------------------------------------ // Legend if (showLegend) { legend .width( availableWidth ) .key(pie.x()); wrap.select('.nv-legendWrap') .datum(pie.values()(data[0])) .call(legend); if ( margin.top != legend.height()) { margin.top = legend.height(); availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; } wrap.select('.nv-legendWrap') .attr('transform', 'translate(0,' + (-margin.top) +')'); } //------------------------------------------------------------ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ // Main Chart Component(s) pie .width(availableWidth) .height(availableHeight); var pieWrap = g.select('.nv-pieWrap') .datum(data); d3.transition(pieWrap).call(pie); //------------------------------------------------------------ //============================================================ // Event Handling/Dispatching (in chart's scope) //------------------------------------------------------------ legend.dispatch.on('legendClick', function(d,i, that) { d.disabled = !d.disabled; if (!pie.values()(data[0]).filter(function(d) { return !d.disabled }).length) { pie.values()(data[0]).map(function(d) { d.disabled = false; wrap.selectAll('.nv-series').classed('disabled', false); return d; }); } state.disabled = data[0].map(function(d) { return !!d.disabled }); dispatch.stateChange(state); chart.update(); }); pie.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); // Update chart from a state object passed to event handler dispatch.on('changeState', function(e) { if (typeof e.disabled !== 'undefined') { data[0].forEach(function(series,i) { series.disabled = e.disabled[i]; }); state.disabled = e.disabled; } chart.update(); }); //============================================================ }); return chart; } //============================================================ // Event Handling/Dispatching (out of chart's scope) //------------------------------------------------------------ pie.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); dispatch.on('tooltipShow', function(e) { if (tooltips) showTooltip(e); }); dispatch.on('tooltipHide', function() { if (tooltips) nv.tooltip.cleanup(); }); //============================================================ //============================================================ // Expose Public Variables //------------------------------------------------------------ // expose chart's sub-components chart.legend = legend; chart.dispatch = dispatch; chart.pie = pie; d3.rebind(chart, pie, 'valueFormat', 'values', 'x', 'y', 'description', 'id', 'showLabels', 'donutLabelsOutside', 'pieLabelsOutside', 'donut', 'donutRatio', 'labelThreshold'); chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); legend.color(color); pie.color(color); return chart; }; chart.showLegend = function(_) { if (!arguments.length) return showLegend; showLegend = _; return chart; }; chart.tooltips = function(_) { if (!arguments.length) return tooltips; tooltips = _; return chart; }; chart.tooltipContent = function(_) { if (!arguments.length) return tooltip; tooltip = _; return chart; }; chart.state = function(_) { if (!arguments.length) return state; state = _; return chart; }; chart.defaultState = function(_) { if (!arguments.length) return defaultState; defaultState = _; return chart; }; chart.noData = function(_) { if (!arguments.length) return noData; noData = _; return chart; }; //============================================================ return chart; } nv.models.scatter = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var margin = {top: 0, right: 0, bottom: 0, left: 0} , width = 960 , height = 500 , color = nv.utils.defaultColor() // chooses color , id = Math.floor(Math.random() * 100000) //Create semi-unique ID incase user doesn't select one , x = d3.scale.linear() , y = d3.scale.linear() , z = d3.scale.linear() //linear because d3.svg.shape.size is treated as area , getX = function(d) { return d.x } // accessor to get the x value , getY = function(d) { return d.y } // accessor to get the y value , getSize = function(d) { return d.size || 1} // accessor to get the point size , getShape = function(d) { return d.shape || 'circle' } // accessor to get point shape , onlyCircles = true // Set to false to use shapes , forceX = [] // List of numbers to Force into the X scale (ie. 0, or a max / min, etc.) , forceY = [] // List of numbers to Force into the Y scale , forceSize = [] // List of numbers to Force into the Size scale , interactive = true // If true, plots a voronoi overlay for advanced point intersection , pointKey = null , pointActive = function(d) { return !d.notActive } // any points that return false will be filtered out , padData = false // If true, adds half a data points width to front and back, for lining up a line chart with a bar chart , padDataOuter = .1 //outerPadding to imitate ordinal scale outer padding , clipEdge = false // if true, masks points within x and y scale , clipVoronoi = true // if true, masks each point with a circle... can turn off to slightly increase performance , clipRadius = function() { return 25 } // function to get the radius for voronoi point clips , xDomain = null // Override x domain (skips the calculation from data) , yDomain = null // Override y domain , sizeDomain = null // Override point size domain , sizeRange = null , singlePoint = false , dispatch = d3.dispatch('elementClick', 'elementMouseover', 'elementMouseout') , useVoronoi = true ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var x0, y0, z0 // used to store previous scales , timeoutID , needsUpdate = false // Flag for when the points are visually updating, but the interactive layer is behind, to disable tooltips ; //============================================================ function chart(selection) { selection.each(function(data) { var availableWidth = width - margin.left - margin.right, availableHeight = height - margin.top - margin.bottom, container = d3.select(this); //add series index to each data point for reference data = data.map(function(series, i) { series.values = series.values.map(function(point) { point.series = i; return point; }); return series; }); //------------------------------------------------------------ // Setup Scales // remap and flatten the data for use in calculating the scales' domains var seriesData = (xDomain && yDomain && sizeDomain) ? [] : // if we know xDomain and yDomain and sizeDomain, no need to calculate.... if Size is constant remember to set sizeDomain to speed up performance d3.merge( data.map(function(d) { return d.values.map(function(d,i) { return { x: getX(d,i), y: getY(d,i), size: getSize(d,i) } }) }) ); x .domain(xDomain || d3.extent(seriesData.map(function(d) { return d.x; }).concat(forceX))) if (padData && data[0]) x.range([(availableWidth * padDataOuter + availableWidth) / (2 *data[0].values.length), availableWidth - availableWidth * (1 + padDataOuter) / (2 * data[0].values.length) ]); //x.range([availableWidth * .5 / data[0].values.length, availableWidth * (data[0].values.length - .5) / data[0].values.length ]); else x.range([0, availableWidth]); y .domain(yDomain || d3.extent(seriesData.map(function(d) { return d.y }).concat(forceY))) .range([availableHeight, 0]); z .domain(sizeDomain || d3.extent(seriesData.map(function(d) { return d.size }).concat(forceSize))) .range(sizeRange || [16, 256]); // If scale's domain don't have a range, slightly adjust to make one... so a chart can show a single data point if (x.domain()[0] === x.domain()[1] || y.domain()[0] === y.domain()[1]) singlePoint = true; if (x.domain()[0] === x.domain()[1]) x.domain()[0] ? x.domain([x.domain()[0] - x.domain()[0] * 0.01, x.domain()[1] + x.domain()[1] * 0.01]) : x.domain([-1,1]); if (y.domain()[0] === y.domain()[1]) y.domain()[0] ? y.domain([y.domain()[0] + y.domain()[0] * 0.01, y.domain()[1] - y.domain()[1] * 0.01]) : y.domain([-1,1]); if ( isNaN(x.domain()[0])) { x.domain([-1,1]); } if ( isNaN(y.domain()[0])) { y.domain([-1,1]); } x0 = x0 || x; y0 = y0 || y; z0 = z0 || z; //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-scatter').data([data]); var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-scatter nv-chart-' + id + (singlePoint ? ' nv-single-point' : '')); var defsEnter = wrapEnter.append('defs'); var gEnter = wrapEnter.append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-groups'); gEnter.append('g').attr('class', 'nv-point-paths'); wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ defsEnter.append('clipPath') .attr('id', 'nv-edge-clip-' + id) .append('rect'); wrap.select('#nv-edge-clip-' + id + ' rect') .attr('width', availableWidth) .attr('height', availableHeight); g .attr('clip-path', clipEdge ? 'url(#nv-edge-clip-' + id + ')' : ''); function updateInteractiveLayer() { if (!interactive) return false; var eventElements; var vertices = d3.merge(data.map(function(group, groupIndex) { return group.values .map(function(point, pointIndex) { // *Adding noise to make duplicates very unlikely // *Injecting series and point index for reference /* *Adding a 'jitter' to the points, because there's an issue in d3.geom.voronoi. */ var pX = getX(point,pointIndex) + Math.random() * 1e-7; var pY = getY(point,pointIndex) + Math.random() * 1e-7; return [x(pX), y(pY), groupIndex, pointIndex, point]; //temp hack to add noise untill I think of a better way so there are no duplicates }) .filter(function(pointArray, pointIndex) { return pointActive(pointArray[4], pointIndex); // Issue #237.. move filter to after map, so pointIndex is correct! }) }) ); //inject series and point index for reference into voronoi if (useVoronoi === true) { if (clipVoronoi) { var pointClipsEnter = wrap.select('defs').selectAll('.nv-point-clips') .data([id]) .enter(); pointClipsEnter.append('clipPath') .attr('class', 'nv-point-clips') .attr('id', 'nv-points-clip-' + id); var pointClips = wrap.select('#nv-points-clip-' + id).selectAll('circle') .data(vertices); pointClips.enter().append('circle') .attr('r', clipRadius); pointClips.exit().remove(); pointClips .attr('cx', function(d) { return d[0] }) .attr('cy', function(d) { return d[1] }); wrap.select('.nv-point-paths') .attr('clip-path', 'url(#nv-points-clip-' + id + ')'); } if(vertices.length) { // Issue #283 - Adding 2 dummy points to the voronoi b/c voronoi requires min 3 points to work vertices.push([x.range()[0] - 20, y.range()[0] - 20, null, null]); vertices.push([x.range()[1] + 20, y.range()[1] + 20, null, null]); vertices.push([x.range()[0] - 20, y.range()[0] + 20, null, null]); vertices.push([x.range()[1] + 20, y.range()[1] - 20, null, null]); } var bounds = d3.geom.polygon([ [-10,-10], [-10,height + 10], [width + 10,height + 10], [width + 10,-10] ]); var voronoi = d3.geom.voronoi(vertices).map(function(d, i) { return { 'data': bounds.clip(d), 'series': vertices[i][2], 'point': vertices[i][3] } }); var pointPaths = wrap.select('.nv-point-paths').selectAll('path') .data(voronoi); pointPaths.enter().append('path') .attr('class', function(d,i) { return 'nv-path-'+i; }); pointPaths.exit().remove(); pointPaths .attr('d', function(d) { if (d.data.length === 0) return 'M 0 0' else return 'M' + d.data.join('L') + 'Z'; }); pointPaths .on('click', function(d) { if (needsUpdate) return 0; var series = data[d.series], point = series.values[d.point]; dispatch.elementClick({ point: point, series: series, pos: [x(getX(point, d.point)) + margin.left, y(getY(point, d.point)) + margin.top], seriesIndex: d.series, pointIndex: d.point }); }) .on('mouseover', function(d) { if (needsUpdate) return 0; var series = data[d.series], point = series.values[d.point]; dispatch.elementMouseover({ point: point, series: series, pos: [x(getX(point, d.point)) + margin.left, y(getY(point, d.point)) + margin.top], seriesIndex: d.series, pointIndex: d.point }); }) .on('mouseout', function(d, i) { if (needsUpdate) return 0; var series = data[d.series], point = series.values[d.point]; dispatch.elementMouseout({ point: point, series: series, seriesIndex: d.series, pointIndex: d.point }); }); } else { /* // bring data in form needed for click handlers var dataWithPoints = vertices.map(function(d, i) { return { 'data': d, 'series': vertices[i][2], 'point': vertices[i][3] } }); */ // add event handlers to points instead voronoi paths wrap.select('.nv-groups').selectAll('.nv-group') .selectAll('.nv-point') //.data(dataWithPoints) //.style('pointer-events', 'auto') // recativate events, disabled by css .on('click', function(d,i) { //nv.log('test', d, i); if (needsUpdate || !data[d.series]) return 0; //check if this is a dummy point var series = data[d.series], point = series.values[i]; dispatch.elementClick({ point: point, series: series, pos: [x(getX(point, i)) + margin.left, y(getY(point, i)) + margin.top], seriesIndex: d.series, pointIndex: i }); }) .on('mouseover', function(d,i) { if (needsUpdate || !data[d.series]) return 0; //check if this is a dummy point var series = data[d.series], point = series.values[i]; dispatch.elementMouseover({ point: point, series: series, pos: [x(getX(point, i)) + margin.left, y(getY(point, i)) + margin.top], seriesIndex: d.series, pointIndex: i }); }) .on('mouseout', function(d,i) { if (needsUpdate || !data[d.series]) return 0; //check if this is a dummy point var series = data[d.series], point = series.values[i]; dispatch.elementMouseout({ point: point, series: series, seriesIndex: d.series, pointIndex: i }); }); } needsUpdate = false; } needsUpdate = true; var groups = wrap.select('.nv-groups').selectAll('.nv-group') .data(function(d) { return d }, function(d) { return d.key }); groups.enter().append('g') .style('stroke-opacity', 1e-6) .style('fill-opacity', 1e-6); d3.transition(groups.exit()) .style('stroke-opacity', 1e-6) .style('fill-opacity', 1e-6) .remove(); groups .attr('class', function(d,i) { return 'nv-group nv-series-' + i }) .classed('hover', function(d) { return d.hover }); d3.transition(groups) .style('fill', function(d,i) { return color(d, i) }) .style('stroke', function(d,i) { return color(d, i) }) .style('stroke-opacity', 1) .style('fill-opacity', .5); if (onlyCircles) { var points = groups.selectAll('circle.nv-point') .data(function(d) { return d.values }, pointKey); points.enter().append('circle') .attr('cx', function(d,i) { return x0(getX(d,i)) }) .attr('cy', function(d,i) { return y0(getY(d,i)) }) .attr('r', function(d,i) { return Math.sqrt(z(getSize(d,i))/Math.PI) }); points.exit().remove(); groups.exit().selectAll('path.nv-point').transition() .attr('cx', function(d,i) { return x(getX(d,i)) }) .attr('cy', function(d,i) { return y(getY(d,i)) }) .remove(); points.each(function(d,i) { d3.select(this) .classed('nv-point', true) .classed('nv-point-' + i, true); }); points.transition() .attr('cx', function(d,i) { return x(getX(d,i)) }) .attr('cy', function(d,i) { return y(getY(d,i)) }) .attr('r', function(d,i) { return Math.sqrt(z(getSize(d,i))/Math.PI) }); } else { var points = groups.selectAll('path.nv-point') .data(function(d) { return d.values }); points.enter().append('path') .attr('transform', function(d,i) { return 'translate(' + x0(getX(d,i)) + ',' + y0(getY(d,i)) + ')' }) .attr('d', d3.svg.symbol() .type(getShape) .size(function(d,i) { return z(getSize(d,i)) }) ); points.exit().remove(); d3.transition(groups.exit().selectAll('path.nv-point')) .attr('transform', function(d,i) { return 'translate(' + x(getX(d,i)) + ',' + y(getY(d,i)) + ')' }) .remove(); points.each(function(d,i) { d3.select(this) .classed('nv-point', true) .classed('nv-point-' + i, true); }); points.transition() .attr('transform', function(d,i) { //nv.log(d,i,getX(d,i), x(getX(d,i))); return 'translate(' + x(getX(d,i)) + ',' + y(getY(d,i)) + ')' }) .attr('d', d3.svg.symbol() .type(getShape) .size(function(d,i) { return z(getSize(d,i)) }) ); } // Delay updating the invisible interactive layer for smoother animation clearTimeout(timeoutID); // stop repeat calls to updateInteractiveLayer timeoutID = setTimeout(updateInteractiveLayer, 300); //updateInteractiveLayer(); //store old scales for use in transitions on update x0 = x.copy(); y0 = y.copy(); z0 = z.copy(); }); return chart; } //============================================================ // Event Handling/Dispatching (out of chart's scope) //------------------------------------------------------------ dispatch.on('elementMouseover.point', function(d) { if (interactive) d3.select('.nv-chart-' + id + ' .nv-series-' + d.seriesIndex + ' .nv-point-' + d.pointIndex) .classed('hover', true); }); dispatch.on('elementMouseout.point', function(d) { if (interactive) d3.select('.nv-chart-' + id + ' .nv-series-' + d.seriesIndex + ' .nv-point-' + d.pointIndex) .classed('hover', false); }); //============================================================ //============================================================ // Expose Public Variables //------------------------------------------------------------ chart.dispatch = dispatch; chart.x = function(_) { if (!arguments.length) return getX; getX = d3.functor(_); return chart; }; chart.y = function(_) { if (!arguments.length) return getY; getY = d3.functor(_); return chart; }; chart.size = function(_) { if (!arguments.length) return getSize; getSize = d3.functor(_); return chart; }; chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.xScale = function(_) { if (!arguments.length) return x; x = _; return chart; }; chart.yScale = function(_) { if (!arguments.length) return y; y = _; return chart; }; chart.zScale = function(_) { if (!arguments.length) return z; z = _; return chart; }; chart.xDomain = function(_) { if (!arguments.length) return xDomain; xDomain = _; return chart; }; chart.yDomain = function(_) { if (!arguments.length) return yDomain; yDomain = _; return chart; }; chart.sizeDomain = function(_) { if (!arguments.length) return sizeDomain; sizeDomain = _; return chart; }; chart.sizeRange = function(_) { if (!arguments.length) return sizeRange; sizeRange = _; return chart; }; chart.forceX = function(_) { if (!arguments.length) return forceX; forceX = _; return chart; }; chart.forceY = function(_) { if (!arguments.length) return forceY; forceY = _; return chart; }; chart.forceSize = function(_) { if (!arguments.length) return forceSize; forceSize = _; return chart; }; chart.interactive = function(_) { if (!arguments.length) return interactive; interactive = _; return chart; }; chart.pointKey = function(_) { if (!arguments.length) return pointKey; pointKey = _; return chart; }; chart.pointActive = function(_) { if (!arguments.length) return pointActive; pointActive = _; return chart; }; chart.padData = function(_) { if (!arguments.length) return padData; padData = _; return chart; }; chart.padDataOuter = function(_) { if (!arguments.length) return padDataOuter; padDataOuter = _; return chart; }; chart.clipEdge = function(_) { if (!arguments.length) return clipEdge; clipEdge = _; return chart; }; chart.clipVoronoi= function(_) { if (!arguments.length) return clipVoronoi; clipVoronoi = _; return chart; }; chart.useVoronoi= function(_) { if (!arguments.length) return useVoronoi; useVoronoi = _; if (useVoronoi === false) { clipVoronoi = false; } return chart; }; chart.clipRadius = function(_) { if (!arguments.length) return clipRadius; clipRadius = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); return chart; }; chart.shape = function(_) { if (!arguments.length) return getShape; getShape = _; return chart; }; chart.onlyCircles = function(_) { if (!arguments.length) return onlyCircles; onlyCircles = _; return chart; }; chart.id = function(_) { if (!arguments.length) return id; id = _; return chart; }; chart.singlePoint = function(_) { if (!arguments.length) return singlePoint; singlePoint = _; return chart; }; //============================================================ return chart; } nv.models.scatterChart = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var scatter = nv.models.scatter() , xAxis = nv.models.axis() , yAxis = nv.models.axis() , legend = nv.models.legend() , controls = nv.models.legend() , distX = nv.models.distribution() , distY = nv.models.distribution() ; var margin = {top: 30, right: 20, bottom: 50, left: 75} , width = null , height = null , color = nv.utils.defaultColor() , x = d3.fisheye ? d3.fisheye.scale(d3.scale.linear).distortion(0) : scatter.xScale() , y = d3.fisheye ? d3.fisheye.scale(d3.scale.linear).distortion(0) : scatter.yScale() , xPadding = 0 , yPadding = 0 , showDistX = false , showDistY = false , showLegend = true , showControls = !!d3.fisheye , fisheye = 0 , pauseFisheye = false , tooltips = true , tooltipX = function(key, x, y) { return '<strong>' + x + '</strong>' } , tooltipY = function(key, x, y) { return '<strong>' + y + '</strong>' } //, tooltip = function(key, x, y) { return '<h3>' + key + '</h3>' } , tooltip = null , state = {} , defaultState = null , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState') , noData = "No Data Available." ; scatter .xScale(x) .yScale(y) ; xAxis .orient('bottom') .tickPadding(10) ; yAxis .orient('left') .tickPadding(10) ; distX .axis('x') ; distY .axis('y') ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var x0, y0; var showTooltip = function(e, offsetElement) { //TODO: make tooltip style an option between single or dual on axes (maybe on all charts with axes?) var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), top = e.pos[1] + ( offsetElement.offsetTop || 0), leftX = e.pos[0] + ( offsetElement.offsetLeft || 0 ), topX = y.range()[0] + margin.top + ( offsetElement.offsetTop || 0), leftY = x.range()[0] + margin.left + ( offsetElement.offsetLeft || 0 ), topY = e.pos[1] + ( offsetElement.offsetTop || 0), xVal = xAxis.tickFormat()(scatter.x()(e.point, e.pointIndex)), yVal = yAxis.tickFormat()(scatter.y()(e.point, e.pointIndex)); if( tooltipX != null ) nv.tooltip.show([leftX, topX], tooltipX(e.series.key, xVal, yVal, e, chart), 'n', 1, offsetElement, 'x-nvtooltip'); if( tooltipY != null ) nv.tooltip.show([leftY, topY], tooltipY(e.series.key, xVal, yVal, e, chart), 'e', 1, offsetElement, 'y-nvtooltip'); if( tooltip != null ) nv.tooltip.show([left, top], tooltip(e.series.key, xVal, yVal, e, chart), e.value < 0 ? 'n' : 's', null, offsetElement); }; var controlsData = [ { key: 'Magnify', disabled: true } ]; //============================================================ function chart(selection) { selection.each(function(data) { var container = d3.select(this), that = this; var availableWidth = (width || parseInt(container.style('width')) || 960) - margin.left - margin.right, availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; chart.update = function() { container.transition().call(chart); }; // chart.container = this; //set state.disabled state.disabled = data.map(function(d) { return !!d.disabled }); if (!defaultState) { var key; defaultState = {}; for (key in state) { if (state[key] instanceof Array) defaultState[key] = state[key].slice(0); else defaultState[key] = state[key]; } } //------------------------------------------------------------ // Display noData message if there's nothing to show. if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) { var noDataText = container.selectAll('.nv-noData').data([noData]); noDataText.enter().append('text') .attr('class', 'nvd3 nv-noData') .attr('dy', '-.7em') .style('text-anchor', 'middle'); noDataText .attr('x', margin.left + availableWidth / 2) .attr('y', margin.top + availableHeight / 2) .text(function(d) { return d }); return chart; } else { container.selectAll('.nv-noData').remove(); } //------------------------------------------------------------ //------------------------------------------------------------ // Setup Scales x0 = x0 || x; y0 = y0 || y; //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-scatterChart').data([data]); var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-scatterChart nv-chart-' + scatter.id()); var gEnter = wrapEnter.append('g'); var g = wrap.select('g'); // background for pointer events gEnter.append('rect').attr('class', 'nvd3 nv-background'); gEnter.append('g').attr('class', 'nv-x nv-axis'); gEnter.append('g').attr('class', 'nv-y nv-axis'); gEnter.append('g').attr('class', 'nv-scatterWrap'); gEnter.append('g').attr('class', 'nv-distWrap'); gEnter.append('g').attr('class', 'nv-legendWrap'); gEnter.append('g').attr('class', 'nv-controlsWrap'); //------------------------------------------------------------ //------------------------------------------------------------ // Legend if (showLegend) { legend.width( availableWidth / 2 ); wrap.select('.nv-legendWrap') .datum(data) .call(legend); if ( margin.top != legend.height()) { margin.top = legend.height(); availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; } wrap.select('.nv-legendWrap') .attr('transform', 'translate(' + (availableWidth / 2) + ',' + (-margin.top) +')'); } //------------------------------------------------------------ //------------------------------------------------------------ // Controls if (showControls) { controls.width(180).color(['#444']); g.select('.nv-controlsWrap') .datum(controlsData) .attr('transform', 'translate(0,' + (-margin.top) +')') .call(controls); } //------------------------------------------------------------ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ // Main Chart Component(s) scatter .width(availableWidth) .height(availableHeight) .color(data.map(function(d,i) { return d.color || color(d, i); }).filter(function(d,i) { return !data[i].disabled })) .xDomain(null) .yDomain(null) wrap.select('.nv-scatterWrap') .datum(data.filter(function(d) { return !d.disabled })) .call(scatter); //Adjust for x and y padding if (xPadding) { var xRange = x.domain()[1] - x.domain()[0]; scatter.xDomain([x.domain()[0] - (xPadding * xRange), x.domain()[1] + (xPadding * xRange)]); } if (yPadding) { var yRange = y.domain()[1] - y.domain()[0]; scatter.yDomain([y.domain()[0] - (yPadding * yRange), y.domain()[1] + (yPadding * yRange)]); } wrap.select('.nv-scatterWrap') .datum(data.filter(function(d) { return !d.disabled })) .call(scatter); //------------------------------------------------------------ //------------------------------------------------------------ // Setup Axes xAxis .scale(x) .ticks( xAxis.ticks() && xAxis.ticks().length ? xAxis.ticks() : availableWidth / 100 ) .tickSize( -availableHeight , 0); g.select('.nv-x.nv-axis') .attr('transform', 'translate(0,' + y.range()[0] + ')') .call(xAxis); yAxis .scale(y) .ticks( yAxis.ticks() && yAxis.ticks().length ? yAxis.ticks() : availableHeight / 36 ) .tickSize( -availableWidth, 0); g.select('.nv-y.nv-axis') .call(yAxis); if (showDistX) { distX .getData(scatter.x()) .scale(x) .width(availableWidth) .color(data.map(function(d,i) { return d.color || color(d, i); }).filter(function(d,i) { return !data[i].disabled })); gEnter.select('.nv-distWrap').append('g') .attr('class', 'nv-distributionX'); g.select('.nv-distributionX') .attr('transform', 'translate(0,' + y.range()[0] + ')') .datum(data.filter(function(d) { return !d.disabled })) .call(distX); } if (showDistY) { distY .getData(scatter.y()) .scale(y) .width(availableHeight) .color(data.map(function(d,i) { return d.color || color(d, i); }).filter(function(d,i) { return !data[i].disabled })); gEnter.select('.nv-distWrap').append('g') .attr('class', 'nv-distributionY'); g.select('.nv-distributionY') .attr('transform', 'translate(-' + distY.size() + ',0)') .datum(data.filter(function(d) { return !d.disabled })) .call(distY); } //------------------------------------------------------------ if (d3.fisheye) { g.select('.nv-background') .attr('width', availableWidth) .attr('height', availableHeight); g.select('.nv-background').on('mousemove', updateFisheye); g.select('.nv-background').on('click', function() { pauseFisheye = !pauseFisheye;}); scatter.dispatch.on('elementClick.freezeFisheye', function() { pauseFisheye = !pauseFisheye; }); } function updateFisheye() { if (pauseFisheye) { g.select('.nv-point-paths').style('pointer-events', 'all'); return false; } g.select('.nv-point-paths').style('pointer-events', 'none' ); var mouse = d3.mouse(this); x.distortion(fisheye).focus(mouse[0]); y.distortion(fisheye).focus(mouse[1]); g.select('.nv-scatterWrap') .call(scatter); g.select('.nv-x.nv-axis').call(xAxis); g.select('.nv-y.nv-axis').call(yAxis); g.select('.nv-distributionX') .datum(data.filter(function(d) { return !d.disabled })) .call(distX); g.select('.nv-distributionY') .datum(data.filter(function(d) { return !d.disabled })) .call(distY); } //============================================================ // Event Handling/Dispatching (in chart's scope) //------------------------------------------------------------ controls.dispatch.on('legendClick', function(d,i) { d.disabled = !d.disabled; fisheye = d.disabled ? 0 : 2.5; g.select('.nv-background') .style('pointer-events', d.disabled ? 'none' : 'all'); g.select('.nv-point-paths').style('pointer-events', d.disabled ? 'all' : 'none' ); if (d.disabled) { x.distortion(fisheye).focus(0); y.distortion(fisheye).focus(0); g.select('.nv-scatterWrap').call(scatter); g.select('.nv-x.nv-axis').call(xAxis); g.select('.nv-y.nv-axis').call(yAxis); } else { pauseFisheye = false; } chart.update(); }); legend.dispatch.on('legendClick', function(d,i, that) { d.disabled = !d.disabled; if (!data.filter(function(d) { return !d.disabled }).length) { data.map(function(d) { d.disabled = false; wrap.selectAll('.nv-series').classed('disabled', false); return d; }); } state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); chart.update(); }); legend.dispatch.on('legendDblclick', function(d) { //Double clicking should always enable current series, and disabled all others. data.forEach(function(d) { d.disabled = true; }); d.disabled = false; state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); chart.update(); }); /* legend.dispatch.on('legendMouseover', function(d, i) { d.hover = true; chart(selection); }); legend.dispatch.on('legendMouseout', function(d, i) { d.hover = false; chart(selection); }); */ scatter.dispatch.on('elementMouseover.tooltip', function(e) { d3.select('.nv-chart-' + scatter.id() + ' .nv-series-' + e.seriesIndex + ' .nv-distx-' + e.pointIndex) .attr('y1', function(d,i) { return e.pos[1] - availableHeight;}); d3.select('.nv-chart-' + scatter.id() + ' .nv-series-' + e.seriesIndex + ' .nv-disty-' + e.pointIndex) .attr('x2', e.pos[0] + distX.size()); e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); dispatch.on('tooltipShow', function(e) { if (tooltips) showTooltip(e, that.parentNode); }); // Update chart from a state object passed to event handler dispatch.on('changeState', function(e) { if (typeof e.disabled !== 'undefined') { data.forEach(function(series,i) { series.disabled = e.disabled[i]; }); state.disabled = e.disabled; } chart.update(); }); //============================================================ //store old scales for use in transitions on update x0 = x.copy(); y0 = y.copy(); }); return chart; } //============================================================ // Event Handling/Dispatching (out of chart's scope) //------------------------------------------------------------ scatter.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); d3.select('.nv-chart-' + scatter.id() + ' .nv-series-' + e.seriesIndex + ' .nv-distx-' + e.pointIndex) .attr('y1', 0); d3.select('.nv-chart-' + scatter.id() + ' .nv-series-' + e.seriesIndex + ' .nv-disty-' + e.pointIndex) .attr('x2', distY.size()); }); dispatch.on('tooltipHide', function() { if (tooltips) nv.tooltip.cleanup(); }); //============================================================ //============================================================ // Expose Public Variables //------------------------------------------------------------ // expose chart's sub-components chart.dispatch = dispatch; chart.scatter = scatter; chart.legend = legend; chart.controls = controls; chart.xAxis = xAxis; chart.yAxis = yAxis; chart.distX = distX; chart.distY = distY; d3.rebind(chart, scatter, 'id', 'interactive', 'pointActive', 'x', 'y', 'shape', 'size', 'xScale', 'yScale', 'zScale', 'xDomain', 'yDomain', 'sizeDomain', 'sizeRange', 'forceX', 'forceY', 'forceSize', 'clipVoronoi', 'clipRadius', 'useVoronoi'); chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); legend.color(color); distX.color(color); distY.color(color); return chart; }; chart.showDistX = function(_) { if (!arguments.length) return showDistX; showDistX = _; return chart; }; chart.showDistY = function(_) { if (!arguments.length) return showDistY; showDistY = _; return chart; }; chart.showControls = function(_) { if (!arguments.length) return showControls; showControls = _; return chart; }; chart.showLegend = function(_) { if (!arguments.length) return showLegend; showLegend = _; return chart; }; chart.fisheye = function(_) { if (!arguments.length) return fisheye; fisheye = _; return chart; }; chart.xPadding = function(_) { if (!arguments.length) return xPadding; xPadding = _; return chart; }; chart.yPadding = function(_) { if (!arguments.length) return yPadding; yPadding = _; return chart; }; chart.tooltips = function(_) { if (!arguments.length) return tooltips; tooltips = _; return chart; }; chart.tooltipContent = function(_) { if (!arguments.length) return tooltip; tooltip = _; return chart; }; chart.tooltipXContent = function(_) { if (!arguments.length) return tooltipX; tooltipX = _; return chart; }; chart.tooltipYContent = function(_) { if (!arguments.length) return tooltipY; tooltipY = _; return chart; }; chart.state = function(_) { if (!arguments.length) return state; state = _; return chart; }; chart.defaultState = function(_) { if (!arguments.length) return defaultState; defaultState = _; return chart; }; chart.noData = function(_) { if (!arguments.length) return noData; noData = _; return chart; }; //============================================================ return chart; } nv.models.scatterPlusLineChart = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var scatter = nv.models.scatter() , xAxis = nv.models.axis() , yAxis = nv.models.axis() , legend = nv.models.legend() , controls = nv.models.legend() , distX = nv.models.distribution() , distY = nv.models.distribution() ; var margin = {top: 30, right: 20, bottom: 50, left: 75} , width = null , height = null , color = nv.utils.defaultColor() , x = d3.fisheye ? d3.fisheye.scale(d3.scale.linear).distortion(0) : scatter.xScale() , y = d3.fisheye ? d3.fisheye.scale(d3.scale.linear).distortion(0) : scatter.yScale() , showDistX = false , showDistY = false , showLegend = true , showControls = !!d3.fisheye , fisheye = 0 , pauseFisheye = false , tooltips = true , tooltipX = function(key, x, y) { return '<strong>' + x + '</strong>' } , tooltipY = function(key, x, y) { return '<strong>' + y + '</strong>' } , tooltip = function(key, x, y, date) { return '<h3>' + key + '</h3>' + '<p>' + date + '</p>' } //, tooltip = null , state = {} , defaultState = null , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState') , noData = "No Data Available." ; scatter .xScale(x) .yScale(y) ; xAxis .orient('bottom') .tickPadding(10) ; yAxis .orient('left') .tickPadding(10) ; distX .axis('x') ; distY .axis('y') ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var x0, y0; var showTooltip = function(e, offsetElement) { //TODO: make tooltip style an option between single or dual on axes (maybe on all charts with axes?) var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), top = e.pos[1] + ( offsetElement.offsetTop || 0), leftX = e.pos[0] + ( offsetElement.offsetLeft || 0 ), topX = y.range()[0] + margin.top + ( offsetElement.offsetTop || 0), leftY = x.range()[0] + margin.left + ( offsetElement.offsetLeft || 0 ), topY = e.pos[1] + ( offsetElement.offsetTop || 0), xVal = xAxis.tickFormat()(scatter.x()(e.point, e.pointIndex)), yVal = yAxis.tickFormat()(scatter.y()(e.point, e.pointIndex)); if( tooltipX != null ) nv.tooltip.show([leftX, topX], tooltipX(e.series.key, xVal, yVal, e, chart), 'n', 1, offsetElement, 'x-nvtooltip'); if( tooltipY != null ) nv.tooltip.show([leftY, topY], tooltipY(e.series.key, xVal, yVal, e, chart), 'e', 1, offsetElement, 'y-nvtooltip'); if( tooltip != null ) nv.tooltip.show([left, top], tooltip(e.series.key, xVal, yVal, e.point.tooltip, e, chart), e.value < 0 ? 'n' : 's', null, offsetElement); }; var controlsData = [ { key: 'Magnify', disabled: true } ]; //============================================================ function chart(selection) { selection.each(function(data) { var container = d3.select(this), that = this; var availableWidth = (width || parseInt(container.style('width')) || 960) - margin.left - margin.right, availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; chart.update = function() { container.transition().call(chart); }; chart.container = this; //set state.disabled state.disabled = data.map(function(d) { return !!d.disabled }); if (!defaultState) { var key; defaultState = {}; for (key in state) { if (state[key] instanceof Array) defaultState[key] = state[key].slice(0); else defaultState[key] = state[key]; } } //------------------------------------------------------------ // Display noData message if there's nothing to show. if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) { var noDataText = container.selectAll('.nv-noData').data([noData]); noDataText.enter().append('text') .attr('class', 'nvd3 nv-noData') .attr('dy', '-.7em') .style('text-anchor', 'middle'); noDataText .attr('x', margin.left + availableWidth / 2) .attr('y', margin.top + availableHeight / 2) .text(function(d) { return d }); return chart; } else { container.selectAll('.nv-noData').remove(); } //------------------------------------------------------------ //------------------------------------------------------------ // Setup Scales x = scatter.xScale(); y = scatter.yScale(); x0 = x0 || x; y0 = y0 || y; //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-scatterChart').data([data]); var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-scatterChart nv-chart-' + scatter.id()); var gEnter = wrapEnter.append('g'); var g = wrap.select('g') // background for pointer events gEnter.append('rect').attr('class', 'nvd3 nv-background') gEnter.append('g').attr('class', 'nv-x nv-axis'); gEnter.append('g').attr('class', 'nv-y nv-axis'); gEnter.append('g').attr('class', 'nv-scatterWrap'); gEnter.append('g').attr('class', 'nv-regressionLinesWrap'); gEnter.append('g').attr('class', 'nv-distWrap'); gEnter.append('g').attr('class', 'nv-legendWrap'); gEnter.append('g').attr('class', 'nv-controlsWrap'); wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ //------------------------------------------------------------ // Legend if (showLegend) { legend.width( availableWidth / 2 ); wrap.select('.nv-legendWrap') .datum(data) .call(legend); if ( margin.top != legend.height()) { margin.top = legend.height(); availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; } wrap.select('.nv-legendWrap') .attr('transform', 'translate(' + (availableWidth / 2) + ',' + (-margin.top) +')'); } //------------------------------------------------------------ //------------------------------------------------------------ // Controls if (showControls) { controls.width(180).color(['#444']); g.select('.nv-controlsWrap') .datum(controlsData) .attr('transform', 'translate(0,' + (-margin.top) +')') .call(controls); } //------------------------------------------------------------ //------------------------------------------------------------ // Main Chart Component(s) scatter .width(availableWidth) .height(availableHeight) .color(data.map(function(d,i) { return d.color || color(d, i); }).filter(function(d,i) { return !data[i].disabled })) wrap.select('.nv-scatterWrap') .datum(data.filter(function(d) { return !d.disabled })) .call(scatter); wrap.select('.nv-regressionLinesWrap') .attr('clip-path', 'url(#nv-edge-clip-' + scatter.id() + ')'); var regWrap = wrap.select('.nv-regressionLinesWrap').selectAll('.nv-regLines') .data(function(d) { return d }); var reglines = regWrap.enter() .append('g').attr('class', 'nv-regLines') .append('line').attr('class', 'nv-regLine') .style('stroke-opacity', 0); //d3.transition(regWrap.selectAll('.nv-regLines line')) regWrap.selectAll('.nv-regLines line') .attr('x1', x.range()[0]) .attr('x2', x.range()[1]) .attr('y1', function(d,i) { return y(x.domain()[0] * d.slope + d.intercept) }) .attr('y2', function(d,i) { return y(x.domain()[1] * d.slope + d.intercept) }) .style('stroke', function(d,i,j) { return color(d,j) }) .style('stroke-opacity', function(d,i) { return (d.disabled || typeof d.slope === 'undefined' || typeof d.intercept === 'undefined') ? 0 : 1 }); //------------------------------------------------------------ //------------------------------------------------------------ // Setup Axes xAxis .scale(x) .ticks( xAxis.ticks() ? xAxis.ticks() : availableWidth / 100 ) .tickSize( -availableHeight , 0); g.select('.nv-x.nv-axis') .attr('transform', 'translate(0,' + y.range()[0] + ')') .call(xAxis); yAxis .scale(y) .ticks( yAxis.ticks() ? yAxis.ticks() : availableHeight / 36 ) .tickSize( -availableWidth, 0); g.select('.nv-y.nv-axis') .call(yAxis); if (showDistX) { distX .getData(scatter.x()) .scale(x) .width(availableWidth) .color(data.map(function(d,i) { return d.color || color(d, i); }).filter(function(d,i) { return !data[i].disabled })); gEnter.select('.nv-distWrap').append('g') .attr('class', 'nv-distributionX'); g.select('.nv-distributionX') .attr('transform', 'translate(0,' + y.range()[0] + ')') .datum(data.filter(function(d) { return !d.disabled })) .call(distX); } if (showDistY) { distY .getData(scatter.y()) .scale(y) .width(availableHeight) .color(data.map(function(d,i) { return d.color || color(d, i); }).filter(function(d,i) { return !data[i].disabled })); gEnter.select('.nv-distWrap').append('g') .attr('class', 'nv-distributionY'); g.select('.nv-distributionY') .attr('transform', 'translate(-' + distY.size() + ',0)') .datum(data.filter(function(d) { return !d.disabled })) .call(distY); } //------------------------------------------------------------ if (d3.fisheye) { g.select('.nv-background') .attr('width', availableWidth) .attr('height', availableHeight); g.select('.nv-background').on('mousemove', updateFisheye); g.select('.nv-background').on('click', function() { pauseFisheye = !pauseFisheye;}); scatter.dispatch.on('elementClick.freezeFisheye', function() { pauseFisheye = !pauseFisheye; }); } function updateFisheye() { if (pauseFisheye) { g.select('.nv-point-paths').style('pointer-events', 'all'); return false; } g.select('.nv-point-paths').style('pointer-events', 'none' ); var mouse = d3.mouse(this); x.distortion(fisheye).focus(mouse[0]); y.distortion(fisheye).focus(mouse[1]); g.select('.nv-scatterWrap') .datum(data.filter(function(d) { return !d.disabled })) .call(scatter); g.select('.nv-x.nv-axis').call(xAxis); g.select('.nv-y.nv-axis').call(yAxis); g.select('.nv-distributionX') .datum(data.filter(function(d) { return !d.disabled })) .call(distX); g.select('.nv-distributionY') .datum(data.filter(function(d) { return !d.disabled })) .call(distY); } //============================================================ // Event Handling/Dispatching (in chart's scope) //------------------------------------------------------------ controls.dispatch.on('legendClick', function(d,i) { d.disabled = !d.disabled; fisheye = d.disabled ? 0 : 2.5; g.select('.nv-background') .style('pointer-events', d.disabled ? 'none' : 'all'); g.select('.nv-point-paths').style('pointer-events', d.disabled ? 'all' : 'none' ); if (d.disabled) { x.distortion(fisheye).focus(0); y.distortion(fisheye).focus(0); g.select('.nv-scatterWrap').call(scatter); g.select('.nv-x.nv-axis').call(xAxis); g.select('.nv-y.nv-axis').call(yAxis); } else { pauseFisheye = false; } chart.update(); }); legend.dispatch.on('legendClick', function(d,i, that) { d.disabled = !d.disabled; if (!data.filter(function(d) { return !d.disabled }).length) { data.map(function(d) { d.disabled = false; wrap.selectAll('.nv-series').classed('disabled', false); return d; }); } state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); chart.update(); }); legend.dispatch.on('legendDblclick', function(d) { //Double clicking should always enable current series, and disabled all others. data.forEach(function(d) { d.disabled = true; }); d.disabled = false; state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); chart.update(); }); /* legend.dispatch.on('legendMouseover', function(d, i) { d.hover = true; chart(selection); }); legend.dispatch.on('legendMouseout', function(d, i) { d.hover = false; chart(selection); }); */ scatter.dispatch.on('elementMouseover.tooltip', function(e) { d3.select('.nv-chart-' + scatter.id() + ' .nv-series-' + e.seriesIndex + ' .nv-distx-' + e.pointIndex) .attr('y1', e.pos[1] - availableHeight); d3.select('.nv-chart-' + scatter.id() + ' .nv-series-' + e.seriesIndex + ' .nv-disty-' + e.pointIndex) .attr('x2', e.pos[0] + distX.size()); e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); dispatch.on('tooltipShow', function(e) { if (tooltips) showTooltip(e, that.parentNode); }); // Update chart from a state object passed to event handler dispatch.on('changeState', function(e) { if (typeof e.disabled !== 'undefined') { data.forEach(function(series,i) { series.disabled = e.disabled[i]; }); state.disabled = e.disabled; } chart.update(); }); //============================================================ //store old scales for use in transitions on update x0 = x.copy(); y0 = y.copy(); }); return chart; } //============================================================ // Event Handling/Dispatching (out of chart's scope) //------------------------------------------------------------ scatter.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); d3.select('.nv-chart-' + scatter.id() + ' .nv-series-' + e.seriesIndex + ' .nv-distx-' + e.pointIndex) .attr('y1', 0); d3.select('.nv-chart-' + scatter.id() + ' .nv-series-' + e.seriesIndex + ' .nv-disty-' + e.pointIndex) .attr('x2', distY.size()); }); dispatch.on('tooltipHide', function() { if (tooltips) nv.tooltip.cleanup(); }); //============================================================ //============================================================ // Expose Public Variables //------------------------------------------------------------ // expose chart's sub-components chart.dispatch = dispatch; chart.scatter = scatter; chart.legend = legend; chart.controls = controls; chart.xAxis = xAxis; chart.yAxis = yAxis; chart.distX = distX; chart.distY = distY; d3.rebind(chart, scatter, 'id', 'interactive', 'pointActive', 'x', 'y', 'shape', 'size', 'xScale', 'yScale', 'zScale', 'xDomain', 'yDomain', 'sizeDomain', 'sizeRange', 'forceX', 'forceY', 'forceSize', 'clipVoronoi', 'clipRadius', 'useVoronoi'); chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); legend.color(color); distX.color(color); distY.color(color); return chart; }; chart.showDistX = function(_) { if (!arguments.length) return showDistX; showDistX = _; return chart; }; chart.showDistY = function(_) { if (!arguments.length) return showDistY; showDistY = _; return chart; }; chart.showControls = function(_) { if (!arguments.length) return showControls; showControls = _; return chart; }; chart.showLegend = function(_) { if (!arguments.length) return showLegend; showLegend = _; return chart; }; chart.fisheye = function(_) { if (!arguments.length) return fisheye; fisheye = _; return chart; }; chart.tooltips = function(_) { if (!arguments.length) return tooltips; tooltips = _; return chart; }; chart.tooltipContent = function(_) { if (!arguments.length) return tooltip; tooltip = _; return chart; }; chart.tooltipXContent = function(_) { if (!arguments.length) return tooltipX; tooltipX = _; return chart; }; chart.tooltipYContent = function(_) { if (!arguments.length) return tooltipY; tooltipY = _; return chart; }; chart.state = function(_) { if (!arguments.length) return state; state = _; return chart; }; chart.defaultState = function(_) { if (!arguments.length) return defaultState; defaultState = _; return chart; }; chart.noData = function(_) { if (!arguments.length) return noData; noData = _; return chart; }; //============================================================ return chart; } nv.models.sparkline = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var margin = {top: 2, right: 0, bottom: 2, left: 0} , width = 400 , height = 32 , animate = true , x = d3.scale.linear() , y = d3.scale.linear() , getX = function(d) { return d.x } , getY = function(d) { return d.y } , color = nv.utils.getColor(['#000']) , xDomain , yDomain ; //============================================================ function chart(selection) { selection.each(function(data) { var availableWidth = width - margin.left - margin.right, availableHeight = height - margin.top - margin.bottom, container = d3.select(this); //------------------------------------------------------------ // Setup Scales x .domain(xDomain || d3.extent(data, getX )) .range([0, availableWidth]); y .domain(yDomain || d3.extent(data, getY )) .range([availableHeight, 0]); //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-sparkline').data([data]); var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-sparkline'); var gEnter = wrapEnter.append('g'); var g = wrap.select('g'); wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')') //------------------------------------------------------------ var paths = wrap.selectAll('path') .data(function(d) { return [d] }); paths.enter().append('path'); paths.exit().remove(); paths .style('stroke', function(d,i) { return d.color || color(d, i) }) .attr('d', d3.svg.line() .x(function(d,i) { return x(getX(d,i)) }) .y(function(d,i) { return y(getY(d,i)) }) ); // TODO: Add CURRENT data point (Need Min, Mac, Current / Most recent) var points = wrap.selectAll('circle.nv-point') .data(function(data) { var yValues = data.map(function(d, i) { return getY(d,i); }); function pointIndex(index) { if (index != -1) { var result = data[index]; result.pointIndex = index; return result; } else { return null; } } var maxPoint = pointIndex(yValues.lastIndexOf(y.domain()[1])), minPoint = pointIndex(yValues.indexOf(y.domain()[0])), currentPoint = pointIndex(yValues.length - 1); return [minPoint, maxPoint, currentPoint].filter(function (d) {return d != null;}); }); points.enter().append('circle'); points.exit().remove(); points .attr('cx', function(d,i) { return x(getX(d,d.pointIndex)) }) .attr('cy', function(d,i) { return y(getY(d,d.pointIndex)) }) .attr('r', 2) .attr('class', function(d,i) { return getX(d, d.pointIndex) == x.domain()[1] ? 'nv-point nv-currentValue' : getY(d, d.pointIndex) == y.domain()[0] ? 'nv-point nv-minValue' : 'nv-point nv-maxValue' }); }); return chart; } //============================================================ // Expose Public Variables //------------------------------------------------------------ chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.x = function(_) { if (!arguments.length) return getX; getX = d3.functor(_); return chart; }; chart.y = function(_) { if (!arguments.length) return getY; getY = d3.functor(_); return chart; }; chart.xScale = function(_) { if (!arguments.length) return x; x = _; return chart; }; chart.yScale = function(_) { if (!arguments.length) return y; y = _; return chart; }; chart.xDomain = function(_) { if (!arguments.length) return xDomain; xDomain = _; return chart; }; chart.yDomain = function(_) { if (!arguments.length) return yDomain; yDomain = _; return chart; }; chart.animate = function(_) { if (!arguments.length) return animate; animate = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); return chart; }; //============================================================ return chart; } nv.models.sparklinePlus = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var sparkline = nv.models.sparkline(); var margin = {top: 15, right: 100, bottom: 10, left: 50} , width = null , height = null , x , y , index = [] , paused = false , xTickFormat = d3.format(',r') , yTickFormat = d3.format(',.2f') , showValue = true , alignValue = true , rightAlignValue = false , noData = "No Data Available." ; //============================================================ function chart(selection) { selection.each(function(data) { var container = d3.select(this); var availableWidth = (width || parseInt(container.style('width')) || 960) - margin.left - margin.right, availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; chart.update = function() { chart(selection) }; chart.container = this; //------------------------------------------------------------ // Display No Data message if there's nothing to show. if (!data || !data.length) { var noDataText = container.selectAll('.nv-noData').data([noData]); noDataText.enter().append('text') .attr('class', 'nvd3 nv-noData') .attr('dy', '-.7em') .style('text-anchor', 'middle'); noDataText .attr('x', margin.left + availableWidth / 2) .attr('y', margin.top + availableHeight / 2) .text(function(d) { return d }); return chart; } else { container.selectAll('.nv-noData').remove(); } var currentValue = sparkline.y()(data[data.length-1], data.length-1); //------------------------------------------------------------ //------------------------------------------------------------ // Setup Scales x = sparkline.xScale(); y = sparkline.yScale(); //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-sparklineplus').data([data]); var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-sparklineplus'); var gEnter = wrapEnter.append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-sparklineWrap'); gEnter.append('g').attr('class', 'nv-valueWrap'); gEnter.append('g').attr('class', 'nv-hoverArea'); wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ //------------------------------------------------------------ // Main Chart Component(s) var sparklineWrap = g.select('.nv-sparklineWrap'); sparkline .width(availableWidth) .height(availableHeight); sparklineWrap .call(sparkline); //------------------------------------------------------------ var valueWrap = g.select('.nv-valueWrap'); var value = valueWrap.selectAll('.nv-currentValue') .data([currentValue]); value.enter().append('text').attr('class', 'nv-currentValue') .attr('dx', rightAlignValue ? -8 : 8) .attr('dy', '.9em') .style('text-anchor', rightAlignValue ? 'end' : 'start'); value .attr('x', availableWidth + (rightAlignValue ? margin.right : 0)) .attr('y', alignValue ? function(d) { return y(d) } : 0) .style('fill', sparkline.color()(data[data.length-1], data.length-1)) .text(yTickFormat(currentValue)); gEnter.select('.nv-hoverArea').append('rect') .on('mousemove', sparklineHover) .on('click', function() { paused = !paused }) .on('mouseout', function() { index = []; updateValueLine(); }); //.on('mouseout', function() { index = null; updateValueLine(); }); g.select('.nv-hoverArea rect') .attr('transform', function(d) { return 'translate(' + -margin.left + ',' + -margin.top + ')' }) .attr('width', availableWidth + margin.left + margin.right) .attr('height', availableHeight + margin.top); function updateValueLine() { //index is currently global (within the chart), may or may not keep it that way if (paused) return; var hoverValue = g.selectAll('.nv-hoverValue').data(index) var hoverEnter = hoverValue.enter() .append('g').attr('class', 'nv-hoverValue') .style('stroke-opacity', 0) .style('fill-opacity', 0); hoverValue.exit() .transition().duration(250) .style('stroke-opacity', 0) .style('fill-opacity', 0) .remove(); hoverValue .attr('transform', function(d) { return 'translate(' + x(sparkline.x()(data[d],d)) + ',0)' }) .transition().duration(250) .style('stroke-opacity', 1) .style('fill-opacity', 1); if (!index.length) return; hoverEnter.append('line') .attr('x1', 0) .attr('y1', -margin.top) .attr('x2', 0) .attr('y2', availableHeight); hoverEnter.append('text').attr('class', 'nv-xValue') .attr('x', -6) .attr('y', -margin.top) .attr('text-anchor', 'end') .attr('dy', '.9em') g.select('.nv-hoverValue .nv-xValue') .text(xTickFormat(sparkline.x()(data[index[0]], index[0]))); hoverEnter.append('text').attr('class', 'nv-yValue') .attr('x', 6) .attr('y', -margin.top) .attr('text-anchor', 'start') .attr('dy', '.9em') g.select('.nv-hoverValue .nv-yValue') .text(yTickFormat(sparkline.y()(data[index[0]], index[0]))); } function sparklineHover() { if (paused) return; var pos = d3.mouse(this)[0] - margin.left; function getClosestIndex(data, x) { var distance = Math.abs(sparkline.x()(data[0], 0) - x); var closestIndex = 0; for (var i = 0; i < data.length; i++){ if (Math.abs(sparkline.x()(data[i], i) - x) < distance) { distance = Math.abs(sparkline.x()(data[i], i) - x); closestIndex = i; } } return closestIndex; } index = [getClosestIndex(data, Math.round(x.invert(pos)))]; updateValueLine(); } }); return chart; } //============================================================ // Expose Public Variables //------------------------------------------------------------ // expose chart's sub-components chart.sparkline = sparkline; d3.rebind(chart, sparkline, 'x', 'y', 'xScale', 'yScale', 'color'); chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.xTickFormat = function(_) { if (!arguments.length) return xTickFormat; xTickFormat = _; return chart; }; chart.yTickFormat = function(_) { if (!arguments.length) return yTickFormat; yTickFormat = _; return chart; }; chart.showValue = function(_) { if (!arguments.length) return showValue; showValue = _; return chart; }; chart.alignValue = function(_) { if (!arguments.length) return alignValue; alignValue = _; return chart; }; chart.rightAlignValue = function(_) { if (!arguments.length) return rightAlignValue; rightAlignValue = _; return chart; }; chart.noData = function(_) { if (!arguments.length) return noData; noData = _; return chart; }; //============================================================ return chart; } nv.models.stackedArea = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var margin = {top: 0, right: 0, bottom: 0, left: 0} , width = 960 , height = 500 , color = nv.utils.defaultColor() // a function that computes the color , id = Math.floor(Math.random() * 100000) //Create semi-unique ID incase user doesn't selet one , getX = function(d) { return d.x } // accessor to get the x value from a data point , getY = function(d) { return d.y } // accessor to get the y value from a data point , style = 'stack' , offset = 'zero' , order = 'default' , interpolate = 'linear' // controls the line interpolation , clipEdge = false // if true, masks lines within x and y scale , x //can be accessed via chart.xScale() , y //can be accessed via chart.yScale() , scatter = nv.models.scatter() , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'areaClick', 'areaMouseover', 'areaMouseout') ; scatter .size(2.2) // default size .sizeDomain([2.2,2.2]) // all the same size by default ; /************************************ * offset: * 'wiggle' (stream) * 'zero' (stacked) * 'expand' (normalize to 100%) * 'silhouette' (simple centered) * * order: * 'inside-out' (stream) * 'default' (input order) ************************************/ //============================================================ function chart(selection) { selection.each(function(data) { var availableWidth = width - margin.left - margin.right, availableHeight = height - margin.top - margin.bottom, container = d3.select(this); //------------------------------------------------------------ // Setup Scales x = scatter.xScale(); y = scatter.yScale(); //------------------------------------------------------------ // Injecting point index into each point because d3.layout.stack().out does not give index // ***Also storing getY(d,i) as stackedY so that it can be set to 0 if series is disabled data = data.map(function(aseries, i) { aseries.values = aseries.values.map(function(d, j) { d.index = j; d.stackedY = aseries.disabled ? 0 : getY(d,j); return d; }) return aseries; }); data = d3.layout.stack() .order(order) .offset(offset) .values(function(d) { return d.values }) //TODO: make values customizeable in EVERY model in this fashion .x(getX) .y(function(d) { return d.stackedY }) .out(function(d, y0, y) { d.display = { y: y, y0: y0 }; }) (data); //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-stackedarea').data([data]); var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-stackedarea'); var defsEnter = wrapEnter.append('defs'); var gEnter = wrapEnter.append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-areaWrap'); gEnter.append('g').attr('class', 'nv-scatterWrap'); wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ scatter .width(availableWidth) .height(availableHeight) .x(getX) .y(function(d) { return d.display.y + d.display.y0 }) .forceY([0]) .color(data.map(function(d,i) { return d.color || color(d, i); }).filter(function(d,i) { return !data[i].disabled })); var scatterWrap = g.select('.nv-scatterWrap') .datum(data.filter(function(d) { return !d.disabled })) //d3.transition(scatterWrap).call(scatter); scatterWrap.call(scatter); defsEnter.append('clipPath') .attr('id', 'nv-edge-clip-' + id) .append('rect'); wrap.select('#nv-edge-clip-' + id + ' rect') .attr('width', availableWidth) .attr('height', availableHeight); g .attr('clip-path', clipEdge ? 'url(#nv-edge-clip-' + id + ')' : ''); var area = d3.svg.area() .x(function(d,i) { return x(getX(d,i)) }) .y0(function(d) { return y(d.display.y0) }) .y1(function(d) { return y(d.display.y + d.display.y0) }) .interpolate(interpolate); var zeroArea = d3.svg.area() .x(function(d,i) { return x(getX(d,i)) }) .y0(function(d) { return y(d.display.y0) }) .y1(function(d) { return y(d.display.y0) }); var path = g.select('.nv-areaWrap').selectAll('path.nv-area') .data(function(d) { return d }); //.data(function(d) { return d }, function(d) { return d.key }); path.enter().append('path').attr('class', function(d,i) { return 'nv-area nv-area-' + i }) .on('mouseover', function(d,i) { d3.select(this).classed('hover', true); dispatch.areaMouseover({ point: d, series: d.key, pos: [d3.event.pageX, d3.event.pageY], seriesIndex: i }); }) .on('mouseout', function(d,i) { d3.select(this).classed('hover', false); dispatch.areaMouseout({ point: d, series: d.key, pos: [d3.event.pageX, d3.event.pageY], seriesIndex: i }); }) .on('click', function(d,i) { d3.select(this).classed('hover', false); dispatch.areaClick({ point: d, series: d.key, pos: [d3.event.pageX, d3.event.pageY], seriesIndex: i }); }) //d3.transition(path.exit()) path.exit() .attr('d', function(d,i) { return zeroArea(d.values,i) }) .remove(); path .style('fill', function(d,i){ return d.color || color(d, i) }) .style('stroke', function(d,i){ return d.color || color(d, i) }); //d3.transition(path) path .attr('d', function(d,i) { return area(d.values,i) }) //============================================================ // Event Handling/Dispatching (in chart's scope) //------------------------------------------------------------ scatter.dispatch.on('elementMouseover.area', function(e) { g.select('.nv-chart-' + id + ' .nv-area-' + e.seriesIndex).classed('hover', true); }); scatter.dispatch.on('elementMouseout.area', function(e) { g.select('.nv-chart-' + id + ' .nv-area-' + e.seriesIndex).classed('hover', false); }); //============================================================ }); return chart; } //============================================================ // Event Handling/Dispatching (out of chart's scope) //------------------------------------------------------------ scatter.dispatch.on('elementClick.area', function(e) { dispatch.areaClick(e); }) scatter.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top], dispatch.tooltipShow(e); }); scatter.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); //============================================================ //============================================================ // Global getters and setters //------------------------------------------------------------ chart.dispatch = dispatch; chart.scatter = scatter; d3.rebind(chart, scatter, 'interactive', 'size', 'xScale', 'yScale', 'zScale', 'xDomain', 'yDomain', 'sizeDomain', 'forceX', 'forceY', 'forceSize', 'clipVoronoi', 'clipRadius'); chart.x = function(_) { if (!arguments.length) return getX; getX = d3.functor(_); return chart; }; chart.y = function(_) { if (!arguments.length) return getY; getY = d3.functor(_); return chart; } chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; }; chart.clipEdge = function(_) { if (!arguments.length) return clipEdge; clipEdge = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); return chart; }; chart.offset = function(_) { if (!arguments.length) return offset; offset = _; return chart; }; chart.order = function(_) { if (!arguments.length) return order; order = _; return chart; }; //shortcut for offset + order chart.style = function(_) { if (!arguments.length) return style; style = _; switch (style) { case 'stack': chart.offset('zero'); chart.order('default'); break; case 'stream': chart.offset('wiggle'); chart.order('inside-out'); break; case 'stream-center': chart.offset('silhouette'); chart.order('inside-out'); break; case 'expand': chart.offset('expand'); chart.order('default'); break; } return chart; }; chart.interpolate = function(_) { if (!arguments.length) return interpolate; interpolate = _; return interpolate; }; //============================================================ return chart; } nv.models.stackedAreaChart = function() { //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var stacked = nv.models.stackedArea() , xAxis = nv.models.axis() , yAxis = nv.models.axis() , legend = nv.models.legend() , controls = nv.models.legend() ; var margin = {top: 30, right: 25, bottom: 50, left: 60} , width = null , height = null , color = nv.utils.defaultColor() // a function that takes in d, i and returns color , showControls = true , showLegend = true , tooltips = true , tooltip = function(key, x, y, e, graph) { return '<h3>' + key + '</h3>' + '<p>' + y + ' on ' + x + '</p>' } , x //can be accessed via chart.xScale() , y //can be accessed via chart.yScale() , yAxisTickFormat = d3.format(',.2f') , state = { style: stacked.style() } , defaultState = null , noData = 'No Data Available.' , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState') , controlWidth = 250 ; xAxis .orient('bottom') .tickPadding(7) ; yAxis .orient('left') ; stacked.scatter .pointActive(function(d) { //console.log(stacked.y()(d), !!Math.round(stacked.y()(d) * 100)); return !!Math.round(stacked.y()(d) * 100); }) ; //============================================================ //============================================================ // Private Variables //------------------------------------------------------------ var showTooltip = function(e, offsetElement) { var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), top = e.pos[1] + ( offsetElement.offsetTop || 0), x = xAxis.tickFormat()(stacked.x()(e.point, e.pointIndex)), y = yAxis.tickFormat()(stacked.y()(e.point, e.pointIndex)), content = tooltip(e.series.key, x, y, e, chart); nv.tooltip.show([left, top], content, e.value < 0 ? 'n' : 's', null, offsetElement); }; //============================================================ function chart(selection) { selection.each(function(data) { var container = d3.select(this), that = this; var availableWidth = (width || parseInt(container.style('width')) || 960) - margin.left - margin.right, availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; chart.update = function() { container.transition().call(chart); }; chart.container = this; //set state.disabled state.disabled = data.map(function(d) { return !!d.disabled }); if (!defaultState) { var key; defaultState = {}; for (key in state) { if (state[key] instanceof Array) defaultState[key] = state[key].slice(0); else defaultState[key] = state[key]; } } //------------------------------------------------------------ // Display No Data message if there's nothing to show. if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) { var noDataText = container.selectAll('.nv-noData').data([noData]); noDataText.enter().append('text') .attr('class', 'nvd3 nv-noData') .attr('dy', '-.7em') .style('text-anchor', 'middle'); noDataText .attr('x', margin.left + availableWidth / 2) .attr('y', margin.top + availableHeight / 2) .text(function(d) { return d }); return chart; } else { container.selectAll('.nv-noData').remove(); } //------------------------------------------------------------ //------------------------------------------------------------ // Setup Scales x = stacked.xScale(); y = stacked.yScale(); //------------------------------------------------------------ //------------------------------------------------------------ // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-stackedAreaChart').data([data]); var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-stackedAreaChart').append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-x nv-axis'); gEnter.append('g').attr('class', 'nv-y nv-axis'); gEnter.append('g').attr('class', 'nv-stackedWrap'); gEnter.append('g').attr('class', 'nv-legendWrap'); gEnter.append('g').attr('class', 'nv-controlsWrap'); //------------------------------------------------------------ //------------------------------------------------------------ // Legend if (showLegend) { legend .width( availableWidth - controlWidth ); g.select('.nv-legendWrap') .datum(data) .call(legend); if ( margin.top != legend.height()) { margin.top = legend.height(); availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; } g.select('.nv-legendWrap') .attr('transform', 'translate(' + controlWidth + ',' + (-margin.top) +')'); } //------------------------------------------------------------ //------------------------------------------------------------ // Controls if (showControls) { var controlsData = [ { key: 'Stacked', disabled: stacked.offset() != 'zero' }, { key: 'Stream', disabled: stacked.offset() != 'wiggle' }, { key: 'Expanded', disabled: stacked.offset() != 'expand' } ]; controls .width( controlWidth ) .color(['#444', '#444', '#444']); g.select('.nv-controlsWrap') .datum(controlsData) .call(controls); if ( margin.top != Math.max(controls.height(), legend.height()) ) { margin.top = Math.max(controls.height(), legend.height()); availableHeight = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom; } g.select('.nv-controlsWrap') .attr('transform', 'translate(0,' + (-margin.top) +')'); } //------------------------------------------------------------ wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); //------------------------------------------------------------ // Main Chart Component(s) stacked .width(availableWidth) .height(availableHeight) var stackedWrap = g.select('.nv-stackedWrap') .datum(data); //d3.transition(stackedWrap).call(stacked); stackedWrap.call(stacked); //------------------------------------------------------------ //------------------------------------------------------------ // Setup Axes xAxis .scale(x) .ticks( availableWidth / 100 ) .tickSize( -availableHeight, 0); g.select('.nv-x.nv-axis') .attr('transform', 'translate(0,' + availableHeight + ')'); //d3.transition(g.select('.nv-x.nv-axis')) g.select('.nv-x.nv-axis') .transition().duration(0) .call(xAxis); yAxis .scale(y) .ticks(stacked.offset() == 'wiggle' ? 0 : availableHeight / 36) .tickSize(-availableWidth, 0) .setTickFormat(stacked.offset() == 'expand' ? d3.format('%') : yAxisTickFormat); //d3.transition(g.select('.nv-y.nv-axis')) g.select('.nv-y.nv-axis') .transition().duration(0) .call(yAxis); //------------------------------------------------------------ //============================================================ // Event Handling/Dispatching (in chart's scope) //------------------------------------------------------------ stacked.dispatch.on('areaClick.toggle', function(e) { if (data.filter(function(d) { return !d.disabled }).length === 1) data = data.map(function(d) { d.disabled = false; return d }); else data = data.map(function(d,i) { d.disabled = (i != e.seriesIndex); return d }); state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); //selection.transition().call(chart); chart.update(); }); legend.dispatch.on('legendClick', function(d,i) { d.disabled = !d.disabled; if (!data.filter(function(d) { return !d.disabled }).length) { data.map(function(d) { d.disabled = false; return d; }); } state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); //selection.transition().call(chart); chart.update(); }); legend.dispatch.on('legendDblclick', function(d) { //Double clicking should always enable current series, and disabled all others. data.forEach(function(d) { d.disabled = true; }); d.disabled = false; state.disabled = data.map(function(d) { return !!d.disabled }); dispatch.stateChange(state); chart.update(); }); controls.dispatch.on('legendClick', function(d,i) { if (!d.disabled) return; controlsData = controlsData.map(function(s) { s.disabled = true; return s; }); d.disabled = false; switch (d.key) { case 'Stacked': stacked.style('stack'); break; case 'Stream': stacked.style('stream'); break; case 'Expanded': stacked.style('expand'); break; } state.style = stacked.style(); dispatch.stateChange(state); //selection.transition().call(chart); chart.update(); }); dispatch.on('tooltipShow', function(e) { if (tooltips) showTooltip(e, that.parentNode); }); // Update chart from a state object passed to event handler dispatch.on('changeState', function(e) { if (typeof e.disabled !== 'undefined') { data.forEach(function(series,i) { series.disabled = e.disabled[i]; }); state.disabled = e.disabled; } if (typeof e.style !== 'undefined') { stacked.style(e.style); } chart.update(); }); }); return chart; } //============================================================ // Event Handling/Dispatching (out of chart's scope) //------------------------------------------------------------ stacked.dispatch.on('tooltipShow', function(e) { //disable tooltips when value ~= 0 //// TODO: consider removing points from voronoi that have 0 value instead of this hack /* if (!Math.round(stacked.y()(e.point) * 100)) { // 100 will not be good for very small numbers... will have to think about making this valu dynamic, based on data range setTimeout(function() { d3.selectAll('.point.hover').classed('hover', false) }, 0); return false; } */ e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top], dispatch.tooltipShow(e); }); stacked.dispatch.on('tooltipHide', function(e) { dispatch.tooltipHide(e); }); dispatch.on('tooltipHide', function() { if (tooltips) nv.tooltip.cleanup(); }); //============================================================ //============================================================ // Expose Public Variables //------------------------------------------------------------ // expose chart's sub-components chart.dispatch = dispatch; chart.stacked = stacked; chart.legend = legend; chart.controls = controls; chart.xAxis = xAxis; chart.yAxis = yAxis; d3.rebind(chart, stacked, 'x', 'y', 'size', 'xScale', 'yScale', 'xDomain', 'yDomain', 'sizeDomain', 'interactive', 'offset', 'order', 'style', 'clipEdge', 'forceX', 'forceY', 'forceSize', 'interpolate'); chart.margin = function(_) { if (!arguments.length) return margin; margin.top = typeof _.top != 'undefined' ? _.top : margin.top; margin.right = typeof _.right != 'undefined' ? _.right : margin.right; margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; margin.left = typeof _.left != 'undefined' ? _.left : margin.left; return chart; }; chart.width = function(_) { if (!arguments.length) return getWidth; width = _; return chart; }; chart.height = function(_) { if (!arguments.length) return getHeight; height = _; return chart; }; chart.color = function(_) { if (!arguments.length) return color; color = nv.utils.getColor(_); legend.color(color); stacked.color(color); return chart; }; chart.showControls = function(_) { if (!arguments.length) return showControls; showControls = _; return chart; }; chart.showLegend = function(_) { if (!arguments.length) return showLegend; showLegend = _; return chart; }; chart.tooltip = function(_) { if (!arguments.length) return tooltip; tooltip = _; return chart; }; chart.tooltips = function(_) { if (!arguments.length) return tooltips; tooltips = _; return chart; }; chart.tooltipContent = function(_) { if (!arguments.length) return tooltip; tooltip = _; return chart; }; chart.state = function(_) { if (!arguments.length) return state; state = _; return chart; }; chart.defaultState = function(_) { if (!arguments.length) return defaultState; defaultState = _; return chart; }; chart.noData = function(_) { if (!arguments.length) return noData; noData = _; return chart; }; yAxis.setTickFormat = yAxis.tickFormat; yAxis.tickFormat = function(_) { if (!arguments.length) return yAxisTickFormat; yAxisTickFormat = _; return yAxis; }; //============================================================ return chart; } })();
mit
lukekarrys/lukecod.es
gatsby-config.js
2570
const TURBOLINKS = process.env.TURBOLINKS === "true" const NOJS = process.env.NOJS === "true" module.exports = { siteMetadata: { title: `Luke Codes`, description: `The code blog of Luke Karrys.`, author: `@lukekarrys`, }, plugins: [ `gatsby-plugin-react-helmet`, { resolve: `gatsby-source-filesystem`, options: { name: `images`, path: `${__dirname}/src/images`, }, }, { resolve: `gatsby-source-filesystem`, options: { name: `posts`, path: `${__dirname}/src/posts`, }, }, { resolve: `gatsby-source-filesystem`, options: { name: `projects`, path: `${__dirname}/src/projects`, }, }, `gatsby-transformer-sharp`, `gatsby-plugin-sharp`, { resolve: `gatsby-plugin-manifest`, options: { name: `gatsby-starter-default`, short_name: `starter`, start_url: `/`, background_color: `#6a9fb5`, theme_color: `#6a9fb5`, display: `minimal-ui`, icon: `src/images/logo.png`, }, }, { resolve: `gatsby-transformer-remark`, options: { excerpt_separator: `<!-- more -->`, plugins: [ { resolve: `gatsby-remark-images`, options: { maxWidth: 820, withWebp: true, }, }, { resolve: "gatsby-remark-embed-gist", options: { username: "lukekarrys", includeDefaultCss: true, }, }, { resolve: `gatsby-remark-autolink-headers`, options: { icon: false, maintainCase: false, removeAccents: true, }, }, { resolve: `gatsby-remark-prismjs`, options: { classPrefix: "language-", inlineCodeMarker: null, aliases: {}, showLineNumbers: false, noInlineHighlight: true, }, }, { resolve: "gatsby-remark-codesandbox-repl", options: { target: "_blank", directory: `${__dirname}/src/examples/`, }, }, `gatsby-remark-smartypants`, `gatsby-remark-static-images`, ], }, }, "gatsby-plugin-draft", { resolve: `gatsby-plugin-catch-links`, }, (TURBOLINKS || NOJS) && "gatsby-plugin-no-javascript", ].filter(Boolean), }
mit
robotis/heklapunch
src/is/heklapunch/MainActivity.java
2950
package is.heklapunch; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { EditText editBox; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // get name box editBox = (EditText) findViewById(R.id.saved_name); } //Go to compete mode public void keppa(View view) { if (!this.editBox.getText().toString().equals("")) { Intent o = new Intent(this, KeppaActivity.class); startActivity(o); } else { Toast.makeText(this, "Nafn keppanda er nauðsynlegt", Toast.LENGTH_SHORT).show(); } } //Go to organize mode public void organize(View view) { Intent o = new Intent(this, OrganizeActivity.class); startActivity(o); } //Go to organize mode public void test_qr(View view) { Intent o = new Intent(this, QRActivity.class); startActivity(o); } // Initiating Menu XML file (menu.xml) @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.main_menu, menu); return true; } protected void onResume() { super.onResume(); SharedPreferences prefs = this.getSharedPreferences("competitor_name", Context.MODE_PRIVATE); String restoredText = prefs.getString("competitor_name", null); if (restoredText != null) { editBox.setText(restoredText, TextView.BufferType.EDITABLE); int selectionStart = prefs.getInt("selection-start", -1); int selectionEnd = prefs.getInt("selection-end", -1); if (selectionStart != -1 && selectionEnd != -1) { editBox.setSelection(selectionStart, selectionEnd); } } } protected void onPause() { super.onPause(); SharedPreferences prefs = this.getSharedPreferences("competitor_name", Context.MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); editor.putString("competitor_name", editBox.getText().toString()); editor.putInt("selection-start", editBox.getSelectionStart()); editor.putInt("selection-end", editBox.getSelectionEnd()); editor.commit(); } @Override //Handle menu clicks public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.main_test: this.test_qr(this.getCurrentFocus()); return true; default: return super.onOptionsItemSelected(item); } } }
mit
wesleye2003/pick-app
test/controllers/users_controller_test.rb
504
require 'test_helper' class UsersControllerTest < ActionController::TestCase test "Controller should render user profile" do get(:show, {'id' => users(:jimi).id}) assert_response :success # assert_not_nil assigns(:posts) end test "controller should create a user" do assert_difference('User.count') do post :create, { :username => 'Beyonce', :password => 'password', :zipcode => '60601' } end # assert_redirected_to post_path(assigns(:post)) end end
mit
emclab/ad_resourcex
lib/ad_resourcex/engine.rb
301
module AdResourcex class Engine < ::Rails::Engine isolate_namespace AdResourcex config.generators do |g| g.template_engine :erb g.integration_tool :rspec g.test_framework :rspec g.fixture_replacement :factory_girl, :dir => "spec/factories" end end end
mit
parix/gw2
lib/gw2/event.rb
551
module GW2 module Event extend Resource def self.all raise GW2::Disabled, "This endpoint is disabled due to the implementation of Megaserver technology." end def self.where(query_hash = {}) raise GW2::Disabled, "This endpoint is disabled due to the implementation of Megaserver technology." end def self.world_names get("/world_names.json") end def self.event_names raise GW2::Disabled, "This endpoint is disabled." end def self.map_names GW2::Misc.worlds end end end
mit
attugit/archie
test/utils/mover_test.cpp
1049
#include <archie/fused/mover.hpp> #include <type_traits> #include <gtest/gtest.h> namespace { namespace fused = archie::fused; struct empty { }; struct def { def(def&&) = default; def(def const&) = default; }; struct nondef { nondef(nondef&&) {} nondef(nondef const&) {} }; struct noncopyable { noncopyable(noncopyable&&) = default; noncopyable(noncopyable const&) = delete; }; static_assert(std::is_same<fused::move_t<int>, int>::value, ""); static_assert(std::is_same<fused::move_t<empty>, empty>::value, ""); static_assert(std::is_same<fused::move_t<def>, def>::value, ""); static_assert(std::is_same<fused::move_t<nondef>, fused::detail::move_capture<nondef>>::value, ""); static_assert( std::is_same<fused::move_t<noncopyable>, fused::detail::move_capture<noncopyable>>::value, ""); TEST(mover, canCastToConstValue) { auto i = 1; auto m = fused::move_t<const int&>(i); auto const& x = static_cast<const int&>(m); EXPECT_EQ(&i, &x); } }
mit
sfgeorge/ruby_speech
spec/ruby_speech/ssml/p_spec.rb
3028
require 'spec_helper' module RubySpeech module SSML describe P do let(:doc) { Nokogiri::XML::Document.new } subject { described_class.new doc } its(:name) { should == 'p' } describe "setting options in initializers" do subject { P.new doc, :language => 'jp' } its(:language) { should == 'jp' } end it 'registers itself' do Element.class_from_registration(:p).should == P end describe "from a document" do let(:document) { '<p>foo</p>' } subject { Element.import document } it { should be_instance_of P } its(:content) { should == 'foo' } end describe "comparing objects" do it "should be equal if the content and language are the same" do P.new(doc, :language => 'jp', :content => "Hello there").should == P.new(doc, :language => 'jp', :content => "Hello there") end describe "when the content is different" do it "should not be equal" do P.new(doc, :content => "Hello").should_not == P.new(doc, :content => "Hello there") end end describe "when the language is different" do it "should not be equal" do P.new(doc, :language => 'jp').should_not == P.new(doc, :language => 'en') end end end describe "<<" do it "should accept String" do lambda { subject << 'anything' }.should_not raise_error end it "should accept Audio" do lambda { subject << Audio.new(doc) }.should_not raise_error end it "should accept Break" do lambda { subject << Break.new(doc) }.should_not raise_error end it "should accept Emphasis" do lambda { subject << Emphasis.new(doc) }.should_not raise_error end it "should accept Mark" do lambda { subject << Mark.new(doc) }.should_not raise_error end it "should accept Phoneme" do lambda { subject << Phoneme.new(doc) }.should_not raise_error end it "should accept Prosody" do lambda { subject << Prosody.new(doc) }.should_not raise_error end it "should accept SayAs" do lambda { subject << SayAs.new(doc, :interpret_as => :foo) }.should_not raise_error end it "should accept Sub" do lambda { subject << Sub.new(doc) }.should_not raise_error end it "should accept S" do lambda { subject << S.new(doc) }.should_not raise_error end it "should accept Voice" do lambda { subject << Voice.new(doc) }.should_not raise_error end it "should raise InvalidChildError with non-acceptable objects" do lambda { subject << 1 }.should raise_error(InvalidChildError, "A P can only accept String, Audio, Break, Emphasis, Mark, Phoneme, Prosody, SayAs, Sub, S, Voice as children") end end end # P end # SSML end # RubySpeech
mit
brianc/node-postgres
packages/pg/test/integration/client/api-tests.js
6768
'use strict' var helper = require('../test-helper') var pg = helper.pg var suite = new helper.Suite() suite.test('null and undefined are both inserted as NULL', function (done) { const pool = new pg.Pool() pool.connect( assert.calls(function (err, client, release) { assert(!err) client.query('CREATE TEMP TABLE my_nulls(a varchar(1), b varchar(1), c integer, d integer, e date, f date)') client.query('INSERT INTO my_nulls(a,b,c,d,e,f) VALUES ($1,$2,$3,$4,$5,$6)', [ null, undefined, null, undefined, null, undefined, ]) client.query( 'SELECT * FROM my_nulls', assert.calls(function (err, result) { console.log(err) assert.ifError(err) assert.equal(result.rows.length, 1) assert.isNull(result.rows[0].a) assert.isNull(result.rows[0].b) assert.isNull(result.rows[0].c) assert.isNull(result.rows[0].d) assert.isNull(result.rows[0].e) assert.isNull(result.rows[0].f) pool.end(done) release() }) ) }) ) }) suite.test('pool callback behavior', (done) => { // test weird callback behavior with node-pool const pool = new pg.Pool() pool.connect(function (err) { assert(!err) arguments[1].emit('drain') arguments[2]() pool.end(done) }) }) suite.test('query timeout', (cb) => { const pool = new pg.Pool({ query_timeout: 1000 }) pool.connect().then((client) => { client.query( 'SELECT pg_sleep(2)', assert.calls(function (err, result) { assert(err) assert(err.message === 'Query read timeout') client.release() pool.end(cb) }) ) }) }) suite.test('query recover from timeout', (cb) => { const pool = new pg.Pool({ query_timeout: 1000 }) pool.connect().then((client) => { client.query( 'SELECT pg_sleep(20)', assert.calls(function (err, result) { assert(err) assert(err.message === 'Query read timeout') client.release(err) pool.connect().then((client) => { client.query( 'SELECT 1', assert.calls(function (err, result) { assert(!err) client.release(err) pool.end(cb) }) ) }) }) ) }) }) suite.test('query no timeout', (cb) => { const pool = new pg.Pool({ query_timeout: 10000 }) pool.connect().then((client) => { client.query( 'SELECT pg_sleep(1)', assert.calls(function (err, result) { assert(!err) client.release() pool.end(cb) }) ) }) }) suite.test('callback API', (done) => { const client = new helper.Client() client.query('CREATE TEMP TABLE peep(name text)') client.query('INSERT INTO peep(name) VALUES ($1)', ['brianc']) const config = { text: 'INSERT INTO peep(name) VALUES ($1)', values: ['brian'], } client.query(config) client.query('INSERT INTO peep(name) VALUES ($1)', ['aaron']) client.query('SELECT * FROM peep ORDER BY name COLLATE "C"', (err, res) => { assert(!err) assert.equal(res.rowCount, 3) assert.deepEqual(res.rows, [ { name: 'aaron', }, { name: 'brian', }, { name: 'brianc', }, ]) done() }) client.connect((err) => { assert(!err) client.once('drain', () => client.end()) }) }) suite.test('executing nested queries', function (done) { const pool = new pg.Pool() pool.connect( assert.calls(function (err, client, release) { assert(!err) client.query( 'select now as now from NOW()', assert.calls(function (err, result) { assert.equal(new Date().getYear(), result.rows[0].now.getYear()) client.query( 'select now as now_again FROM NOW()', assert.calls(function () { client.query( 'select * FROM NOW()', assert.calls(function () { assert.ok('all queries hit') release() pool.end(done) }) ) }) ) }) ) }) ) }) suite.test('raises error if cannot connect', function () { var connectionString = 'pg://sfalsdkf:asdf@localhost/ieieie' const pool = new pg.Pool({ connectionString: connectionString }) pool.connect( assert.calls(function (err, client, done) { assert.ok(err, 'should have raised an error') done() }) ) }) suite.test('query errors are handled and do not bubble if callback is provided', function (done) { const pool = new pg.Pool() pool.connect( assert.calls(function (err, client, release) { assert(!err) client.query( 'SELECT OISDJF FROM LEIWLISEJLSE', assert.calls(function (err, result) { assert.ok(err) release() pool.end(done) }) ) }) ) }) suite.test('callback is fired once and only once', function (done) { const pool = new pg.Pool() pool.connect( assert.calls(function (err, client, release) { assert(!err) client.query('CREATE TEMP TABLE boom(name varchar(10))') var callCount = 0 client.query( [ "INSERT INTO boom(name) VALUES('hai')", "INSERT INTO boom(name) VALUES('boom')", "INSERT INTO boom(name) VALUES('zoom')", ].join(';'), function (err, callback) { assert.equal(callCount++, 0, 'Call count should be 0. More means this callback fired more than once.') release() pool.end(done) } ) }) ) }) suite.test('can provide callback and config object', function (done) { const pool = new pg.Pool() pool.connect( assert.calls(function (err, client, release) { assert(!err) client.query( { name: 'boom', text: 'select NOW()', }, assert.calls(function (err, result) { assert(!err) assert.equal(result.rows[0].now.getYear(), new Date().getYear()) release() pool.end(done) }) ) }) ) }) suite.test('can provide callback and config and parameters', function (done) { const pool = new pg.Pool() pool.connect( assert.calls(function (err, client, release) { assert(!err) var config = { text: 'select $1::text as val', } client.query( config, ['hi'], assert.calls(function (err, result) { assert(!err) assert.equal(result.rows.length, 1) assert.equal(result.rows[0].val, 'hi') release() pool.end(done) }) ) }) ) })
mit
thuraucsy/onlineshop
fuel/app/views/admin/member/index.php
1326
<?php echo Form::open(array("class"=>"form-horizontal"));?> <div class="col-md-3"> <label for="search">Search member by name or email:</label> <?php echo Form::input('search', Input::post('search'), array('placeholder' => 'search')); ?> <?php echo Form::submit('submit', 'Search'); ?> </div> <?php echo Form::close(); ?> <br/> <?php echo Html::anchor('admin/member/create','Add Member',array('class' => 'btn btn-success pull-right')); ?> <?php if ($list_member): ?> <table class="table table-striped"> <thead> <tr> <th>Username</th> <th>Email</th> <th>Address</th> <th>Phone</th> <th>Created Date</th> <th>Action</th> </tr> </thead> <tbody> <?php foreach ($list_member as $item): ?> <tr> <td><?php echo $item->username; ?></td> <td><?php echo $item->email; ?></td> <td><?php echo $item->address; ?></td> <td><?php echo $item->phone; ?></td> <td><?php echo date('Y-m-d', $item->created_at); ?></td> <td> <?php echo Html::anchor('admin/member/edit/'.$item->id, 'Edit'); ?> | <?php echo Html::anchor('admin/member/delete/'.$item->id, 'Delete', array('onclick' => "return confirm('Are you sure?')")); ?> </td> </tr> <?php endforeach; ?> </tbody> </table> <?php else: ?> <p>No Createusers.</p> <?php endif; ?> <br>
mit
vitorbal/eslint
lib/code-path-analysis/code-path-state.js
44877
/** * @fileoverview A class to manage state of generating a code path. * @author Toru Nagashima */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ const CodePathSegment = require("./code-path-segment"), ForkContext = require("./fork-context"); //------------------------------------------------------------------------------ // Helpers //------------------------------------------------------------------------------ /** * Adds given segments into the `dest` array. * If the `others` array does not includes the given segments, adds to the `all` * array as well. * * This adds only reachable and used segments. * * @param {CodePathSegment[]} dest - A destination array (`returnedSegments` or `thrownSegments`). * @param {CodePathSegment[]} others - Another destination array (`returnedSegments` or `thrownSegments`). * @param {CodePathSegment[]} all - The unified destination array (`finalSegments`). * @param {CodePathSegment[]} segments - Segments to add. * @returns {void} */ function addToReturnedOrThrown(dest, others, all, segments) { for (let i = 0; i < segments.length; ++i) { const segment = segments[i]; dest.push(segment); if (others.indexOf(segment) === -1) { all.push(segment); } } } /** * Gets a loop-context for a `continue` statement. * * @param {CodePathState} state - A state to get. * @param {string} label - The label of a `continue` statement. * @returns {LoopContext} A loop-context for a `continue` statement. */ function getContinueContext(state, label) { if (!label) { return state.loopContext; } let context = state.loopContext; while (context) { if (context.label === label) { return context; } context = context.upper; } /* istanbul ignore next: foolproof (syntax error) */ return null; } /** * Gets a context for a `break` statement. * * @param {CodePathState} state - A state to get. * @param {string} label - The label of a `break` statement. * @returns {LoopContext|SwitchContext} A context for a `break` statement. */ function getBreakContext(state, label) { let context = state.breakContext; while (context) { if (label ? context.label === label : context.breakable) { return context; } context = context.upper; } /* istanbul ignore next: foolproof (syntax error) */ return null; } /** * Gets a context for a `return` statement. * * @param {CodePathState} state - A state to get. * @returns {TryContext|CodePathState} A context for a `return` statement. */ function getReturnContext(state) { let context = state.tryContext; while (context) { if (context.hasFinalizer && context.position !== "finally") { return context; } context = context.upper; } return state; } /** * Gets a context for a `throw` statement. * * @param {CodePathState} state - A state to get. * @returns {TryContext|CodePathState} A context for a `throw` statement. */ function getThrowContext(state) { let context = state.tryContext; while (context) { if (context.position === "try" || (context.hasFinalizer && context.position === "catch") ) { return context; } context = context.upper; } return state; } /** * Removes a given element from a given array. * * @param {any[]} xs - An array to remove the specific element. * @param {any} x - An element to be removed. * @returns {void} */ function remove(xs, x) { xs.splice(xs.indexOf(x), 1); } /** * Disconnect given segments. * * This is used in a process for switch statements. * If there is the "default" chunk before other cases, the order is different * between node's and running's. * * @param {CodePathSegment[]} prevSegments - Forward segments to disconnect. * @param {CodePathSegment[]} nextSegments - Backward segments to disconnect. * @returns {void} */ function removeConnection(prevSegments, nextSegments) { for (let i = 0; i < prevSegments.length; ++i) { const prevSegment = prevSegments[i]; const nextSegment = nextSegments[i]; remove(prevSegment.nextSegments, nextSegment); remove(prevSegment.allNextSegments, nextSegment); remove(nextSegment.prevSegments, prevSegment); remove(nextSegment.allPrevSegments, prevSegment); } } /** * Creates looping path. * * @param {CodePathState} state - The instance. * @param {CodePathSegment[]} fromSegments - Segments which are source. * @param {CodePathSegment[]} toSegments - Segments which are destination. * @returns {void} */ function makeLooped(state, fromSegments, toSegments) { const end = Math.min(fromSegments.length, toSegments.length); for (let i = 0; i < end; ++i) { const fromSegment = fromSegments[i]; const toSegment = toSegments[i]; if (toSegment.reachable) { fromSegment.nextSegments.push(toSegment); } if (fromSegment.reachable) { toSegment.prevSegments.push(fromSegment); } fromSegment.allNextSegments.push(toSegment); toSegment.allPrevSegments.push(fromSegment); if (toSegment.allPrevSegments.length >= 2) { CodePathSegment.markPrevSegmentAsLooped(toSegment, fromSegment); } state.notifyLooped(fromSegment, toSegment); } } /** * Finalizes segments of `test` chunk of a ForStatement. * * - Adds `false` paths to paths which are leaving from the loop. * - Sets `true` paths to paths which go to the body. * * @param {LoopContext} context - A loop context to modify. * @param {ChoiceContext} choiceContext - A choice context of this loop. * @param {CodePathSegment[]} head - The current head paths. * @returns {void} */ function finalizeTestSegmentsOfFor(context, choiceContext, head) { if (!choiceContext.processed) { choiceContext.trueForkContext.add(head); choiceContext.falseForkContext.add(head); } if (context.test !== true) { context.brokenForkContext.addAll(choiceContext.falseForkContext); } context.endOfTestSegments = choiceContext.trueForkContext.makeNext(0, -1); } //------------------------------------------------------------------------------ // Public Interface //------------------------------------------------------------------------------ /** * A class which manages state to analyze code paths. * * @constructor * @param {IdGenerator} idGenerator - An id generator to generate id for code * path segments. * @param {Function} onLooped - A callback function to notify looping. */ function CodePathState(idGenerator, onLooped) { this.idGenerator = idGenerator; this.notifyLooped = onLooped; this.forkContext = ForkContext.newRoot(idGenerator); this.choiceContext = null; this.switchContext = null; this.tryContext = null; this.loopContext = null; this.breakContext = null; this.currentSegments = []; this.initialSegment = this.forkContext.head[0]; // returnedSegments and thrownSegments push elements into finalSegments also. const final = this.finalSegments = []; const returned = this.returnedForkContext = []; const thrown = this.thrownForkContext = []; returned.add = addToReturnedOrThrown.bind(null, returned, thrown, final); thrown.add = addToReturnedOrThrown.bind(null, thrown, returned, final); } CodePathState.prototype = { constructor: CodePathState, /** * The head segments. * @type {CodePathSegment[]} */ get headSegments() { return this.forkContext.head; }, /** * The parent forking context. * This is used for the root of new forks. * @type {ForkContext} */ get parentForkContext() { const current = this.forkContext; return current && current.upper; }, /** * Creates and stacks new forking context. * * @param {boolean} forkLeavingPath - A flag which shows being in a * "finally" block. * @returns {ForkContext} The created context. */ pushForkContext: function(forkLeavingPath) { this.forkContext = ForkContext.newEmpty( this.forkContext, forkLeavingPath ); return this.forkContext; }, /** * Pops and merges the last forking context. * @returns {ForkContext} The last context. */ popForkContext: function() { const lastContext = this.forkContext; this.forkContext = lastContext.upper; this.forkContext.replaceHead(lastContext.makeNext(0, -1)); return lastContext; }, /** * Creates a new path. * @returns {void} */ forkPath: function() { this.forkContext.add(this.parentForkContext.makeNext(-1, -1)); }, /** * Creates a bypass path. * This is used for such as IfStatement which does not have "else" chunk. * * @returns {void} */ forkBypassPath: function() { this.forkContext.add(this.parentForkContext.head); }, //-------------------------------------------------------------------------- // ConditionalExpression, LogicalExpression, IfStatement //-------------------------------------------------------------------------- /** * Creates a context for ConditionalExpression, LogicalExpression, * IfStatement, WhileStatement, DoWhileStatement, or ForStatement. * * LogicalExpressions have cases that it goes different paths between the * `true` case and the `false` case. * * For Example: * * if (a || b) { * foo(); * } else { * bar(); * } * * In this case, `b` is evaluated always in the code path of the `else` * block, but it's not so in the code path of the `if` block. * So there are 3 paths. * * a -> foo(); * a -> b -> foo(); * a -> b -> bar(); * * @param {string} kind - A kind string. * If the new context is LogicalExpression's, this is `"&&"` or `"||"`. * If it's IfStatement's or ConditionalExpression's, this is `"test"`. * Otherwise, this is `"loop"`. * @param {boolean} isForkingAsResult - A flag that shows that goes different * paths between `true` and `false`. * @returns {void} */ pushChoiceContext: function(kind, isForkingAsResult) { this.choiceContext = { upper: this.choiceContext, kind: kind, isForkingAsResult: isForkingAsResult, trueForkContext: ForkContext.newEmpty(this.forkContext), falseForkContext: ForkContext.newEmpty(this.forkContext), processed: false }; }, /** * Pops the last choice context and finalizes it. * * @returns {ChoiceContext} The popped context. */ popChoiceContext: function() { const context = this.choiceContext; this.choiceContext = context.upper; const forkContext = this.forkContext; const headSegments = forkContext.head; switch (context.kind) { case "&&": case "||": /* * If any result were not transferred from child contexts, * this sets the head segments to both cases. * The head segments are the path of the right-hand operand. */ if (!context.processed) { context.trueForkContext.add(headSegments); context.falseForkContext.add(headSegments); } /* * Transfers results to upper context if this context is in * test chunk. */ if (context.isForkingAsResult) { const parentContext = this.choiceContext; parentContext.trueForkContext.addAll(context.trueForkContext); parentContext.falseForkContext.addAll(context.falseForkContext); parentContext.processed = true; return context; } break; case "test": if (!context.processed) { /* * The head segments are the path of the `if` block here. * Updates the `true` path with the end of the `if` block. */ context.trueForkContext.clear(); context.trueForkContext.add(headSegments); } else { /* * The head segments are the path of the `else` block here. * Updates the `false` path with the end of the `else` * block. */ context.falseForkContext.clear(); context.falseForkContext.add(headSegments); } break; case "loop": /* * Loops are addressed in popLoopContext(). * This is called from popLoopContext(). */ return context; /* istanbul ignore next */ default: throw new Error("unreachable"); } // Merges all paths. const prevForkContext = context.trueForkContext; prevForkContext.addAll(context.falseForkContext); forkContext.replaceHead(prevForkContext.makeNext(0, -1)); return context; }, /** * Makes a code path segment of the right-hand operand of a logical * expression. * * @returns {void} */ makeLogicalRight: function() { const context = this.choiceContext; const forkContext = this.forkContext; if (context.processed) { /* * This got segments already from the child choice context. * Creates the next path from own true/false fork context. */ const prevForkContext = context.kind === "&&" ? context.trueForkContext : /* kind === "||" */ context.falseForkContext; forkContext.replaceHead(prevForkContext.makeNext(0, -1)); prevForkContext.clear(); context.processed = false; } else { /* * This did not get segments from the child choice context. * So addresses the head segments. * The head segments are the path of the left-hand operand. */ if (context.kind === "&&") { // The path does short-circuit if false. context.falseForkContext.add(forkContext.head); } else { // The path does short-circuit if true. context.trueForkContext.add(forkContext.head); } forkContext.replaceHead(forkContext.makeNext(-1, -1)); } }, /** * Makes a code path segment of the `if` block. * * @returns {void} */ makeIfConsequent: function() { const context = this.choiceContext; const forkContext = this.forkContext; /* * If any result were not transferred from child contexts, * this sets the head segments to both cases. * The head segments are the path of the test expression. */ if (!context.processed) { context.trueForkContext.add(forkContext.head); context.falseForkContext.add(forkContext.head); } context.processed = false; // Creates new path from the `true` case. forkContext.replaceHead( context.trueForkContext.makeNext(0, -1) ); }, /** * Makes a code path segment of the `else` block. * * @returns {void} */ makeIfAlternate: function() { const context = this.choiceContext; const forkContext = this.forkContext; /* * The head segments are the path of the `if` block. * Updates the `true` path with the end of the `if` block. */ context.trueForkContext.clear(); context.trueForkContext.add(forkContext.head); context.processed = true; // Creates new path from the `false` case. forkContext.replaceHead( context.falseForkContext.makeNext(0, -1) ); }, //-------------------------------------------------------------------------- // SwitchStatement //-------------------------------------------------------------------------- /** * Creates a context object of SwitchStatement and stacks it. * * @param {boolean} hasCase - `true` if the switch statement has one or more * case parts. * @param {string|null} label - The label text. * @returns {void} */ pushSwitchContext: function(hasCase, label) { this.switchContext = { upper: this.switchContext, hasCase: hasCase, defaultSegments: null, defaultBodySegments: null, foundDefault: false, lastIsDefault: false, countForks: 0 }; this.pushBreakContext(true, label); }, /** * Pops the last context of SwitchStatement and finalizes it. * * - Disposes all forking stack for `case` and `default`. * - Creates the next code path segment from `context.brokenForkContext`. * - If the last `SwitchCase` node is not a `default` part, creates a path * to the `default` body. * * @returns {void} */ popSwitchContext: function() { const context = this.switchContext; this.switchContext = context.upper; const forkContext = this.forkContext; const brokenForkContext = this.popBreakContext().brokenForkContext; if (context.countForks === 0) { /* * When there is only one `default` chunk and there is one or more * `break` statements, even if forks are nothing, it needs to merge * those. */ if (!brokenForkContext.empty) { brokenForkContext.add(forkContext.makeNext(-1, -1)); forkContext.replaceHead(brokenForkContext.makeNext(0, -1)); } return; } const lastSegments = forkContext.head; this.forkBypassPath(); const lastCaseSegments = forkContext.head; /* * `brokenForkContext` is used to make the next segment. * It must add the last segment into `brokenForkContext`. */ brokenForkContext.add(lastSegments); /* * A path which is failed in all case test should be connected to path * of `default` chunk. */ if (!context.lastIsDefault) { if (context.defaultBodySegments) { /* * Remove a link from `default` label to its chunk. * It's false route. */ removeConnection(context.defaultSegments, context.defaultBodySegments); makeLooped(this, lastCaseSegments, context.defaultBodySegments); } else { /* * It handles the last case body as broken if `default` chunk * does not exist. */ brokenForkContext.add(lastCaseSegments); } } // Pops the segment context stack until the entry segment. for (let i = 0; i < context.countForks; ++i) { this.forkContext = this.forkContext.upper; } /* * Creates a path from all brokenForkContext paths. * This is a path after switch statement. */ this.forkContext.replaceHead(brokenForkContext.makeNext(0, -1)); }, /** * Makes a code path segment for a `SwitchCase` node. * * @param {boolean} isEmpty - `true` if the body is empty. * @param {boolean} isDefault - `true` if the body is the default case. * @returns {void} */ makeSwitchCaseBody: function(isEmpty, isDefault) { const context = this.switchContext; if (!context.hasCase) { return; } /* * Merge forks. * The parent fork context has two segments. * Those are from the current case and the body of the previous case. */ const parentForkContext = this.forkContext; const forkContext = this.pushForkContext(); forkContext.add(parentForkContext.makeNext(0, -1)); /* * Save `default` chunk info. * If the `default` label is not at the last, we must make a path from * the last `case` to the `default` chunk. */ if (isDefault) { context.defaultSegments = parentForkContext.head; if (isEmpty) { context.foundDefault = true; } else { context.defaultBodySegments = forkContext.head; } } else { if (!isEmpty && context.foundDefault) { context.foundDefault = false; context.defaultBodySegments = forkContext.head; } } context.lastIsDefault = isDefault; context.countForks += 1; }, //-------------------------------------------------------------------------- // TryStatement //-------------------------------------------------------------------------- /** * Creates a context object of TryStatement and stacks it. * * @param {boolean} hasFinalizer - `true` if the try statement has a * `finally` block. * @returns {void} */ pushTryContext: function(hasFinalizer) { this.tryContext = { upper: this.tryContext, position: "try", hasFinalizer: hasFinalizer, returnedForkContext: hasFinalizer ? ForkContext.newEmpty(this.forkContext) : null, thrownForkContext: ForkContext.newEmpty(this.forkContext), lastOfTryIsReachable: false, lastOfCatchIsReachable: false }; }, /** * Pops the last context of TryStatement and finalizes it. * * @returns {void} */ popTryContext: function() { const context = this.tryContext; this.tryContext = context.upper; if (context.position === "catch") { // Merges two paths from the `try` block and `catch` block merely. this.popForkContext(); return; } /* * The following process is executed only when there is the `finally` * block. */ const returned = context.returnedForkContext; const thrown = context.thrownForkContext; if (returned.empty && thrown.empty) { return; } // Separate head to normal paths and leaving paths. const headSegments = this.forkContext.head; this.forkContext = this.forkContext.upper; const normalSegments = headSegments.slice(0, headSegments.length / 2 | 0); const leavingSegments = headSegments.slice(headSegments.length / 2 | 0); // Forwards the leaving path to upper contexts. if (!returned.empty) { getReturnContext(this).returnedForkContext.add(leavingSegments); } if (!thrown.empty) { getThrowContext(this).thrownForkContext.add(leavingSegments); } // Sets the normal path as the next. this.forkContext.replaceHead(normalSegments); // If both paths of the `try` block and the `catch` block are // unreachable, the next path becomes unreachable as well. if (!context.lastOfTryIsReachable && !context.lastOfCatchIsReachable) { this.forkContext.makeUnreachable(); } }, /** * Makes a code path segment for a `catch` block. * * @returns {void} */ makeCatchBlock: function() { const context = this.tryContext; const forkContext = this.forkContext; const thrown = context.thrownForkContext; // Update state. context.position = "catch"; context.thrownForkContext = ForkContext.newEmpty(forkContext); context.lastOfTryIsReachable = forkContext.reachable; // Merge thrown paths. thrown.add(forkContext.head); const thrownSegments = thrown.makeNext(0, -1); // Fork to a bypass and the merged thrown path. this.pushForkContext(); this.forkBypassPath(); this.forkContext.add(thrownSegments); }, /** * Makes a code path segment for a `finally` block. * * In the `finally` block, parallel paths are created. The parallel paths * are used as leaving-paths. The leaving-paths are paths from `return` * statements and `throw` statements in a `try` block or a `catch` block. * * @returns {void} */ makeFinallyBlock: function() { const context = this.tryContext; let forkContext = this.forkContext; const returned = context.returnedForkContext; const thrown = context.thrownForkContext; const headOfLeavingSegments = forkContext.head; // Update state. if (context.position === "catch") { // Merges two paths from the `try` block and `catch` block. this.popForkContext(); forkContext = this.forkContext; context.lastOfCatchIsReachable = forkContext.reachable; } else { context.lastOfTryIsReachable = forkContext.reachable; } context.position = "finally"; if (returned.empty && thrown.empty) { // This path does not leave. return; } /* * Create a parallel segment from merging returned and thrown. * This segment will leave at the end of this finally block. */ const segments = forkContext.makeNext(-1, -1); let j; for (let i = 0; i < forkContext.count; ++i) { const prevSegsOfLeavingSegment = [headOfLeavingSegments[i]]; for (j = 0; j < returned.segmentsList.length; ++j) { prevSegsOfLeavingSegment.push(returned.segmentsList[j][i]); } for (j = 0; j < thrown.segmentsList.length; ++j) { prevSegsOfLeavingSegment.push(thrown.segmentsList[j][i]); } segments.push(CodePathSegment.newNext( this.idGenerator.next(), prevSegsOfLeavingSegment)); } this.pushForkContext(true); this.forkContext.add(segments); }, /** * Makes a code path segment from the first throwable node to the `catch` * block or the `finally` block. * * @returns {void} */ makeFirstThrowablePathInTryBlock: function() { const forkContext = this.forkContext; if (!forkContext.reachable) { return; } const context = getThrowContext(this); if (context === this || context.position !== "try" || !context.thrownForkContext.empty ) { return; } context.thrownForkContext.add(forkContext.head); forkContext.replaceHead(forkContext.makeNext(-1, -1)); }, //-------------------------------------------------------------------------- // Loop Statements //-------------------------------------------------------------------------- /** * Creates a context object of a loop statement and stacks it. * * @param {string} type - The type of the node which was triggered. One of * `WhileStatement`, `DoWhileStatement`, `ForStatement`, `ForInStatement`, * and `ForStatement`. * @param {string|null} label - A label of the node which was triggered. * @returns {void} */ pushLoopContext: function(type, label) { const forkContext = this.forkContext; const breakContext = this.pushBreakContext(true, label); switch (type) { case "WhileStatement": this.pushChoiceContext("loop", false); this.loopContext = { upper: this.loopContext, type: type, label: label, test: void 0, continueDestSegments: null, brokenForkContext: breakContext.brokenForkContext }; break; case "DoWhileStatement": this.pushChoiceContext("loop", false); this.loopContext = { upper: this.loopContext, type: type, label: label, test: void 0, entrySegments: null, continueForkContext: ForkContext.newEmpty(forkContext), brokenForkContext: breakContext.brokenForkContext }; break; case "ForStatement": this.pushChoiceContext("loop", false); this.loopContext = { upper: this.loopContext, type: type, label: label, test: void 0, endOfInitSegments: null, testSegments: null, endOfTestSegments: null, updateSegments: null, endOfUpdateSegments: null, continueDestSegments: null, brokenForkContext: breakContext.brokenForkContext }; break; case "ForInStatement": case "ForOfStatement": this.loopContext = { upper: this.loopContext, type: type, label: label, prevSegments: null, leftSegments: null, endOfLeftSegments: null, continueDestSegments: null, brokenForkContext: breakContext.brokenForkContext }; break; /* istanbul ignore next */ default: throw new Error("unknown type: \"" + type + "\""); } }, /** * Pops the last context of a loop statement and finalizes it. * * @returns {void} */ popLoopContext: function() { const context = this.loopContext; this.loopContext = context.upper; const forkContext = this.forkContext; const brokenForkContext = this.popBreakContext().brokenForkContext; let choiceContext; // Creates a looped path. switch (context.type) { case "WhileStatement": case "ForStatement": choiceContext = this.popChoiceContext(); makeLooped( this, forkContext.head, context.continueDestSegments); break; case "DoWhileStatement": { choiceContext = this.popChoiceContext(); if (!choiceContext.processed) { choiceContext.trueForkContext.add(forkContext.head); choiceContext.falseForkContext.add(forkContext.head); } if (context.test !== true) { brokenForkContext.addAll(choiceContext.falseForkContext); } // `true` paths go to looping. const segmentsList = choiceContext.trueForkContext.segmentsList; for (let i = 0; i < segmentsList.length; ++i) { makeLooped( this, segmentsList[i], context.entrySegments); } break; } case "ForInStatement": case "ForOfStatement": brokenForkContext.add(forkContext.head); makeLooped( this, forkContext.head, context.leftSegments); break; /* istanbul ignore next */ default: throw new Error("unreachable"); } // Go next. if (brokenForkContext.empty) { forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); } else { forkContext.replaceHead(brokenForkContext.makeNext(0, -1)); } }, /** * Makes a code path segment for the test part of a WhileStatement. * * @param {boolean|undefined} test - The test value (only when constant). * @returns {void} */ makeWhileTest: function(test) { const context = this.loopContext; const forkContext = this.forkContext; const testSegments = forkContext.makeNext(0, -1); // Update state. context.test = test; context.continueDestSegments = testSegments; forkContext.replaceHead(testSegments); }, /** * Makes a code path segment for the body part of a WhileStatement. * * @returns {void} */ makeWhileBody: function() { const context = this.loopContext; const choiceContext = this.choiceContext; const forkContext = this.forkContext; if (!choiceContext.processed) { choiceContext.trueForkContext.add(forkContext.head); choiceContext.falseForkContext.add(forkContext.head); } // Update state. if (context.test !== true) { context.brokenForkContext.addAll(choiceContext.falseForkContext); } forkContext.replaceHead(choiceContext.trueForkContext.makeNext(0, -1)); }, /** * Makes a code path segment for the body part of a DoWhileStatement. * * @returns {void} */ makeDoWhileBody: function() { const context = this.loopContext; const forkContext = this.forkContext; const bodySegments = forkContext.makeNext(-1, -1); // Update state. context.entrySegments = bodySegments; forkContext.replaceHead(bodySegments); }, /** * Makes a code path segment for the test part of a DoWhileStatement. * * @param {boolean|undefined} test - The test value (only when constant). * @returns {void} */ makeDoWhileTest: function(test) { const context = this.loopContext; const forkContext = this.forkContext; context.test = test; // Creates paths of `continue` statements. if (!context.continueForkContext.empty) { context.continueForkContext.add(forkContext.head); const testSegments = context.continueForkContext.makeNext(0, -1); forkContext.replaceHead(testSegments); } }, /** * Makes a code path segment for the test part of a ForStatement. * * @param {boolean|undefined} test - The test value (only when constant). * @returns {void} */ makeForTest: function(test) { const context = this.loopContext; const forkContext = this.forkContext; const endOfInitSegments = forkContext.head; const testSegments = forkContext.makeNext(-1, -1); // Update state. context.test = test; context.endOfInitSegments = endOfInitSegments; context.continueDestSegments = context.testSegments = testSegments; forkContext.replaceHead(testSegments); }, /** * Makes a code path segment for the update part of a ForStatement. * * @returns {void} */ makeForUpdate: function() { const context = this.loopContext; const choiceContext = this.choiceContext; const forkContext = this.forkContext; // Make the next paths of the test. if (context.testSegments) { finalizeTestSegmentsOfFor( context, choiceContext, forkContext.head); } else { context.endOfInitSegments = forkContext.head; } // Update state. const updateSegments = forkContext.makeDisconnected(-1, -1); context.continueDestSegments = context.updateSegments = updateSegments; forkContext.replaceHead(updateSegments); }, /** * Makes a code path segment for the body part of a ForStatement. * * @returns {void} */ makeForBody: function() { const context = this.loopContext; const choiceContext = this.choiceContext; const forkContext = this.forkContext; // Update state. if (context.updateSegments) { context.endOfUpdateSegments = forkContext.head; // `update` -> `test` if (context.testSegments) { makeLooped( this, context.endOfUpdateSegments, context.testSegments); } } else if (context.testSegments) { finalizeTestSegmentsOfFor( context, choiceContext, forkContext.head); } else { context.endOfInitSegments = forkContext.head; } let bodySegments = context.endOfTestSegments; if (!bodySegments) { /* * If there is not the `test` part, the `body` path comes from the * `init` part and the `update` part. */ const prevForkContext = ForkContext.newEmpty(forkContext); prevForkContext.add(context.endOfInitSegments); if (context.endOfUpdateSegments) { prevForkContext.add(context.endOfUpdateSegments); } bodySegments = prevForkContext.makeNext(0, -1); } context.continueDestSegments = context.continueDestSegments || bodySegments; forkContext.replaceHead(bodySegments); }, /** * Makes a code path segment for the left part of a ForInStatement and a * ForOfStatement. * * @returns {void} */ makeForInOfLeft: function() { const context = this.loopContext; const forkContext = this.forkContext; const leftSegments = forkContext.makeDisconnected(-1, -1); // Update state. context.prevSegments = forkContext.head; context.leftSegments = context.continueDestSegments = leftSegments; forkContext.replaceHead(leftSegments); }, /** * Makes a code path segment for the right part of a ForInStatement and a * ForOfStatement. * * @returns {void} */ makeForInOfRight: function() { const context = this.loopContext; const forkContext = this.forkContext; const temp = ForkContext.newEmpty(forkContext); temp.add(context.prevSegments); const rightSegments = temp.makeNext(-1, -1); // Update state. context.endOfLeftSegments = forkContext.head; forkContext.replaceHead(rightSegments); }, /** * Makes a code path segment for the body part of a ForInStatement and a * ForOfStatement. * * @returns {void} */ makeForInOfBody: function() { const context = this.loopContext; const forkContext = this.forkContext; const temp = ForkContext.newEmpty(forkContext); temp.add(context.endOfLeftSegments); const bodySegments = temp.makeNext(-1, -1); // Make a path: `right` -> `left`. makeLooped(this, forkContext.head, context.leftSegments); // Update state. context.brokenForkContext.add(forkContext.head); forkContext.replaceHead(bodySegments); }, //-------------------------------------------------------------------------- // Control Statements //-------------------------------------------------------------------------- /** * Creates new context for BreakStatement. * * @param {boolean} breakable - The flag to indicate it can break by * an unlabeled BreakStatement. * @param {string|null} label - The label of this context. * @returns {Object} The new context. */ pushBreakContext: function(breakable, label) { this.breakContext = { upper: this.breakContext, breakable: breakable, label: label, brokenForkContext: ForkContext.newEmpty(this.forkContext) }; return this.breakContext; }, /** * Removes the top item of the break context stack. * * @returns {Object} The removed context. */ popBreakContext: function() { const context = this.breakContext; const forkContext = this.forkContext; this.breakContext = context.upper; // Process this context here for other than switches and loops. if (!context.breakable) { const brokenForkContext = context.brokenForkContext; if (!brokenForkContext.empty) { brokenForkContext.add(forkContext.head); forkContext.replaceHead(brokenForkContext.makeNext(0, -1)); } } return context; }, /** * Makes a path for a `break` statement. * * It registers the head segment to a context of `break`. * It makes new unreachable segment, then it set the head with the segment. * * @param {string} label - A label of the break statement. * @returns {void} */ makeBreak: function(label) { const forkContext = this.forkContext; if (!forkContext.reachable) { return; } const context = getBreakContext(this, label); /* istanbul ignore else: foolproof (syntax error) */ if (context) { context.brokenForkContext.add(forkContext.head); } forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); }, /** * Makes a path for a `continue` statement. * * It makes a looping path. * It makes new unreachable segment, then it set the head with the segment. * * @param {string} label - A label of the continue statement. * @returns {void} */ makeContinue: function(label) { const forkContext = this.forkContext; if (!forkContext.reachable) { return; } const context = getContinueContext(this, label); /* istanbul ignore else: foolproof (syntax error) */ if (context) { if (context.continueDestSegments) { makeLooped(this, forkContext.head, context.continueDestSegments); // If the context is a for-in/of loop, this effects a break also. if (context.type === "ForInStatement" || context.type === "ForOfStatement" ) { context.brokenForkContext.add(forkContext.head); } } else { context.continueForkContext.add(forkContext.head); } } forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); }, /** * Makes a path for a `return` statement. * * It registers the head segment to a context of `return`. * It makes new unreachable segment, then it set the head with the segment. * * @returns {void} */ makeReturn: function() { const forkContext = this.forkContext; if (forkContext.reachable) { getReturnContext(this).returnedForkContext.add(forkContext.head); forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); } }, /** * Makes a path for a `throw` statement. * * It registers the head segment to a context of `throw`. * It makes new unreachable segment, then it set the head with the segment. * * @returns {void} */ makeThrow: function() { const forkContext = this.forkContext; if (forkContext.reachable) { getThrowContext(this).thrownForkContext.add(forkContext.head); forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); } }, /** * Makes the final path. * @returns {void} */ makeFinal: function() { const segments = this.currentSegments; if (segments.length > 0 && segments[0].reachable) { this.returnedForkContext.add(segments); } } }; module.exports = CodePathState;
mit
fgprodigal/RayUI
Interface/AddOns/IntelliMount/Modules/UtilityMounts.lua
2487
------------------------------------------------------------ -- UtilityMounts.lua -- -- Abin -- 2014/10/21 ------------------------------------------------------------ local GetSpellInfo = GetSpellInfo local wipe = wipe local ipairs = ipairs local GetNumMounts = C_MountJournal.GetNumMounts local GetMountInfo = C_MountJournal.GetMountInfo local _, addon = ... local utilityMounts = { { id = 75973, passenger = 1 }, { id = 121820, passenger = 1 }, { id = 93326, passenger = 1 }, { id = 60424, passenger = 1 }, { id = 61425, passenger = 1, vendor = 1 }, { id = 122708, passenger = 1, vendor = 1 }, { id = 118089, surface = 1 }, { id = 127271, surface = 1 }, { id = 64731, underwater = 1 }, { id = 30174, underwater = 1 }, { id = 98718, underwater = 1 }, } if addon.class == "WARLOCK" then tinsert(utilityMounts, { id = 5784, surface = 1 }) tinsert(utilityMounts, { id = 23161, surface = 1 }) end local LEARNED_MOUNTS = {} do local _, data for _, data in ipairs(utilityMounts) do data.name, _, data.icon = GetSpellInfo(data.id) end sort(utilityMounts, function(a, b) return (a.name or "") < (b.name or "") end) -- Sort the table by mount names end addon:RegisterDebugAttr("surfaceMount") function addon:UpdateUtilityMounts() wipe(LEARNED_MOUNTS) local count = GetNumMounts() local i for i = 1, count do local name, _, _, _, _, _, _, _, _, hideOnChar, isCollected = C_MountJournal.GetDisplayedMountInfo(i) if name and not hideOnChar and isCollected then LEARNED_MOUNTS[name] = 1 end end local _, data for _, data in ipairs(utilityMounts) do data.learned = LEARNED_MOUNTS[data.name] end end function addon:GetNumUtilityMounts() return #utilityMounts end function addon:GetUtilityMountData(index) return utilityMounts[index] end function addon:IsMountLearned(name) return LEARNED_MOUNTS[name] end addon:RegisterEventCallback("OnInitialize", function(db) -- Transfer old version data to new one if addon.db.waterStrider then addon.db.surfaceMount = addon.db.waterStrider addon.db.waterStrider = nil end if addon.db.surfaceMount and not addon.db.warlockSurfaceMount then addon.db.warlockSurfaceMount = addon.db.surfaceMount end if addon.class == "WARLOCK" then addon:SetAttribute("surfaceMount", addon.db.warlockSurfaceMount) else addon:SetAttribute("surfaceMount", addon.db.surfaceMount) end end) addon:RegisterOptionCallback("surfaceIfNotFlable", function(value) addon:SetAttribute("surfaceIfNotFlable", value) end)
mit
QQorp/QQat
front-src/js/Message.js
299
import React from 'react'; var Message = React.createClass({ render: function() { return ( <div className="Message"> <h3 className="messageAuthor" > {this.props.author} </h3> {this.props.children} </div> ); } }); module.exports = Message;
mit
hashrocket/localpolitics.in
db/migrate/20090326141831_create_senator_comparisons.rb
294
class CreateSenatorComparisons < ActiveRecord::Migration def self.up create_table :senator_comparisons do |t| t.integer :govtrack_id_1 t.integer :govtrack_id_2 t.text :body t.timestamps end end def self.down drop_table :senator_comparisons end end
mit
cdrttn/fragmon
OptionsDlg.cpp
3153
/* ** Copyright (c) 2006 Christopher Davis ** ** Permission is hereby granted, free of charge, to any person obtaining a copy of ** this software and associated documentation files (the "Software"), to deal in ** the Software without restriction, including without limitation the rights to ** use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of ** the Software, and to permit persons to whom the Software is furnished to do so, ** subject to the following conditions: ** ** The above copyright notice and this permission notice shall be included in all ** copies or substantial portions of the Software. ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS ** FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR ** COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER ** IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN ** CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ** ** $Id$ */ #include "wx/wx.h" #include "OptionsDlg.h" #include "CopyFmt.h" #include "ExecInput.h" #include "QueryOpts.h" #include "BroadcastFmt.h" BEGIN_EVENT_TABLE(OptionsDlg, wxDialog) EVT_BUTTON(wxID_OK, OptionsDlg::OnButtonHandler) EVT_BUTTON(wxID_APPLY, OptionsDlg::OnButtonHandler) EVT_BUTTON(wxID_CLOSE, OptionsDlg::OnButtonHandler) //EVT_NOTEBOOK_PAGE_CHANGED(-1, OptionsDlg::OnPage) END_EVENT_TABLE() OptionsDlg::OptionsDlg(wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style, const wxString& name) : wxDialog(parent, id, title, pos, size, style, name) { wxBoxSizer *box = new wxBoxSizer(wxVERTICAL); wxBoxSizer *buttons = new wxBoxSizer(wxHORIZONTAL); m_pages = new wxNotebook(this, -1); m_pages->AddPage(new QueryOpts(m_pages, -1), "Query Options"); m_pages->AddPage(new ExecInput(m_pages, -1), "Game Paths"); m_pages->AddPage(new CopyFmt(m_pages, -1), "Copy Format"); m_pages->AddPage(new BroadcastFmt(m_pages, -1), "Broadcast Format"); //m_current = m_pages->GetCurrentPage(); buttons->Add(new wxButton(this, wxID_APPLY)); buttons->AddSpacer(10); buttons->Add(new wxButton(this, wxID_OK)); buttons->AddSpacer(10); buttons->Add(new wxButton(this, wxID_CLOSE)); box->Add(m_pages, 1, wxEXPAND); box->AddSpacer(15); box->Add(buttons, 0, wxALIGN_CENTER); SetSizerAndFit(box); } void OptionsDlg::OnButtonHandler(wxCommandEvent &evt) { evt.StopPropagation(); if (evt.GetId() == wxID_OK) //apply on all windows { evt.SetId(wxID_APPLY); for (int i = 0; i < m_pages->GetPageCount(); i++) m_pages->GetPage(i)->ProcessEvent(evt); EndModal(wxID_OK); } else if (evt.GetId() == wxID_CLOSE) EndModal(wxID_CLOSE); else m_pages->GetCurrentPage()->ProcessEvent(evt); } /*void OptionsDlg::OnPage(wxNotebookEvent &evt) { m_current = m_pages->GetCurrentPage(); }*/
mit
helinjiang/nodeadmin
www/static/plugins/editor.md/lib/codemirror/addon/hint/css-hint.js
2019
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("common/plugins/editor.md/lib/codemirror/lib/codemirror"), require("common/plugins/editor.md/lib/codemirror/mode/css/css")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../../mode/css/css"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; var pseudoClasses = {link: 1, visited: 1, active: 1, hover: 1, focus: 1, "first-letter": 1, "first-line": 1, "first-child": 1, before: 1, after: 1, lang: 1}; CodeMirror.registerHelper("hint", "css", function(cm) { var cur = cm.getCursor(), token = cm.getTokenAt(cur); var inner = CodeMirror.innerMode(cm.getMode(), token.state); if (inner.mode.name != "css") return; var start = token.start, end = cur.ch, word = token.string.slice(0, end - start); if (/[^\w$_-]/.test(word)) { word = ""; start = end = cur.ch; } var spec = CodeMirror.resolveMode("text/css"); var result = []; function add(keywords) { for (var name in keywords) if (!word || name.lastIndexOf(word, 0) == 0) result.push(name); } var st = inner.state.state; if (st == "pseudo" || token.type == "variable-3") { add(pseudoClasses); } else if (st == "block" || st == "maybeprop") { add(spec.propertyKeywords); } else if (st == "prop" || st == "parens" || st == "at" || st == "params") { add(spec.valueKeywords); add(spec.colorKeywords); } else if (st == "media" || st == "media_parens") { add(spec.mediaTypes); add(spec.mediaFeatures); } if (result.length) return { list: result, from: CodeMirror.Pos(cur.line, start), to: CodeMirror.Pos(cur.line, end) }; }); });
mit
htna/HCsbLib
HCsbLib/HCsbLib/HTLib3/Core/Collection/Collections.HToListByItemN.cs
2142
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace HTLib3 { public static partial class Collections { public static List<T1> HToListByItem1<T1, T2>(this IList<Tuple<T1, T2>> list) { T1[] items = new T1[list.Count]; for(int i=0; i<list.Count; i++) items[i]=list[i].Item1; return new List<T1>(items); } public static List<T2> HToListByItem2<T1, T2>(this IList<Tuple<T1, T2>> list) { T2[] items = new T2[list.Count]; for(int i=0; i<list.Count; i++) items[i]=list[i].Item2; return new List<T2>(items); } public static List<T1> HToListByItem1<T1, T2, T3>(this IList<Tuple<T1, T2, T3>> list) { T1[] items = new T1[list.Count]; for(int i=0; i<list.Count; i++) items[i]=list[i].Item1; return new List<T1>(items); } public static List<T2> HToListByItem2<T1, T2, T3>(this IList<Tuple<T1, T2, T3>> list) { T2[] items = new T2[list.Count]; for(int i=0; i<list.Count; i++) items[i]=list[i].Item2; return new List<T2>(items); } public static List<T3> HToListByItem3<T1, T2, T3>(this IList<Tuple<T1, T2, T3>> list) { T3[] items = new T3[list.Count]; for(int i=0; i<list.Count; i++) items[i]=list[i].Item3; return new List<T3>(items); } public static List<T1> HToListByItem1<T1, T2, T3, T4>(this IList<Tuple<T1, T2, T3, T4>> list) { T1[] items = new T1[list.Count]; for(int i=0; i<list.Count; i++) items[i]=list[i].Item1; return new List<T1>(items); } public static List<T2> HToListByItem2<T1, T2, T3, T4>(this IList<Tuple<T1, T2, T3, T4>> list) { T2[] items = new T2[list.Count]; for(int i=0; i<list.Count; i++) items[i]=list[i].Item2; return new List<T2>(items); } public static List<T3> HToListByItem3<T1, T2, T3, T4>(this IList<Tuple<T1, T2, T3, T4>> list) { T3[] items = new T3[list.Count]; for(int i=0; i<list.Count; i++) items[i]=list[i].Item3; return new List<T3>(items); } public static List<T4> HToListByItem4<T1, T2, T3, T4>(this IList<Tuple<T1, T2, T3, T4>> list) { T4[] items = new T4[list.Count]; for(int i=0; i<list.Count; i++) items[i]=list[i].Item4; return new List<T4>(items); } } }
mit
ryanmitchener/web-build
example/src/test-target/js/constants.js
22
var TEST = "test-var";
mit
EduardAl/Proyectos-Visual-Studio
ACOPEDH/ACOPEDH/Nueva Imagen.Designer.cs
13571
namespace ACOPEDH { partial class Nueva_Imagen { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Nueva_Imagen)); this.bttSeleccionar = new System.Windows.Forms.Button(); this.label2 = new System.Windows.Forms.Label(); this.cbTipoImagen = new System.Windows.Forms.ComboBox(); this.label3 = new System.Windows.Forms.Label(); this.txtComentarios = new System.Windows.Forms.RichTextBox(); this.bttGuardar = new System.Windows.Forms.Button(); this.pbNuevaImagen = new System.Windows.Forms.PictureBox(); this.pictureBox3 = new System.Windows.Forms.PictureBox(); this.BarraTítulo = new System.Windows.Forms.Label(); this.odNuevaImagen = new System.Windows.Forms.OpenFileDialog(); this.bttCer = new System.Windows.Forms.PictureBox(); this.bttMax = new System.Windows.Forms.PictureBox(); this.gbDatos = new System.Windows.Forms.GroupBox(); ((System.ComponentModel.ISupportInitialize)(this.pbNuevaImagen)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.bttCer)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.bttMax)).BeginInit(); this.gbDatos.SuspendLayout(); this.SuspendLayout(); // // bttSeleccionar // this.bttSeleccionar.Anchor = System.Windows.Forms.AnchorStyles.Right; this.bttSeleccionar.Font = new System.Drawing.Font("Linotte-Bold", 10F); this.bttSeleccionar.Location = new System.Drawing.Point(48, 24); this.bttSeleccionar.Name = "bttSeleccionar"; this.bttSeleccionar.Size = new System.Drawing.Size(158, 31); this.bttSeleccionar.TabIndex = 0; this.bttSeleccionar.Text = "Seleccionar Imagen..."; this.bttSeleccionar.UseVisualStyleBackColor = true; this.bttSeleccionar.Click += new System.EventHandler(this.bttSeleccionar_Click); // // label2 // this.label2.Anchor = System.Windows.Forms.AnchorStyles.Right; this.label2.AutoSize = true; this.label2.BackColor = System.Drawing.Color.Transparent; this.label2.Location = new System.Drawing.Point(86, 82); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(97, 19); this.label2.TabIndex = 3; this.label2.Text = "Tipo Imagen"; // // cbTipoImagen // this.cbTipoImagen.Anchor = System.Windows.Forms.AnchorStyles.Right; this.cbTipoImagen.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbTipoImagen.FormattingEnabled = true; this.cbTipoImagen.Location = new System.Drawing.Point(21, 105); this.cbTipoImagen.Name = "cbTipoImagen"; this.cbTipoImagen.Size = new System.Drawing.Size(213, 27); this.cbTipoImagen.TabIndex = 1; // // label3 // this.label3.Anchor = System.Windows.Forms.AnchorStyles.Right; this.label3.AutoSize = true; this.label3.BackColor = System.Drawing.Color.Transparent; this.label3.Location = new System.Drawing.Point(44, 154); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(176, 19); this.label3.TabIndex = 5; this.label3.Text = "Comentarios (Opcional)"; // // txtComentarios // this.txtComentarios.Anchor = System.Windows.Forms.AnchorStyles.Right; this.txtComentarios.Location = new System.Drawing.Point(21, 180); this.txtComentarios.MaxLength = 120; this.txtComentarios.Name = "txtComentarios"; this.txtComentarios.Size = new System.Drawing.Size(213, 70); this.txtComentarios.TabIndex = 2; this.txtComentarios.Text = ""; // // bttGuardar // this.bttGuardar.Anchor = System.Windows.Forms.AnchorStyles.Right; this.bttGuardar.Location = new System.Drawing.Point(88, 286); this.bttGuardar.Name = "bttGuardar"; this.bttGuardar.Size = new System.Drawing.Size(95, 42); this.bttGuardar.TabIndex = 3; this.bttGuardar.Text = "Guardar"; this.bttGuardar.UseVisualStyleBackColor = true; this.bttGuardar.Click += new System.EventHandler(this.bttGuardar_Click); // // pbNuevaImagen // this.pbNuevaImagen.BackColor = System.Drawing.Color.LightGray; this.pbNuevaImagen.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; this.pbNuevaImagen.Location = new System.Drawing.Point(22, 49); this.pbNuevaImagen.Name = "pbNuevaImagen"; this.pbNuevaImagen.Size = new System.Drawing.Size(293, 384); this.pbNuevaImagen.TabIndex = 0; this.pbNuevaImagen.TabStop = false; // // pictureBox3 // this.pictureBox3.BackColor = System.Drawing.Color.Transparent; this.pictureBox3.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("pictureBox3.BackgroundImage"))); this.pictureBox3.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.pictureBox3.Location = new System.Drawing.Point(4, 0); this.pictureBox3.Name = "pictureBox3"; this.pictureBox3.Size = new System.Drawing.Size(30, 30); this.pictureBox3.TabIndex = 124; this.pictureBox3.TabStop = false; // // BarraTítulo // this.BarraTítulo.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.BarraTítulo.BackColor = System.Drawing.Color.Transparent; this.BarraTítulo.Font = new System.Drawing.Font("Gotham Narrow Medium", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.BarraTítulo.Image = ((System.Drawing.Image)(resources.GetObject("BarraTítulo.Image"))); this.BarraTítulo.Location = new System.Drawing.Point(0, 0); this.BarraTítulo.Name = "BarraTítulo"; this.BarraTítulo.Size = new System.Drawing.Size(620, 30); this.BarraTítulo.TabIndex = 1; this.BarraTítulo.Text = " ACOPEDH - Nueva Imagen"; this.BarraTítulo.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // odNuevaImagen // this.odNuevaImagen.FileName = "openFileDialog1"; this.odNuevaImagen.Filter = "Archivos JPG|*.jpg|Archivos PNG|*.png|Archivos GIF|.gif"; this.odNuevaImagen.ShowHelp = true; this.odNuevaImagen.Title = "Seleccione una imagen..."; // // bttCer // this.bttCer.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.bttCer.BackColor = System.Drawing.Color.Transparent; this.bttCer.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("bttCer.BackgroundImage"))); this.bttCer.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; this.bttCer.Image = ((System.Drawing.Image)(resources.GetObject("bttCer.Image"))); this.bttCer.Location = new System.Drawing.Point(590, 0); this.bttCer.Name = "bttCer"; this.bttCer.Size = new System.Drawing.Size(30, 26); this.bttCer.TabIndex = 125; this.bttCer.TabStop = false; this.bttCer.Click += new System.EventHandler(this.bttCancelar_Click); // // bttMax // this.bttMax.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.bttMax.BackColor = System.Drawing.Color.Transparent; this.bttMax.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("bttMax.BackgroundImage"))); this.bttMax.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; this.bttMax.Image = ((System.Drawing.Image)(resources.GetObject("bttMax.Image"))); this.bttMax.Location = new System.Drawing.Point(563, 0); this.bttMax.Name = "bttMax"; this.bttMax.Size = new System.Drawing.Size(30, 26); this.bttMax.TabIndex = 126; this.bttMax.TabStop = false; this.bttMax.Click += new System.EventHandler(this.bttMax_Click); // // gbDatos // this.gbDatos.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom))); this.gbDatos.BackColor = System.Drawing.Color.Transparent; this.gbDatos.Controls.Add(this.bttGuardar); this.gbDatos.Controls.Add(this.txtComentarios); this.gbDatos.Controls.Add(this.label3); this.gbDatos.Controls.Add(this.cbTipoImagen); this.gbDatos.Controls.Add(this.label2); this.gbDatos.Controls.Add(this.bttSeleccionar); this.gbDatos.Location = new System.Drawing.Point(338, 49); this.gbDatos.Name = "gbDatos"; this.gbDatos.Size = new System.Drawing.Size(254, 383); this.gbDatos.TabIndex = 127; this.gbDatos.TabStop = false; // // Nueva_Imagen // this.AcceptButton = this.bttGuardar; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None; this.BackgroundImage = global::ACOPEDH.Properties.Resources.Fondo_Lalalala; this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.ClientSize = new System.Drawing.Size(620, 448); this.Controls.Add(this.gbDatos); this.Controls.Add(this.bttCer); this.Controls.Add(this.bttMax); this.Controls.Add(this.pictureBox3); this.Controls.Add(this.BarraTítulo); this.Controls.Add(this.pbNuevaImagen); this.DoubleBuffered = true; this.Font = new System.Drawing.Font("Linotte-Bold", 12F); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "Nueva_Imagen"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Nueva Imagen"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Nueva_Imagen_FormClosing); this.Load += new System.EventHandler(this.Nueva_Imagen_Load); this.SizeChanged += new System.EventHandler(this.Nueva_Imagen_SizeChanged); ((System.ComponentModel.ISupportInitialize)(this.pbNuevaImagen)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.bttCer)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.bttMax)).EndInit(); this.gbDatos.ResumeLayout(false); this.gbDatos.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.PictureBox pbNuevaImagen; private System.Windows.Forms.Button bttSeleccionar; private System.Windows.Forms.Label label2; private System.Windows.Forms.ComboBox cbTipoImagen; private System.Windows.Forms.Label label3; private System.Windows.Forms.RichTextBox txtComentarios; private System.Windows.Forms.Button bttGuardar; private System.Windows.Forms.PictureBox pictureBox3; private System.Windows.Forms.Label BarraTítulo; private System.Windows.Forms.OpenFileDialog odNuevaImagen; private System.Windows.Forms.PictureBox bttCer; private System.Windows.Forms.PictureBox bttMax; private System.Windows.Forms.GroupBox gbDatos; } }
mit
gatsbyjs/gatsby
packages/gatsby-design-tokens/src/transition.js
309
export const transition = { default: `250ms cubic-bezier(0.4, 0, 0.2, 1)`, curve: { default: `cubic-bezier(0.4, 0, 0.2, 1)`, fastOutLinearIn: `cubic-bezier(0.4, 0, 1, 1)`, }, speed: { faster: `50ms`, fast: `100ms`, default: `250ms`, slow: `500ms`, slower: `1000ms`, }, }
mit
b4k3r/cloudflare
lib/cloudflare/representation.rb
2668
# frozen_string_literal: true # Copyright, 2012, by Marcin Prokop. # Copyright, 2017, by Samuel G. D. Williams. <http://www.codeotaku.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'json' require 'async/rest/representation' module Cloudflare class RequestError < StandardError def initialize(resource, errors) super("#{resource}: #{errors.map{|attributes| attributes[:message]}.join(', ')}") @representation = representation end attr_reader :representation end class Message def initialize(response) @response = response @body = response.read # Some endpoints return the value instead of a message object (like KV reads) @body = { success: true, result: @body } unless @body.is_a?(Hash) end attr :response attr :body def headers @response.headers end def result @body[:result] end def read @body[:result] end def results Array(result) end def errors @body[:errors] end def messages @body[:messages] end def success? @body[:success] end end class Representation < Async::REST::Representation def process_response(*) message = Message.new(super) unless message.success? raise RequestError.new(@resource, message.errors) end return message end def representation Representation end def represent(metadata, attributes) resource = @resource.with(path: attributes[:id]) representation.new(resource, metadata: metadata, value: attributes) end def represent_message(message) represent(message.headers, message.result) end def to_hash if value.is_a?(Hash) return value end end end end
mit
lambdax-x/surt
src/stable/counting.rs
892
pub fn sort<T: Copy, F>(k: usize, v: &mut [T], rank: F) where F: Fn(&T) -> usize { let count_len = k + 1; let mut count: Vec<usize> = vec![0; count_len]; { let v_ranked = v.iter().map(|x| rank(x)); for i in v_ranked { count[i] += 1; } } /// count[i]: number of occurences of i in v.map(rank) for i in 1 .. count_len { count[i] += count[i - 1]; } /// count[i]: number of occurences less or equal than i in v.map(rank) let mut w: Vec<Option<T>> = vec![None; v.len()]; { let v_ranked = v.iter().map(|x| rank(x)); for (e, i) in v.iter().zip(v_ranked).rev() { w[count[i] - 1] = Some(e.clone()); count[i] -= 1; } } for (to, from) in v.iter_mut().zip(w.iter()) { match *from { Some(a) => *to = a, _ => {} } } }
mit
Michal-Fularz/decision_tree
decision_trees/gridsearch.py
7573
from typing import List import datetime import numpy as np from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor from sklearn.model_selection import GridSearchCV, ParameterGrid, PredefinedSplit from sklearn.tree import DecisionTreeClassifier # TODO(MF): original parfit did not work correctly with our data # from parfit.parfit import bestFit, plotScores from decision_trees.own_parfit.parfit import bestFit from decision_trees.utils.constants import ClassifierType from decision_trees.utils.constants import GridSearchType from decision_trees.utils.constants import get_classifier, get_tuned_parameters from decision_trees.utils.convert_to_fixed_point import quantize_data def perform_gridsearch(train_data: np.ndarray, train_target: np.ndarray, test_data: np.ndarray, test_target: np.ndarray, number_of_bits_per_feature_to_test: List[int], clf_type: ClassifierType, gridsearch_type: GridSearchType, path: str, name: str ): filename_with_path = path + '/' + datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S') \ + '_' + name + '_' + clf_type.name + '_gridsearch_results.txt' # first train on the non-quantized data if gridsearch_type == GridSearchType.SCIKIT: best_model, best_score = _scikit_gridsearch(train_data, train_target, test_data, test_target, clf_type) elif gridsearch_type == GridSearchType.PARFIT: best_model, best_score = _parfit_gridsearch(train_data, train_target, test_data, test_target, clf_type, False) elif gridsearch_type == GridSearchType.NONE: best_model, best_score = _none_gridsearch(train_data, train_target, test_data, test_target, clf_type) else: raise ValueError('Requested GridSearchType is not available') print('No quantization - full resolution') with open(filename_with_path, 'a') as f: print('No quantization - full resolution', file=f) _save_score_and_model_to_file(best_score, best_model, filename_with_path) # repeat on quantized data with different number of bits for bit_width in number_of_bits_per_feature_to_test: train_data_quantized, test_data_quantized = quantize_data( train_data, test_data, bit_width, flag_save_details_to_file=False, path='./../../data/' ) if gridsearch_type == GridSearchType.SCIKIT: best_model, best_score = _scikit_gridsearch( train_data_quantized, train_target, test_data, test_target, clf_type ) elif gridsearch_type == GridSearchType.PARFIT: best_model, best_score = _parfit_gridsearch( train_data_quantized, train_target, test_data_quantized, test_target, clf_type, show_plot=False ) elif gridsearch_type == GridSearchType.NONE: best_model, best_score = _none_gridsearch( train_data_quantized, train_target, test_data, test_target, clf_type ) else: raise ValueError('Requested GridSearchType is not available') print(f'number of bits: {bit_width}') with open(filename_with_path, 'a') as f: print(f'number of bits: {bit_width}', file=f) _save_score_and_model_to_file(best_score, best_model, filename_with_path) def _save_score_and_model_to_file(score, model, filename: str): print(f"f1: {score:{1}.{5}}: {model}") with open(filename, "a") as f: print(f"f1: {score:{1}.{5}}: {model}", file=f) # this should use the whole data available to find best parameters. So pass both train and test data, find parameters # and then retrain with found parameters on train data def _scikit_gridsearch( train_data: np.ndarray, train_target: np.ndarray, test_data: np.ndarray, test_target: np.ndarray, clf_type: ClassifierType ): # perform grid search to find best parameters scores = ['neg_mean_squared_error'] if clf_type == ClassifierType.RANDOM_FOREST_REGRESSOR else ['f1_weighted'] # alternatives: http://scikit-learn.org/stable/modules/model_evaluation.html#common-cases-predefined-values tuned_parameters = get_tuned_parameters(clf_type) # for score in scores: score = scores[0] # print("# Tuning hyper-parameters for %s" % score) # print() # TODO: important note - this does not use test data to evaluate, instead it probably splits the train data # internally, which means that the final score will be calculated on this data and is different than the one # calculated on test data data = np.concatenate((train_data, test_data)) target = np.concatenate((train_target, test_target)) labels = np.full((len(data),), -1, dtype=np.int8) labels[len(train_data):] = 1 cv = PredefinedSplit(labels) if clf_type == ClassifierType.DECISION_TREE: clf = GridSearchCV(DecisionTreeClassifier(), tuned_parameters, cv=cv, scoring=score, n_jobs=3) elif clf_type == ClassifierType.RANDOM_FOREST: clf = GridSearchCV(RandomForestClassifier(), tuned_parameters, cv=cv, scoring=score, n_jobs=3) elif clf_type == ClassifierType.RANDOM_FOREST_REGRESSOR: clf = GridSearchCV(RandomForestRegressor(), tuned_parameters, cv=cv, scoring=score, n_jobs=3) else: raise ValueError('Unknown classifier type specified') clf = clf.fit(data, target) # print("Best parameters set found on development set:") # print(clf.best_params_) # print() # print("Grid scores on development set:") # for mean, std, params in zip( # clf.cv_results_['mean_test_score'], # clf.cv_results_['std_test_score'], # clf.cv_results_['params'] # ): # print("%0.3f (+/-%0.03f) for %r" # % (mean, std * 2, params)) # print() return clf.best_params_, clf.best_score_ def _none_gridsearch( train_data: np.ndarray, train_target: np.ndarray, test_data: np.ndarray, test_target: np.ndarray, clf_type: ClassifierType ): clf = get_classifier(clf_type) clf = clf.fit(train_data, train_target) return clf.get_params(), clf.score(test_data, test_target) # TODO(MF): check parfit module for parameters search # https://medium.com/mlreview/parfit-hyper-parameter-optimization-77253e7e175e def _parfit_gridsearch( train_data: np.ndarray, train_target: np.ndarray, test_data: np.ndarray, test_target: np.ndarray, clf_type: ClassifierType, show_plot: bool ): grid = get_tuned_parameters(clf_type) if clf_type == ClassifierType.DECISION_TREE: model = DecisionTreeClassifier elif clf_type == ClassifierType.RANDOM_FOREST: model = RandomForestClassifier else: raise ValueError("Unknown classifier type specified") from sklearn import metrics best_model, best_score, all_models, all_scores = bestFit(model, ParameterGrid(grid), train_data, train_target, test_data, test_target, predictType='predict', metric=metrics.f1_score, bestScore='max', scoreLabel='f1_weighted', showPlot=show_plot) return best_model, best_score
mit
MartinKamenov/Pastoral-Shrews-AngularJS
PastoralShrews/src/app/share/directives/hightlight.directive.ts
538
import { Directive, ElementRef, HostListener, Input } from '@angular/core'; @Directive({ selector: '[appMyHighlight]' }) export class HighlightDirective { constructor(private el: ElementRef) { } @Input() defaultColor: string; @HostListener('mouseenter') onMouseEnter() { this.highlight(this.defaultColor || '#555'); } @HostListener('mouseleave') onMouseLeave() { this.highlight(null); } private highlight(color: string) { this.el.nativeElement.style.backgroundColor = color; } }
mit
sgt39007/waji_redux
app/js/redux/store/configureStore.prod.js
361
import { createStore, applyMiddleware} from 'redux' import thunk from 'redux-thunk' import rootReducer from '../reducers' import { apiMiddleware } from 'redux-api-middleware'; export default function configureStore(initialState) { const store = createStore( rootReducer, initialState, applyMiddleware(thunk, apiMiddleware) ); return store }
mit
superiorcoin/superiorcoin
src/qt/paymentserver.cpp
4513
// Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <QApplication> #include "paymentserver.h" #include "guiconstants.h" #include "ui_interface.h" #include "util.h" #include <QByteArray> #include <QDataStream> #include <QDebug> #include <QFileOpenEvent> #include <QHash> #include <QLocalServer> #include <QLocalSocket> #include <QStringList> #if QT_VERSION < 0x050000 #include <QUrl> #endif using namespace boost; const int BITCOIN_IPC_CONNECT_TIMEOUT = 1000; // milliseconds const QString BITCOIN_IPC_PREFIX("superiorcoin:"); // // Create a name that is unique for: // testnet / non-testnet // data directory // static QString ipcServerName() { QString name("BitcoinQt"); // Append a simple hash of the datadir // Note that GetDataDir(true) returns a different path // for -testnet versus main net QString ddir(GetDataDir(true).string().c_str()); name.append(QString::number(qHash(ddir))); return name; } // // This stores payment requests received before // the main GUI window is up and ready to ask the user // to send payment. // static QStringList savedPaymentRequests; // // Sending to the server is done synchronously, at startup. // If the server isn't already running, startup continues, // and the items in savedPaymentRequest will be handled // when uiReady() is called. // bool PaymentServer::ipcSendCommandLine() { bool fResult = false; const QStringList& args = qApp->arguments(); for (int i = 1; i < args.size(); i++) { if (!args[i].startsWith(BITCOIN_IPC_PREFIX, Qt::CaseInsensitive)) continue; savedPaymentRequests.append(args[i]); } foreach (const QString& arg, savedPaymentRequests) { QLocalSocket* socket = new QLocalSocket(); socket->connectToServer(ipcServerName(), QIODevice::WriteOnly); if (!socket->waitForConnected(BITCOIN_IPC_CONNECT_TIMEOUT)) return false; QByteArray block; QDataStream out(&block, QIODevice::WriteOnly); out.setVersion(QDataStream::Qt_4_0); out << arg; out.device()->seek(0); socket->write(block); socket->flush(); socket->waitForBytesWritten(BITCOIN_IPC_CONNECT_TIMEOUT); socket->disconnectFromServer(); delete socket; fResult = true; } return fResult; } PaymentServer::PaymentServer(QApplication* parent) : QObject(parent), saveURIs(true) { // Install global event filter to catch QFileOpenEvents on the mac (sent when you click bitcoin: links) parent->installEventFilter(this); QString name = ipcServerName(); // Clean up old socket leftover from a crash: QLocalServer::removeServer(name); uriServer = new QLocalServer(this); if (!uriServer->listen(name)) qDebug() << tr("Cannot start superiorcoin: click-to-pay handler"); else connect(uriServer, SIGNAL(newConnection()), this, SLOT(handleURIConnection())); } bool PaymentServer::eventFilter(QObject *object, QEvent *event) { // clicking on bitcoin: URLs creates FileOpen events on the Mac: if (event->type() == QEvent::FileOpen) { QFileOpenEvent* fileEvent = static_cast<QFileOpenEvent*>(event); if (!fileEvent->url().isEmpty()) { if (saveURIs) // Before main window is ready: savedPaymentRequests.append(fileEvent->url().toString()); else emit receivedURI(fileEvent->url().toString()); return true; } } return false; } void PaymentServer::uiReady() { saveURIs = false; foreach (const QString& s, savedPaymentRequests) emit receivedURI(s); savedPaymentRequests.clear(); } void PaymentServer::handleURIConnection() { QLocalSocket *clientConnection = uriServer->nextPendingConnection(); while (clientConnection->bytesAvailable() < (int)sizeof(quint32)) clientConnection->waitForReadyRead(); connect(clientConnection, SIGNAL(disconnected()), clientConnection, SLOT(deleteLater())); QDataStream in(clientConnection); in.setVersion(QDataStream::Qt_4_0); if (clientConnection->bytesAvailable() < (int)sizeof(quint16)) { return; } QString message; in >> message; if (saveURIs) savedPaymentRequests.append(message); else emit receivedURI(message); }
mit
sleepyparadox/EpicCheckersBot
Source/EpicCheckersBot/Checkers/Move.cs
526
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EpicCheckersBot.Checkers { public struct Move { public BoardPoint From; public BoardPoint To; public Move(BoardPoint from, BoardPoint to) { From = from; To = to; } public override string ToString() { return string.Format("from {0} to {1}", From, To); } } }
mit
w-y/ecma262-jison
examples/website/src/parsers/glsl/index.js
203
import './codemirror-mode/glsl'; export const id = 'glsl'; export const displayName = 'GLSL'; export const mimeTypes = ['x-shader/x-vertex', 'x-shader/x-fragment']; export const fileExtension = 'glsl';
mit
MacTynow/manja
src/Manja/SourcingBundle/Entity/StoneVariety.php
1960
<?php namespace Manja\SourcingBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * StoneVariety * * @ORM\Table(name="STONE_VARIETY") * @ORM\Entity */ class StoneVariety { /** * @var string * * @ORM\Column(name="Variety", type="string", length=45, nullable=false) */ private $variety; /** * @var string * * @ORM\Column(name="Family", type="string", length=45, nullable=false) */ private $family; /** * @var float * * @ORM\Column(name="SG", type="float", nullable=false) */ private $sg; /** * @var integer * * @ORM\Column(name="idSTONE_VARIETY", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $idstoneVariety; /** * Set variety * * @param string $variety * @return StoneVariety */ public function setVariety($variety) { $this->variety = $variety; return $this; } /** * Get variety * * @return string */ public function getVariety() { return $this->variety; } /** * Set family * * @param string $family * @return StoneVariety */ public function setFamily($family) { $this->family = $family; return $this; } /** * Get family * * @return string */ public function getFamily() { return $this->family; } /** * Set sg * * @param float $sg * @return StoneVariety */ public function setSg($sg) { $this->sg = $sg; return $this; } /** * Get sg * * @return float */ public function getSg() { return $this->sg; } /** * Get idstoneVariety * * @return integer */ public function getIdstoneVariety() { return $this->idstoneVariety; } }
mit
Kailashrb/Jep
src/org/lsmp/djep/groupJep/GroupI.java
1401
/* @author rich * Created on 05-Mar-2004 * * This code is covered by a Creative Commons * Attribution, Non Commercial, Share Alike license * <a href="http://creativecommons.org/licenses/by-nc-sa/1.0">License</a> */ package org.lsmp.djep.groupJep; import org.nfunk.jep.type.*; import org.nfunk.jep.*; /** * Represents a group with an identity, and addition operator. * * @author Rich Morris * Created on 05-Mar-2004 */ public interface GroupI { /** Returns the identity element under + */ public Number getZERO(); /** Get Inverse of a number */ public Number getInverse(Number num); /** Get sum of the numbers */ public Number add(Number a,Number b); /** Get the difference of the numbers. * i.e. a + (-b) */ public Number sub(Number a,Number b); /** whether two numbers are equal */ public boolean equals(Number a,Number b); /** returns number given by the string */ public Number valueOf(String s); /** returns a number factory for creating group elements from strings. * Most groups which are subclasses of {@link org.lsmp.djep.groupJep.groups.Group Group} do not need to * implement this method. */ public NumberFactory getNumberFactory(); /** adds the standard constants for this group */ public void addStandardConstants(JEP j); /** adds the standard function for this group */ public void addStandardFunctions(JEP j); }
mit
jzxchiang/mhacks2014
config/env/development.js
1370
'use strict'; module.exports = { db: 'mongodb://localhost/mhacks2014-dev', app: { title: 'mhacks2014 - Development Environment' }, facebook: { clientID: process.env.FACEBOOK_ID || 'APP_ID', clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/facebook/callback' }, twitter: { clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY', clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET', callbackURL: 'http://localhost:3000/auth/twitter/callback' }, google: { clientID: process.env.GOOGLE_ID || 'APP_ID', clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/google/callback' }, linkedin: { clientID: process.env.LINKEDIN_ID || 'APP_ID', clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/linkedin/callback' }, github: { clientID: process.env.GITHUB_ID || 'APP_ID', clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/github/callback' }, mailer: { from: process.env.MAILER_FROM || 'MAILER_FROM', options: { service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER', auth: { user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID', pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD' } } } };
mit
erik-sn/formcontrol
app/src/components/inputs/input_small.tsx
2803
import * as _ from "lodash"; import * as React from "react"; import { Panel, ReducerAction } from "../../../src/utils/interfaces"; import Icon from "../utility/icon"; import Checkbox from "./checkbox"; import DateTimePicker from "./datetimepicker"; export interface Props { panel: Panel; close: (id: string) => void; settings: (id: string, event: React.MouseEvent<{}>) => void; update: (panel: Panel) => ReducerAction; disabled: boolean; } interface State { panel: Panel; } export default class Input extends React.Component<Props, State> { /** * Creates an instance of Input. * * @param {Props} props */ constructor(props: Props) { super(props); this.state = { panel: props.panel, }; this.updateLabel = this.updateLabel.bind(this); } /** * Update the label of the Input component * * @param {ChangeEvent} e */ public updateLabel(e: React.FormEvent<{}>): void { const panel = _.cloneDeep(this.state.panel); const target = e.target as HTMLSelectElement; panel.config.label = target.value; this.setState({ panel }); this.props.update(panel); } /** * Return the type of input to be used in the form depending on the type * * @param {string} type - type of input panel * @param {string} label - label of the panel * @returns {JSX.Element} * * @memberOf Input */ public getType(panel: Panel, label: string): JSX.Element { switch (panel.type) { case "date": case "time": return ( <DateTimePicker onChange={undefined} value={undefined} panel={panel} className="design-input-field" disabled /> ); case "checkbox": return ( <Checkbox panel={panel} checked={false} onChange={undefined} className="design-input-field" disabled /> ); default: throw(`The type ${panel.type} is not a supported panel.`); } } public render() { const { type, config } = this.state.panel; const { label, description } = config; return ( <div className="formpanel-small-input-container"> <Icon onClick={this.props.close} id={this.props.panel.id} size={20} icon="cancel" /> <Icon onClick={this.props.settings} id={this.props.panel.id} size={20} icon="settings" /> <div className="small-input-container"> {this.getType(this.props.panel, label)} </div> <div className="small-input-label-container"> <input type="text" value={label} onChange={this.updateLabel} placeholder={`${type} Label...`} /> </div> </div> ); } }
mit
adrien-thierry/htmlstation
content/engine/http-data/post/post.app.js
1519
/* Copyright (C) 2016 Adrien THIERRY http://seraum.com */ module.exports = PostHttp; function PostHttp() { var wf = WF(); function parseMultipartReq(req, multipart) { for(var r in multipart.parts) { req.post[r] = multipart.parts[r].body; } req.field = multipart.fields; req.multipart = multipart.isMultipart; } function parseReqRaw(req) { var tmp = req.postData.toString(); var obj = tmp.split("&"); for(var o = 0; o < obj.length; o++) { var t = obj[o].split("="); if(t[1] === undefined) t[1] = ""; req.post[t[0]] = unescape(t[1].replace(/\+/gi, " ")); } } function parseReqPost(req) { var multipart = new wf.MultipartParser(req.headers['content-type'], req.postData); if(multipart.isMultipart) { parseMultipartReq(req, multipart); } else if(req.postData.lastIndexOf !== undefined && req.postData.indexOf("{", 0) === 0) { try { req.post = JSON.parse(req.postData); } catch(e){} } else { parseReqRaw(req); } } function parseReqJSON(req) { for(var p in req.post) { if(req.post[p].indexOf && req.post[p].indexOf("{", 0) === 0) { try { var tmpJ = JSON.parse(req.post[p]); req.post[p] = tmpJ; }catch(e){ } } } } this.code = function(req, res) { req.post = {}; if(req.method == "POST" || req.method == "PUT") { if(req.postData !== undefined) { parseReqPost(req); // PARSE JSON parseReqJSON(req); } } }; }
mit
micdenny/Radical.Windows
src/net35/Radical.Windows/Model/SortDescriptionExtensions.cs
1158
//using System; //using System.Collections.Generic; //using System.Linq; //using System.Text; //using System.ComponentModel; //using Topics.Radical.ComponentModel; //namespace Topics.Radical.Windows.Model //{ // static class SortDescriptionExtensions // { // public static ListSortDescription Convert<T>( this SortDescription item )// where T : class // { // var property = new EntityItemViewPropertyDescriptor<T> // ( // typeof( T ).GetProperty( item.PropertyName ) // ); // var convertedItem = new ListSortDescription( property, item.Direction ); // return convertedItem; // } // public static ListSortDescriptionCollection Convert<T>( this SortDescriptionCollection source ) //where T : class // { // var tmp = source.Aggregate( new List<ListSortDescription>(), ( a, sd ) => // { // a.Add( sd.Convert<T>() ); // return a; // } ) // .ToArray(); // var list = new ListSortDescriptionCollection( tmp ); // return list; // } // } //}
mit
nebw/keras
keras/layers/convolutional.py
77023
# -*- coding: utf-8 -*- from __future__ import absolute_import from .. import backend as K from .. import activations, initializations, regularizers, constraints from ..engine import Layer, InputSpec from ..utils.np_utils import conv_output_length, conv_input_length # imports for backwards namespace compatibility from .pooling import AveragePooling1D, AveragePooling2D, AveragePooling3D from .pooling import MaxPooling1D, MaxPooling2D, MaxPooling3D class Convolution1D(Layer): '''Convolution operator for filtering neighborhoods of one-dimensional inputs. When using this layer as the first layer in a model, either provide the keyword argument `input_dim` (int, e.g. 128 for sequences of 128-dimensional vectors), or `input_shape` (tuple of integers, e.g. (10, 128) for sequences of 10 vectors of 128-dimensional vectors). # Example ```python # apply a convolution 1d of length 3 to a sequence with 10 timesteps, # with 64 output filters model = Sequential() model.add(Convolution1D(64, 3, border_mode='same', input_shape=(10, 32))) # now model.output_shape == (None, 10, 64) # add a new conv1d on top model.add(Convolution1D(32, 3, border_mode='same')) # now model.output_shape == (None, 10, 32) ``` # Arguments nb_filter: Number of convolution kernels to use (dimensionality of the output). filter_length: The extension (spatial or temporal) of each filter. init: name of initialization function for the weights of the layer (see [initializations](../initializations.md)), or alternatively, Theano function to use for weights initialization. This parameter is only relevant if you don't pass a `weights` argument. activation: name of activation function to use (see [activations](../activations.md)), or alternatively, elementwise Theano function. If you don't specify anything, no activation is applied (ie. "linear" activation: a(x) = x). weights: list of numpy arrays to set as initial weights. border_mode: 'valid' or 'same'. subsample_length: factor by which to subsample output. W_regularizer: instance of [WeightRegularizer](../regularizers.md) (eg. L1 or L2 regularization), applied to the main weights matrix. b_regularizer: instance of [WeightRegularizer](../regularizers.md), applied to the bias. activity_regularizer: instance of [ActivityRegularizer](../regularizers.md), applied to the network output. W_constraint: instance of the [constraints](../constraints.md) module (eg. maxnorm, nonneg), applied to the main weights matrix. b_constraint: instance of the [constraints](../constraints.md) module, applied to the bias. bias: whether to include a bias (i.e. make the layer affine rather than linear). input_dim: Number of channels/dimensions in the input. Either this argument or the keyword argument `input_shape`must be provided when using this layer as the first layer in a model. input_length: Length of input sequences, when it is constant. This argument is required if you are going to connect `Flatten` then `Dense` layers upstream (without it, the shape of the dense outputs cannot be computed). # Input shape 3D tensor with shape: `(samples, steps, input_dim)`. # Output shape 3D tensor with shape: `(samples, new_steps, nb_filter)`. `steps` value might have changed due to padding. ''' def __init__(self, nb_filter, filter_length, init='uniform', activation='linear', weights=None, border_mode='valid', subsample_length=1, W_regularizer=None, b_regularizer=None, activity_regularizer=None, W_constraint=None, b_constraint=None, bias=True, input_dim=None, input_length=None, **kwargs): if border_mode not in {'valid', 'same'}: raise Exception('Invalid border mode for Convolution1D:', border_mode) self.nb_filter = nb_filter self.filter_length = filter_length self.init = initializations.get(init, dim_ordering='th') self.activation = activations.get(activation) assert border_mode in {'valid', 'same'}, 'border_mode must be in {valid, same}' self.border_mode = border_mode self.subsample_length = subsample_length self.subsample = (subsample_length, 1) self.W_regularizer = regularizers.get(W_regularizer) self.b_regularizer = regularizers.get(b_regularizer) self.activity_regularizer = regularizers.get(activity_regularizer) self.W_constraint = constraints.get(W_constraint) self.b_constraint = constraints.get(b_constraint) self.bias = bias self.input_spec = [InputSpec(ndim=3)] self.initial_weights = weights self.input_dim = input_dim self.input_length = input_length if self.input_dim: kwargs['input_shape'] = (self.input_length, self.input_dim) super(Convolution1D, self).__init__(**kwargs) def build(self, input_shape): input_dim = input_shape[2] self.W_shape = (self.nb_filter, input_dim, self.filter_length, 1) self.W = self.init(self.W_shape, name='{}_W'.format(self.name)) if self.bias: self.b = K.zeros((self.nb_filter,), name='{}_b'.format(self.name)) self.trainable_weights = [self.W, self.b] else: self.trainable_weights = [self.W] self.regularizers = [] if self.W_regularizer: self.W_regularizer.set_param(self.W) self.regularizers.append(self.W_regularizer) if self.bias and self.b_regularizer: self.b_regularizer.set_param(self.b) self.regularizers.append(self.b_regularizer) if self.activity_regularizer: self.activity_regularizer.set_layer(self) self.regularizers.append(self.activity_regularizer) self.constraints = {} if self.W_constraint: self.constraints[self.W] = self.W_constraint if self.bias and self.b_constraint: self.constraints[self.b] = self.b_constraint if self.initial_weights is not None: self.set_weights(self.initial_weights) del self.initial_weights def get_output_shape_for(self, input_shape): length = conv_output_length(input_shape[1], self.filter_length, self.border_mode, self.subsample[0]) return (input_shape[0], length, self.nb_filter) def call(self, x, mask=None): x = K.expand_dims(x, -1) # add a dimension of the right x = K.permute_dimensions(x, (0, 2, 1, 3)) output = K.conv2d(x, self.W, strides=self.subsample, border_mode=self.border_mode, dim_ordering='th') if self.bias: output += K.reshape(self.b, (1, self.nb_filter, 1, 1)) output = K.squeeze(output, 3) # remove the dummy 3rd dimension output = K.permute_dimensions(output, (0, 2, 1)) output = self.activation(output) return output def get_config(self): config = {'nb_filter': self.nb_filter, 'filter_length': self.filter_length, 'init': self.init.__name__, 'activation': self.activation.__name__, 'border_mode': self.border_mode, 'subsample_length': self.subsample_length, 'W_regularizer': self.W_regularizer.get_config() if self.W_regularizer else None, 'b_regularizer': self.b_regularizer.get_config() if self.b_regularizer else None, 'activity_regularizer': self.activity_regularizer.get_config() if self.activity_regularizer else None, 'W_constraint': self.W_constraint.get_config() if self.W_constraint else None, 'b_constraint': self.b_constraint.get_config() if self.b_constraint else None, 'bias': self.bias, 'input_dim': self.input_dim, 'input_length': self.input_length} base_config = super(Convolution1D, self).get_config() return dict(list(base_config.items()) + list(config.items())) class Convolution2D(Layer): '''Convolution operator for filtering windows of two-dimensional inputs. When using this layer as the first layer in a model, provide the keyword argument `input_shape` (tuple of integers, does not include the sample axis), e.g. `input_shape=(3, 128, 128)` for 128x128 RGB pictures. # Examples ```python # apply a 3x3 convolution with 64 output filters on a 256x256 image: model = Sequential() model.add(Convolution2D(64, 3, 3, border_mode='same', input_shape=(3, 256, 256))) # now model.output_shape == (None, 64, 256, 256) # add a 3x3 convolution on top, with 32 output filters: model.add(Convolution2D(32, 3, 3, border_mode='same')) # now model.output_shape == (None, 32, 256, 256) ``` # Arguments nb_filter: Number of convolution filters to use. nb_row: Number of rows in the convolution kernel. nb_col: Number of columns in the convolution kernel. init: name of initialization function for the weights of the layer (see [initializations](../initializations.md)), or alternatively, Theano function to use for weights initialization. This parameter is only relevant if you don't pass a `weights` argument. activation: name of activation function to use (see [activations](../activations.md)), or alternatively, elementwise Theano function. If you don't specify anything, no activation is applied (ie. "linear" activation: a(x) = x). weights: list of numpy arrays to set as initial weights. border_mode: 'valid' or 'same'. subsample: tuple of length 2. Factor by which to subsample output. Also called strides elsewhere. W_regularizer: instance of [WeightRegularizer](../regularizers.md) (eg. L1 or L2 regularization), applied to the main weights matrix. b_regularizer: instance of [WeightRegularizer](../regularizers.md), applied to the bias. activity_regularizer: instance of [ActivityRegularizer](../regularizers.md), applied to the network output. W_constraint: instance of the [constraints](../constraints.md) module (eg. maxnorm, nonneg), applied to the main weights matrix. b_constraint: instance of the [constraints](../constraints.md) module, applied to the bias. dim_ordering: 'th' or 'tf'. In 'th' mode, the channels dimension (the depth) is at index 1, in 'tf' mode is it at index 3. It defaults to the `image_dim_ordering` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "th". bias: whether to include a bias (i.e. make the layer affine rather than linear). # Input shape 4D tensor with shape: `(samples, channels, rows, cols)` if dim_ordering='th' or 4D tensor with shape: `(samples, rows, cols, channels)` if dim_ordering='tf'. # Output shape 4D tensor with shape: `(samples, nb_filter, new_rows, new_cols)` if dim_ordering='th' or 4D tensor with shape: `(samples, new_rows, new_cols, nb_filter)` if dim_ordering='tf'. `rows` and `cols` values might have changed due to padding. ''' def __init__(self, nb_filter, nb_row, nb_col, init='glorot_uniform', activation='linear', weights=None, border_mode='valid', subsample=(1, 1), dim_ordering='default', W_regularizer=None, b_regularizer=None, activity_regularizer=None, W_constraint=None, b_constraint=None, bias=True, **kwargs): if dim_ordering == 'default': dim_ordering = K.image_dim_ordering() if border_mode not in {'valid', 'same'}: raise Exception('Invalid border mode for Convolution2D:', border_mode) self.nb_filter = nb_filter self.nb_row = nb_row self.nb_col = nb_col self.init = initializations.get(init, dim_ordering=dim_ordering) self.activation = activations.get(activation) assert border_mode in {'valid', 'same'}, 'border_mode must be in {valid, same}' self.border_mode = border_mode self.subsample = tuple(subsample) assert dim_ordering in {'tf', 'th'}, 'dim_ordering must be in {tf, th}' self.dim_ordering = dim_ordering self.W_regularizer = regularizers.get(W_regularizer) self.b_regularizer = regularizers.get(b_regularizer) self.activity_regularizer = regularizers.get(activity_regularizer) self.W_constraint = constraints.get(W_constraint) self.b_constraint = constraints.get(b_constraint) self.bias = bias self.input_spec = [InputSpec(ndim=4)] self.initial_weights = weights super(Convolution2D, self).__init__(**kwargs) def build(self, input_shape): if self.dim_ordering == 'th': stack_size = input_shape[1] self.W_shape = (self.nb_filter, stack_size, self.nb_row, self.nb_col) elif self.dim_ordering == 'tf': stack_size = input_shape[3] self.W_shape = (self.nb_row, self.nb_col, stack_size, self.nb_filter) else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) self.W = self.init(self.W_shape, name='{}_W'.format(self.name)) if self.bias: self.b = K.zeros((self.nb_filter,), name='{}_b'.format(self.name)) self.trainable_weights = [self.W, self.b] else: self.trainable_weights = [self.W] self.regularizers = [] if self.W_regularizer: self.W_regularizer.set_param(self.W) self.regularizers.append(self.W_regularizer) if self.bias and self.b_regularizer: self.b_regularizer.set_param(self.b) self.regularizers.append(self.b_regularizer) if self.activity_regularizer: self.activity_regularizer.set_layer(self) self.regularizers.append(self.activity_regularizer) self.constraints = {} if self.W_constraint: self.constraints[self.W] = self.W_constraint if self.bias and self.b_constraint: self.constraints[self.b] = self.b_constraint if self.initial_weights is not None: self.set_weights(self.initial_weights) del self.initial_weights def get_output_shape_for(self, input_shape): if self.dim_ordering == 'th': rows = input_shape[2] cols = input_shape[3] elif self.dim_ordering == 'tf': rows = input_shape[1] cols = input_shape[2] else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) rows = conv_output_length(rows, self.nb_row, self.border_mode, self.subsample[0]) cols = conv_output_length(cols, self.nb_col, self.border_mode, self.subsample[1]) if self.dim_ordering == 'th': return (input_shape[0], self.nb_filter, rows, cols) elif self.dim_ordering == 'tf': return (input_shape[0], rows, cols, self.nb_filter) else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) def call(self, x, mask=None): output = K.conv2d(x, self.W, strides=self.subsample, border_mode=self.border_mode, dim_ordering=self.dim_ordering, filter_shape=self.W_shape) if self.bias: if self.dim_ordering == 'th': output += K.reshape(self.b, (1, self.nb_filter, 1, 1)) elif self.dim_ordering == 'tf': output += K.reshape(self.b, (1, 1, 1, self.nb_filter)) else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) output = self.activation(output) return output def get_config(self): config = {'nb_filter': self.nb_filter, 'nb_row': self.nb_row, 'nb_col': self.nb_col, 'init': self.init.__name__, 'activation': self.activation.__name__, 'border_mode': self.border_mode, 'subsample': self.subsample, 'dim_ordering': self.dim_ordering, 'W_regularizer': self.W_regularizer.get_config() if self.W_regularizer else None, 'b_regularizer': self.b_regularizer.get_config() if self.b_regularizer else None, 'activity_regularizer': self.activity_regularizer.get_config() if self.activity_regularizer else None, 'W_constraint': self.W_constraint.get_config() if self.W_constraint else None, 'b_constraint': self.b_constraint.get_config() if self.b_constraint else None, 'bias': self.bias} base_config = super(Convolution2D, self).get_config() return dict(list(base_config.items()) + list(config.items())) class Deconvolution2D(Convolution2D): '''Transposed convolution operator for filtering windows of two-dimensional inputs. The need for transposed convolutions generally arises from the desire to use a transformation going in the opposite direction of a normal convolution, i.e., from something that has the shape of the output of some convolution to something that has the shape of its input while maintaining a connectivity pattern that is compatible with said convolution. [1] When using this layer as the first layer in a model, provide the keyword argument `input_shape` (tuple of integers, does not include the sample axis), e.g. `input_shape=(3, 128, 128)` for 128x128 RGB pictures. # Examples ```python # apply a 3x3 transposed convolution with stride 1x1 and 3 output filters on a 12x12 image: model = Sequential() model.add(Deconvolution2D(3, 3, 3, output_shape=(None, 3, 14, 14), border_mode='valid', input_shape=(3, 12, 12))) # output_shape will be (None, 3, 14, 14) # apply a 3x3 transposed convolution with stride 2x2 and 3 output filters on a 12x12 image: model = Sequential() model.add(Deconvolution2D(3, 3, 3, output_shape=(None, 3, 25, 25), subsample=(2, 2), border_mode='valid', input_shape=(3, 12, 12))) model.summary() # output_shape will be (None, 3, 25, 25) ``` # Arguments nb_filter: Number of transposed convolution filters to use. nb_row: Number of rows in the transposed convolution kernel. nb_col: Number of columns in the transposed convolution kernel. output_shape: Output shape of the transposed convolution operation. tuple of integers (nb_samples, nb_filter, nb_output_rows, nb_output_cols) Formula for calculation of the output shape [1], [2]: o = s (i - 1) + a + k - 2p, \quad a \in \{0, \ldots, s - 1\} where: i - input size (rows or cols), k - kernel size (nb_filter), s - stride (subsample for rows or cols respectively), p - padding size, a - user-specified quantity used to distinguish between the s different possible output sizes. init: name of initialization function for the weights of the layer (see [initializations](../initializations.md)), or alternatively, Theano function to use for weights initialization. This parameter is only relevant if you don't pass a `weights` argument. activation: name of activation function to use (see [activations](../activations.md)), or alternatively, elementwise Theano/TensorFlow function. If you don't specify anything, no activation is applied (ie. "linear" activation: a(x) = x). weights: list of numpy arrays to set as initial weights. border_mode: 'valid' or 'same'. subsample: tuple of length 2. Factor by which to oversample output. Also called strides elsewhere. W_regularizer: instance of [WeightRegularizer](../regularizers.md) (eg. L1 or L2 regularization), applied to the main weights matrix. b_regularizer: instance of [WeightRegularizer](../regularizers.md), applied to the bias. activity_regularizer: instance of [ActivityRegularizer](../regularizers.md), applied to the network output. W_constraint: instance of the [constraints](../constraints.md) module (eg. maxnorm, nonneg), applied to the main weights matrix. b_constraint: instance of the [constraints](../constraints.md) module, applied to the bias. dim_ordering: 'th' or 'tf'. In 'th' mode, the channels dimension (the depth) is at index 1, in 'tf' mode is it at index 3. It defaults to the `image_dim_ordering` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "th". bias: whether to include a bias (i.e. make the layer affine rather than linear). # Input shape 4D tensor with shape: `(samples, channels, rows, cols)` if dim_ordering='th' or 4D tensor with shape: `(samples, rows, cols, channels)` if dim_ordering='tf'. # Output shape 4D tensor with shape: `(samples, nb_filter, new_rows, new_cols)` if dim_ordering='th' or 4D tensor with shape: `(samples, new_rows, new_cols, nb_filter)` if dim_ordering='tf'. `rows` and `cols` values might have changed due to padding. # References [1] [A guide to convolution arithmetic for deep learning](https://arxiv.org/abs/1603.07285 "arXiv:1603.07285v1 [stat.ML]") [2] [Transposed convolution arithmetic](http://deeplearning.net/software/theano_versions/dev/tutorial/conv_arithmetic.html#transposed-convolution-arithmetic) [3] [Deconvolutional Networks](http://www.matthewzeiler.com/pubs/cvpr2010/cvpr2010.pdf) ''' def __init__(self, nb_filter, nb_row, nb_col, output_shape, init='glorot_uniform', activation='linear', weights=None, border_mode='valid', subsample=(1, 1), dim_ordering=K.image_dim_ordering(), W_regularizer=None, b_regularizer=None, activity_regularizer=None, W_constraint=None, b_constraint=None, bias=True, **kwargs): if border_mode not in {'valid', 'same'}: raise Exception('Invalid border mode for Deconvolution2D:', border_mode) self.output_shape_ = output_shape super(Deconvolution2D, self).__init__(nb_filter, nb_row, nb_col, init=init, activation=activation, weights=weights, border_mode=border_mode, subsample=subsample, dim_ordering=dim_ordering, W_regularizer=W_regularizer, b_regularizer=b_regularizer, activity_regularizer=activity_regularizer, W_constraint=W_constraint, b_constraint=b_constraint, bias=bias, **kwargs) def get_output_shape_for(self, input_shape): if self.dim_ordering == 'th': rows = input_shape[2] cols = input_shape[3] elif self.dim_ordering == 'tf': rows = input_shape[1] cols = input_shape[2] else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) rows = conv_input_length(rows, self.nb_row, self.border_mode, self.subsample[0]) cols = conv_input_length(cols, self.nb_col, self.border_mode, self.subsample[1]) if self.dim_ordering == 'th': return (input_shape[0], self.nb_filter, rows, cols) elif self.dim_ordering == 'tf': return (input_shape[0], rows, cols, self.nb_filter) else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) def call(self, x, mask=None): output = K.deconv2d(x, self.W, self.output_shape_, strides=self.subsample, border_mode=self.border_mode, dim_ordering=self.dim_ordering, filter_shape=self.W_shape) if self.bias: if self.dim_ordering == 'th': output += K.reshape(self.b, (1, self.nb_filter, 1, 1)) elif self.dim_ordering == 'tf': output += K.reshape(self.b, (1, 1, 1, self.nb_filter)) else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) output = self.activation(output) return output def get_config(self): config = {'output_shape': self.output_shape} base_config = super(Deconvolution2D, self).get_config() return dict(list(base_config.items()) + list(config.items())) class AtrousConvolution2D(Convolution2D): '''Atrous Convolution operator for filtering windows of two-dimensional inputs. A.k.a dilated convolution or convolution with holes. When using this layer as the first layer in a model, provide the keyword argument `input_shape` (tuple of integers, does not include the sample axis), e.g. `input_shape=(3, 128, 128)` for 128x128 RGB pictures. # Examples ```python # apply a 3x3 convolution with atrous rate 2x2 and 64 output filters on a 256x256 image: model = Sequential() model.add(AtrousConvolution2D(64, 3, 3, atrous_rate=(2,2), border_mode='valid', input_shape=(3, 256, 256))) # now the actual kernel size is dilated from 3x3 to 5x5 (3+(3-1)*(2-1)=5) # thus model.output_shape == (None, 64, 252, 252) ``` # Arguments nb_filter: Number of convolution filters to use. nb_row: Number of rows in the convolution kernel. nb_col: Number of columns in the convolution kernel. init: name of initialization function for the weights of the layer (see [initializations](../initializations.md)), or alternatively, Theano function to use for weights initialization. This parameter is only relevant if you don't pass a `weights` argument. activation: name of activation function to use (see [activations](../activations.md)), or alternatively, elementwise Theano function. If you don't specify anything, no activation is applied (ie. "linear" activation: a(x) = x). weights: list of numpy arrays to set as initial weights. border_mode: 'valid' or 'same'. subsample: tuple of length 2. Factor by which to subsample output. Also called strides elsewhere. atrous_rate: tuple of length 2. Factor for kernel dilation. Also called filter_dilation elsewhere. W_regularizer: instance of [WeightRegularizer](../regularizers.md) (eg. L1 or L2 regularization), applied to the main weights matrix. b_regularizer: instance of [WeightRegularizer](../regularizers.md), applied to the bias. activity_regularizer: instance of [ActivityRegularizer](../regularizers.md), applied to the network output. W_constraint: instance of the [constraints](../constraints.md) module (eg. maxnorm, nonneg), applied to the main weights matrix. b_constraint: instance of the [constraints](../constraints.md) module, applied to the bias. dim_ordering: 'th' or 'tf'. In 'th' mode, the channels dimension (the depth) is at index 1, in 'tf' mode is it at index 3. It defaults to the `image_dim_ordering` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "th". bias: whether to include a bias (i.e. make the layer affine rather than linear). # Input shape 4D tensor with shape: `(samples, channels, rows, cols)` if dim_ordering='th' or 4D tensor with shape: `(samples, rows, cols, channels)` if dim_ordering='tf'. # Output shape 4D tensor with shape: `(samples, nb_filter, new_rows, new_cols)` if dim_ordering='th' or 4D tensor with shape: `(samples, new_rows, new_cols, nb_filter)` if dim_ordering='tf'. `rows` and `cols` values might have changed due to padding. # References - [Multi-Scale Context Aggregation by Dilated Convolutions](https://arxiv.org/abs/1511.07122) ''' def __init__(self, nb_filter, nb_row, nb_col, init='glorot_uniform', activation='linear', weights=None, border_mode='valid', subsample=(1, 1), atrous_rate=(1, 1), dim_ordering='default', W_regularizer=None, b_regularizer=None, activity_regularizer=None, W_constraint=None, b_constraint=None, bias=True, **kwargs): if dim_ordering == 'default': dim_ordering = K.image_dim_ordering() if border_mode not in {'valid', 'same'}: raise Exception('Invalid border mode for AtrousConv2D:', border_mode) self.atrous_rate = tuple(atrous_rate) super(AtrousConvolution2D, self).__init__(nb_filter, nb_row, nb_col, init=init, activation=activation, weights=weights, border_mode=border_mode, subsample=subsample, dim_ordering=dim_ordering, W_regularizer=W_regularizer, b_regularizer=b_regularizer, activity_regularizer=activity_regularizer, W_constraint=W_constraint, b_constraint=b_constraint, bias=bias, **kwargs) def get_output_shape_for(self, input_shape): if self.dim_ordering == 'th': rows = input_shape[2] cols = input_shape[3] elif self.dim_ordering == 'tf': rows = input_shape[1] cols = input_shape[2] else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) rows = conv_output_length(rows, self.nb_row, self.border_mode, self.subsample[0], dilation=self.atrous_rate[0]) cols = conv_output_length(cols, self.nb_col, self.border_mode, self.subsample[1], dilation=self.atrous_rate[1]) if self.dim_ordering == 'th': return (input_shape[0], self.nb_filter, rows, cols) elif self.dim_ordering == 'tf': return (input_shape[0], rows, cols, self.nb_filter) else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) def call(self, x, mask=None): output = K.conv2d(x, self.W, strides=self.subsample, border_mode=self.border_mode, dim_ordering=self.dim_ordering, filter_shape=self.W_shape, filter_dilation=self.atrous_rate) if self.bias: if self.dim_ordering == 'th': output += K.reshape(self.b, (1, self.nb_filter, 1, 1)) elif self.dim_ordering == 'tf': output += K.reshape(self.b, (1, 1, 1, self.nb_filter)) else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) output = self.activation(output) return output def get_config(self): config = {'atrous_rate': self.atrous_rate} base_config = super(AtrousConvolution2D, self).get_config() return dict(list(base_config.items()) + list(config.items())) class SeparableConvolution2D(Layer): '''Separable convolution operator for 2D inputs. Separable convolutions consist in first performing a depthwise spatial convolution (which acts on each input channel separately) followed by a pointwise convolution which mixes together the resulting output channels. The `depth_multiplier` argument controls how many output channels are generated per input channel in the depthwise step. Intuitively, separable convolutions can be understood as a way to factorize a convolution kernel into two smaller kernels, or as an extreme version of an Inception block. When using this layer as the first layer in a model, provide the keyword argument `input_shape` (tuple of integers, does not include the sample axis), e.g. `input_shape=(3, 128, 128)` for 128x128 RGB pictures. # Theano warning This layer is only available with the TensorFlow backend for the time being. # Arguments nb_filter: Number of convolution filters to use. nb_row: Number of rows in the convolution kernel. nb_col: Number of columns in the convolution kernel. init: name of initialization function for the weights of the layer (see [initializations](../initializations.md)), or alternatively, Theano function to use for weights initialization. This parameter is only relevant if you don't pass a `weights` argument. activation: name of activation function to use (see [activations](../activations.md)), or alternatively, elementwise Theano function. If you don't specify anything, no activation is applied (ie. "linear" activation: a(x) = x). weights: list of numpy arrays to set as initial weights. border_mode: 'valid' or 'same'. subsample: tuple of length 2. Factor by which to subsample output. Also called strides elsewhere. depth_multiplier: how many output channel to use per input channel for the depthwise convolution step. depthwise_regularizer: instance of [WeightRegularizer](../regularizers.md) (eg. L1 or L2 regularization), applied to the depthwise weights matrix. pointwise_regularizer: instance of [WeightRegularizer](../regularizers.md) (eg. L1 or L2 regularization), applied to the pointwise weights matrix. b_regularizer: instance of [WeightRegularizer](../regularizers.md), applied to the bias. activity_regularizer: instance of [ActivityRegularizer](../regularizers.md), applied to the network output. depthwise_constraint: instance of the [constraints](../constraints.md) module (eg. maxnorm, nonneg), applied to the depthwise weights matrix. pointwise_constraint: instance of the [constraints](../constraints.md) module (eg. maxnorm, nonneg), applied to the pointwise weights matrix. b_constraint: instance of the [constraints](../constraints.md) module, applied to the bias. dim_ordering: 'th' or 'tf'. In 'th' mode, the channels dimension (the depth) is at index 1, in 'tf' mode is it at index 3. It defaults to the `image_dim_ordering` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "th". bias: whether to include a bias (i.e. make the layer affine rather than linear). # Input shape 4D tensor with shape: `(samples, channels, rows, cols)` if dim_ordering='th' or 4D tensor with shape: `(samples, rows, cols, channels)` if dim_ordering='tf'. # Output shape 4D tensor with shape: `(samples, nb_filter, new_rows, new_cols)` if dim_ordering='th' or 4D tensor with shape: `(samples, new_rows, new_cols, nb_filter)` if dim_ordering='tf'. `rows` and `cols` values might have changed due to padding. ''' def __init__(self, nb_filter, nb_row, nb_col, init='glorot_uniform', activation='linear', weights=None, border_mode='valid', subsample=(1, 1), depth_multiplier=1, dim_ordering='default', depthwise_regularizer=None, pointwise_regularizer=None, b_regularizer=None, activity_regularizer=None, depthwise_constraint=None, pointwise_constraint=None, b_constraint=None, bias=True, **kwargs): if K._BACKEND != 'tensorflow': raise Exception('SeparableConv2D is only available ' 'with TensorFlow for the time being.') if dim_ordering == 'default': dim_ordering = K.image_dim_ordering() if border_mode not in {'valid', 'same'}: raise Exception('Invalid border mode for SeparableConv2D:', border_mode) if border_mode not in {'valid', 'same'}: raise Exception('Invalid border mode for SeparableConv2D:', border_mode) self.nb_filter = nb_filter self.nb_row = nb_row self.nb_col = nb_col self.init = initializations.get(init, dim_ordering=dim_ordering) self.activation = activations.get(activation) assert border_mode in {'valid', 'same'}, 'border_mode must be in {valid, same}' self.border_mode = border_mode self.subsample = tuple(subsample) self.depth_multiplier = depth_multiplier assert dim_ordering in {'tf', 'th'}, 'dim_ordering must be in {tf, th}' self.dim_ordering = dim_ordering self.depthwise_regularizer = regularizers.get(depthwise_regularizer) self.pointwise_regularizer = regularizers.get(pointwise_regularizer) self.b_regularizer = regularizers.get(b_regularizer) self.activity_regularizer = regularizers.get(activity_regularizer) self.depthwise_constraint = constraints.get(depthwise_constraint) self.pointwise_constraint = constraints.get(pointwise_constraint) self.b_constraint = constraints.get(b_constraint) self.bias = bias self.input_spec = [InputSpec(ndim=4)] self.initial_weights = weights super(SeparableConvolution2D, self).__init__(**kwargs) def build(self, input_shape): if self.dim_ordering == 'th': stack_size = input_shape[1] depthwise_shape = (self.depth_multiplier, stack_size, self.nb_row, self.nb_col) pointwise_shape = (self.nb_filter, self.depth_multiplier * stack_size, 1, 1) elif self.dim_ordering == 'tf': stack_size = input_shape[3] depthwise_shape = (self.nb_row, self.nb_col, stack_size, self.depth_multiplier) pointwise_shape = (1, 1, self.depth_multiplier * stack_size, self.nb_filter) else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) self.depthwise_kernel = self.init(depthwise_shape, name='{}_depthwise_kernel'.format(self.name)) self.pointwise_kernel = self.init(pointwise_shape, name='{}_pointwise_kernel'.format(self.name)) if self.bias: self.b = K.zeros((self.nb_filter,), name='{}_b'.format(self.name)) self.trainable_weights = [self.depthwise_kernel, self.pointwise_kernel, self.b] else: self.trainable_weights = [self.depthwise_kernel, self.pointwise_kernel] self.regularizers = [] if self.depthwise_regularizer: self.depthwise_regularizer.set_param(self.depthwise_kernel) self.regularizers.append(self.depthwise_regularizer) if self.pointwise_regularizer: self.pointwise_regularizer.set_param(self.pointwise_kernel) self.regularizers.append(self.pointwise_regularizer) if self.bias and self.b_regularizer: self.b_regularizer.set_param(self.b) self.regularizers.append(self.b_regularizer) if self.activity_regularizer: self.activity_regularizer.set_layer(self) self.regularizers.append(self.activity_regularizer) self.constraints = {} if self.depthwise_constraint: self.constraints[self.depthwise_kernel] = self.depthwise_constraint if self.pointwise_constraint: self.constraints[self.pointwise_kernel] = self.pointwise_constraint if self.bias and self.b_constraint: self.constraints[self.b] = self.b_constraint if self.initial_weights is not None: self.set_weights(self.initial_weights) del self.initial_weights def get_output_shape_for(self, input_shape): if self.dim_ordering == 'th': rows = input_shape[2] cols = input_shape[3] elif self.dim_ordering == 'tf': rows = input_shape[1] cols = input_shape[2] else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) rows = conv_output_length(rows, self.nb_row, self.border_mode, self.subsample[0]) cols = conv_output_length(cols, self.nb_col, self.border_mode, self.subsample[1]) if self.dim_ordering == 'th': return (input_shape[0], self.nb_filter, rows, cols) elif self.dim_ordering == 'tf': return (input_shape[0], rows, cols, self.nb_filter) else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) def call(self, x, mask=None): output = K.separable_conv2d(x, self.depthwise_kernel, self.pointwise_kernel, strides=self.subsample, border_mode=self.border_mode, dim_ordering=self.dim_ordering) if self.bias: if self.dim_ordering == 'th': output += K.reshape(self.b, (1, self.nb_filter, 1, 1)) elif self.dim_ordering == 'tf': output += K.reshape(self.b, (1, 1, 1, self.nb_filter)) else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) output = self.activation(output) return output def get_config(self): config = {'nb_filter': self.nb_filter, 'nb_row': self.nb_row, 'nb_col': self.nb_col, 'init': self.init.__name__, 'activation': self.activation.__name__, 'border_mode': self.border_mode, 'subsample': self.subsample, 'depth_multiplier': self.depth_multiplier, 'dim_ordering': self.dim_ordering, 'depthwise_regularizer': self.depthwise_regularizer.get_config() if self.depthwise_regularizer else None, 'pointwise_regularizer': self.depthwise_regularizer.get_config() if self.depthwise_regularizer else None, 'b_regularizer': self.b_regularizer.get_config() if self.b_regularizer else None, 'activity_regularizer': self.activity_regularizer.get_config() if self.activity_regularizer else None, 'depthwise_constraint': self.depthwise_constraint.get_config() if self.depthwise_constraint else None, 'pointwise_constraint': self.pointwise_constraint.get_config() if self.pointwise_constraint else None, 'b_constraint': self.b_constraint.get_config() if self.b_constraint else None, 'bias': self.bias} base_config = super(SeparableConvolution2D, self).get_config() return dict(list(base_config.items()) + list(config.items())) class Convolution3D(Layer): '''Convolution operator for filtering windows of three-dimensional inputs. When using this layer as the first layer in a model, provide the keyword argument `input_shape` (tuple of integers, does not include the sample axis), e.g. `input_shape=(3, 10, 128, 128)` for 10 frames of 128x128 RGB pictures. # Arguments nb_filter: Number of convolution filters to use. kernel_dim1: Length of the first dimension in the convolution kernel. kernel_dim2: Length of the second dimension in the convolution kernel. kernel_dim3: Length of the third dimension in the convolution kernel. init: name of initialization function for the weights of the layer (see [initializations](../initializations.md)), or alternatively, Theano function to use for weights initialization. This parameter is only relevant if you don't pass a `weights` argument. activation: name of activation function to use (see [activations](../activations.md)), or alternatively, elementwise Theano function. If you don't specify anything, no activation is applied (ie. "linear" activation: a(x) = x). weights: list of Numpy arrays to set as initial weights. border_mode: 'valid' or 'same'. subsample: tuple of length 3. Factor by which to subsample output. Also called strides elsewhere. Note: 'subsample' is implemented by slicing the output of conv3d with strides=(1,1,1). W_regularizer: instance of [WeightRegularizer](../regularizers.md) (eg. L1 or L2 regularization), applied to the main weights matrix. b_regularizer: instance of [WeightRegularizer](../regularizers.md), applied to the bias. activity_regularizer: instance of [ActivityRegularizer](../regularizers.md), applied to the network output. W_constraint: instance of the [constraints](../constraints.md) module (eg. maxnorm, nonneg), applied to the main weights matrix. b_constraint: instance of the [constraints](../constraints.md) module, applied to the bias. dim_ordering: 'th' or 'tf'. In 'th' mode, the channels dimension (the depth) is at index 1, in 'tf' mode is it at index 4. It defaults to the `image_dim_ordering` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "th". bias: whether to include a bias (i.e. make the layer affine rather than linear). # Input shape 5D tensor with shape: `(samples, channels, conv_dim1, conv_dim2, conv_dim3)` if dim_ordering='th' or 5D tensor with shape: `(samples, conv_dim1, conv_dim2, conv_dim3, channels)` if dim_ordering='tf'. # Output shape 5D tensor with shape: `(samples, nb_filter, new_conv_dim1, new_conv_dim2, new_conv_dim3)` if dim_ordering='th' or 5D tensor with shape: `(samples, new_conv_dim1, new_conv_dim2, new_conv_dim3, nb_filter)` if dim_ordering='tf'. `new_conv_dim1`, `new_conv_dim2` and `new_conv_dim3` values might have changed due to padding. ''' def __init__(self, nb_filter, kernel_dim1, kernel_dim2, kernel_dim3, init='glorot_uniform', activation='linear', weights=None, border_mode='valid', subsample=(1, 1, 1), dim_ordering='default', W_regularizer=None, b_regularizer=None, activity_regularizer=None, W_constraint=None, b_constraint=None, bias=True, **kwargs): if dim_ordering == 'default': dim_ordering = K.image_dim_ordering() if border_mode not in {'valid', 'same'}: raise Exception('Invalid border mode for Convolution3D:', border_mode) self.nb_filter = nb_filter self.kernel_dim1 = kernel_dim1 self.kernel_dim2 = kernel_dim2 self.kernel_dim3 = kernel_dim3 self.init = initializations.get(init, dim_ordering=dim_ordering) self.activation = activations.get(activation) assert border_mode in {'valid', 'same'}, 'border_mode must be in {valid, same}' self.border_mode = border_mode self.subsample = tuple(subsample) assert dim_ordering in {'tf', 'th'}, 'dim_ordering must be in {tf, th}' self.dim_ordering = dim_ordering self.W_regularizer = regularizers.get(W_regularizer) self.b_regularizer = regularizers.get(b_regularizer) self.activity_regularizer = regularizers.get(activity_regularizer) self.W_constraint = constraints.get(W_constraint) self.b_constraint = constraints.get(b_constraint) self.bias = bias self.input_spec = [InputSpec(ndim=5)] self.initial_weights = weights super(Convolution3D, self).__init__(**kwargs) def build(self, input_shape): assert len(input_shape) == 5 self.input_spec = [InputSpec(shape=input_shape)] if self.dim_ordering == 'th': stack_size = input_shape[1] self.W_shape = (self.nb_filter, stack_size, self.kernel_dim1, self.kernel_dim2, self.kernel_dim3) elif self.dim_ordering == 'tf': stack_size = input_shape[4] self.W_shape = (self.kernel_dim1, self.kernel_dim2, self.kernel_dim3, stack_size, self.nb_filter) else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) self.W = self.init(self.W_shape, name='{}_W'.format(self.name)) if self.bias: self.b = K.zeros((self.nb_filter,), name='{}_b'.format(self.name)) self.trainable_weights = [self.W, self.b] else: self.trainable_weights = [self.W] self.regularizers = [] if self.W_regularizer: self.W_regularizer.set_param(self.W) self.regularizers.append(self.W_regularizer) if self.bias and self.b_regularizer: self.b_regularizer.set_param(self.b) self.regularizers.append(self.b_regularizer) if self.activity_regularizer: self.activity_regularizer.set_layer(self) self.regularizers.append(self.activity_regularizer) self.constraints = {} if self.W_constraint: self.constraints[self.W] = self.W_constraint if self.bias and self.b_constraint: self.constraints[self.b] = self.b_constraint if self.initial_weights is not None: self.set_weights(self.initial_weights) del self.initial_weights def get_output_shape_for(self, input_shape): if self.dim_ordering == 'th': conv_dim1 = input_shape[2] conv_dim2 = input_shape[3] conv_dim3 = input_shape[4] elif self.dim_ordering == 'tf': conv_dim1 = input_shape[1] conv_dim2 = input_shape[2] conv_dim3 = input_shape[3] else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) conv_dim1 = conv_output_length(conv_dim1, self.kernel_dim1, self.border_mode, self.subsample[0]) conv_dim2 = conv_output_length(conv_dim2, self.kernel_dim2, self.border_mode, self.subsample[1]) conv_dim3 = conv_output_length(conv_dim3, self.kernel_dim3, self.border_mode, self.subsample[2]) if self.dim_ordering == 'th': return (input_shape[0], self.nb_filter, conv_dim1, conv_dim2, conv_dim3) elif self.dim_ordering == 'tf': return (input_shape[0], conv_dim1, conv_dim2, conv_dim3, self.nb_filter) else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) def call(self, x, mask=None): input_shape = self.input_spec[0].shape output = K.conv3d(x, self.W, strides=self.subsample, border_mode=self.border_mode, dim_ordering=self.dim_ordering, volume_shape=input_shape, filter_shape=self.W_shape) if self.bias: if self.dim_ordering == 'th': output += K.reshape(self.b, (1, self.nb_filter, 1, 1, 1)) elif self.dim_ordering == 'tf': output += K.reshape(self.b, (1, 1, 1, 1, self.nb_filter)) else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) output = self.activation(output) return output def get_config(self): config = {'nb_filter': self.nb_filter, 'kernel_dim1': self.kernel_dim1, 'kernel_dim2': self.kernel_dim2, 'kernel_dim3': self.kernel_dim3, 'dim_ordering': self.dim_ordering, 'init': self.init.__name__, 'activation': self.activation.__name__, 'border_mode': self.border_mode, 'subsample': self.subsample, 'W_regularizer': self.W_regularizer.get_config() if self.W_regularizer else None, 'b_regularizer': self.b_regularizer.get_config() if self.b_regularizer else None, 'activity_regularizer': self.activity_regularizer.get_config() if self.activity_regularizer else None, 'W_constraint': self.W_constraint.get_config() if self.W_constraint else None, 'b_constraint': self.b_constraint.get_config() if self.b_constraint else None, 'bias': self.bias} base_config = super(Convolution3D, self).get_config() return dict(list(base_config.items()) + list(config.items())) class UpSampling1D(Layer): '''Repeat each temporal step `length` times along the time axis. # Arguments length: integer. Upsampling factor. # Input shape 3D tensor with shape: `(samples, steps, features)`. # Output shape 3D tensor with shape: `(samples, upsampled_steps, features)`. ''' def __init__(self, length=2, **kwargs): self.length = length self.input_spec = [InputSpec(ndim=3)] super(UpSampling1D, self).__init__(**kwargs) def get_output_shape_for(self, input_shape): length = self.length * input_shape[1] if input_shape[1] is not None else None return (input_shape[0], length, input_shape[2]) def call(self, x, mask=None): output = K.repeat_elements(x, self.length, axis=1) return output def get_config(self): config = {'length': self.length} base_config = super(UpSampling1D, self).get_config() return dict(list(base_config.items()) + list(config.items())) class UpSampling2D(Layer): '''Repeat the rows and columns of the data by size[0] and size[1] respectively. # Arguments size: tuple of 2 integers. The upsampling factors for rows and columns. dim_ordering: 'th' or 'tf'. In 'th' mode, the channels dimension (the depth) is at index 1, in 'tf' mode is it at index 3. It defaults to the `image_dim_ordering` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "th". # Input shape 4D tensor with shape: `(samples, channels, rows, cols)` if dim_ordering='th' or 4D tensor with shape: `(samples, rows, cols, channels)` if dim_ordering='tf'. # Output shape 4D tensor with shape: `(samples, channels, upsampled_rows, upsampled_cols)` if dim_ordering='th' or 4D tensor with shape: `(samples, upsampled_rows, upsampled_cols, channels)` if dim_ordering='tf'. ''' def __init__(self, size=(2, 2), dim_ordering='default', **kwargs): if dim_ordering == 'default': dim_ordering = K.image_dim_ordering() self.size = tuple(size) assert dim_ordering in {'tf', 'th'}, 'dim_ordering must be in {tf, th}' self.dim_ordering = dim_ordering self.input_spec = [InputSpec(ndim=4)] super(UpSampling2D, self).__init__(**kwargs) def get_output_shape_for(self, input_shape): if self.dim_ordering == 'th': width = self.size[0] * input_shape[2] if input_shape[2] is not None else None height = self.size[1] * input_shape[3] if input_shape[3] is not None else None return (input_shape[0], input_shape[1], width, height) elif self.dim_ordering == 'tf': width = self.size[0] * input_shape[1] if input_shape[1] is not None else None height = self.size[1] * input_shape[2] if input_shape[2] is not None else None return (input_shape[0], width, height, input_shape[3]) else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) def call(self, x, mask=None): return K.resize_images(x, self.size[0], self.size[1], self.dim_ordering) def get_config(self): config = {'size': self.size} base_config = super(UpSampling2D, self).get_config() return dict(list(base_config.items()) + list(config.items())) class UpSampling3D(Layer): '''Repeat the first, second and third dimension of the data by size[0], size[1] and size[2] respectively. # Arguments size: tuple of 3 integers. The upsampling factors for dim1, dim2 and dim3. dim_ordering: 'th' or 'tf'. In 'th' mode, the channels dimension (the depth) is at index 1, in 'tf' mode is it at index 4. It defaults to the `image_dim_ordering` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "th". # Input shape 5D tensor with shape: `(samples, channels, dim1, dim2, dim3)` if dim_ordering='th' or 5D tensor with shape: `(samples, dim1, dim2, dim3, channels)` if dim_ordering='tf'. # Output shape 5D tensor with shape: `(samples, channels, upsampled_dim1, upsampled_dim2, upsampled_dim3)` if dim_ordering='th' or 5D tensor with shape: `(samples, upsampled_dim1, upsampled_dim2, upsampled_dim3, channels)` if dim_ordering='tf'. ''' def __init__(self, size=(2, 2, 2), dim_ordering='default', **kwargs): if dim_ordering == 'default': dim_ordering = K.image_dim_ordering() self.size = tuple(size) assert dim_ordering in {'tf', 'th'}, 'dim_ordering must be in {tf, th}' self.dim_ordering = dim_ordering self.input_spec = [InputSpec(ndim=5)] super(UpSampling3D, self).__init__(**kwargs) def get_output_shape_for(self, input_shape): if self.dim_ordering == 'th': dim1 = self.size[0] * input_shape[2] if input_shape[2] is not None else None dim2 = self.size[1] * input_shape[3] if input_shape[3] is not None else None dim3 = self.size[2] * input_shape[4] if input_shape[4] is not None else None return (input_shape[0], input_shape[1], dim1, dim2, dim3) elif self.dim_ordering == 'tf': dim1 = self.size[0] * input_shape[1] if input_shape[1] is not None else None dim2 = self.size[1] * input_shape[2] if input_shape[2] is not None else None dim3 = self.size[2] * input_shape[3] if input_shape[3] is not None else None return (input_shape[0], dim1, dim2, dim3, input_shape[4]) else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) def call(self, x, mask=None): return K.resize_volumes(x, self.size[0], self.size[1], self.size[2], self.dim_ordering) def get_config(self): config = {'size': self.size} base_config = super(UpSampling3D, self).get_config() return dict(list(base_config.items()) + list(config.items())) class ZeroPadding1D(Layer): '''Zero-padding layer for 1D input (e.g. temporal sequence). # Arguments padding: int How many zeros to add at the beginning and end of the padding dimension (axis 1). # Input shape 3D tensor with shape (samples, axis_to_pad, features) # Output shape 3D tensor with shape (samples, padded_axis, features) ''' def __init__(self, padding=1, **kwargs): super(ZeroPadding1D, self).__init__(**kwargs) self.padding = padding self.input_spec = [InputSpec(ndim=3)] def get_output_shape_for(self, input_shape): length = input_shape[1] + self.padding * 2 if input_shape[1] is not None else None return (input_shape[0], length, input_shape[2]) def call(self, x, mask=None): return K.temporal_padding(x, padding=self.padding) def get_config(self): config = {'padding': self.padding} base_config = super(ZeroPadding1D, self).get_config() return dict(list(base_config.items()) + list(config.items())) class ZeroPadding2D(Layer): '''Zero-padding layer for 2D input (e.g. picture). # Arguments padding: tuple of int (length 2) How many zeros to add at the beginning and end of the 2 padding dimensions (axis 3 and 4). dim_ordering: 'th' or 'tf'. In 'th' mode, the channels dimension (the depth) is at index 1, in 'tf' mode is it at index 3. It defaults to the `image_dim_ordering` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "th". # Input shape 4D tensor with shape: (samples, depth, first_axis_to_pad, second_axis_to_pad) # Output shape 4D tensor with shape: (samples, depth, first_padded_axis, second_padded_axis) ''' def __init__(self, padding=(1, 1), dim_ordering='default', **kwargs): super(ZeroPadding2D, self).__init__(**kwargs) if dim_ordering == 'default': dim_ordering = K.image_dim_ordering() self.padding = tuple(padding) assert dim_ordering in {'tf', 'th'}, 'dim_ordering must be in {tf, th}' self.dim_ordering = dim_ordering self.input_spec = [InputSpec(ndim=4)] def get_output_shape_for(self, input_shape): if self.dim_ordering == 'th': width = input_shape[2] + 2 * self.padding[0] if input_shape[2] is not None else None height = input_shape[3] + 2 * self.padding[1] if input_shape[3] is not None else None return (input_shape[0], input_shape[1], width, height) elif self.dim_ordering == 'tf': width = input_shape[1] + 2 * self.padding[0] if input_shape[1] is not None else None height = input_shape[2] + 2 * self.padding[1] if input_shape[2] is not None else None return (input_shape[0], width, height, input_shape[3]) else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) def call(self, x, mask=None): return K.spatial_2d_padding(x, padding=self.padding, dim_ordering=self.dim_ordering) def get_config(self): config = {'padding': self.padding} base_config = super(ZeroPadding2D, self).get_config() return dict(list(base_config.items()) + list(config.items())) class ZeroPadding3D(Layer): '''Zero-padding layer for 3D data (spatial or spatio-temporal). # Arguments padding: tuple of int (length 3) How many zeros to add at the beginning and end of the 3 padding dimensions (axis 3, 4 and 5). dim_ordering: 'th' or 'tf'. In 'th' mode, the channels dimension (the depth) is at index 1, in 'tf' mode is it at index 4. It defaults to the `image_dim_ordering` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "th". # Input shape 5D tensor with shape: (samples, depth, first_axis_to_pad, second_axis_to_pad, third_axis_to_pad) # Output shape 5D tensor with shape: (samples, depth, first_padded_axis, second_padded_axis, third_axis_to_pad) ''' def __init__(self, padding=(1, 1, 1), dim_ordering='default', **kwargs): super(ZeroPadding3D, self).__init__(**kwargs) if dim_ordering == 'default': dim_ordering = K.image_dim_ordering() self.padding = tuple(padding) assert dim_ordering in {'tf', 'th'}, 'dim_ordering must be in {tf, th}' self.dim_ordering = dim_ordering self.input_spec = [InputSpec(ndim=5)] def get_output_shape_for(self, input_shape): if self.dim_ordering == 'th': dim1 = input_shape[2] + 2 * self.padding[0] if input_shape[2] is not None else None dim2 = input_shape[3] + 2 * self.padding[1] if input_shape[3] is not None else None dim3 = input_shape[4] + 2 * self.padding[2] if input_shape[4] is not None else None return (input_shape[0], input_shape[1], dim1, dim2, dim3) elif self.dim_ordering == 'tf': dim1 = input_shape[1] + 2 * self.padding[0] if input_shape[1] is not None else None dim2 = input_shape[2] + 2 * self.padding[1] if input_shape[2] is not None else None dim3 = input_shape[3] + 2 * self.padding[2] if input_shape[3] is not None else None return (input_shape[0], dim1, dim2, dim3, input_shape[4]) else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) def call(self, x, mask=None): return K.spatial_3d_padding(x, padding=self.padding, dim_ordering=self.dim_ordering) def get_config(self): config = {'padding': self.padding} base_config = super(ZeroPadding3D, self).get_config() return dict(list(base_config.items()) + list(config.items())) class Cropping1D(Layer): '''Cropping layer for 1D input (e.g. temporal sequence). It crops along the time dimension (axis 1). # Arguments cropping: tuple of int (length 2) How many units should be trimmed off at the beginning and end of the cropping dimension (axis 1). # Input shape 3D tensor with shape (samples, axis_to_crop, features) # Output shape 3D tensor with shape (samples, cropped_axis, features) ''' def __init__(self, cropping=(1, 1), **kwargs): super(Cropping1D, self).__init__(**kwargs) self.cropping = tuple(cropping) assert len(self.cropping) == 2, 'cropping must be a tuple length of 2' self.input_spec = [InputSpec(ndim=3)] def build(self, input_shape): self.input_spec = [InputSpec(shape=input_shape)] def get_output_shape_for(self, input_shape): length = input_shape[1] - self.cropping[0] - self.cropping[1] if input_shape[1] is not None else None return (input_shape[0], length, input_shape[2]) def call(self, x, mask=None): input_shape = self.input_spec[0].shape return x[:, self.cropping[0]:input_shape[1]-self.cropping[1], :] def get_config(self): config = {'cropping': self.cropping} base_config = super(Cropping1D, self).get_config() return dict(list(base_config.items()) + list(config.items())) class Cropping2D(Layer): '''Cropping layer for 2D input (e.g. picture). It crops along spatial dimensions, i.e. width and height. # Arguments cropping: tuple of tuple of int (length 2) How many units should be trimmed off at the beginning and end of the 2 cropping dimensions (width, height). dim_ordering: 'th' or 'tf'. In 'th' mode, the channels dimension (the depth) is at index 1, in 'tf' mode is it at index 3. It defaults to the `image_dim_ordering` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "th". # Input shape 4D tensor with shape: (samples, depth, first_axis_to_crop, second_axis_to_crop) # Output shape 4D tensor with shape: (samples, depth, first_cropped_axis, second_cropped_axis) # Examples ```python # Crop the input 2D images or feature maps model = Sequential() model.add(Cropping2D(cropping=((2, 2), (4, 4)), input_shape=(3, 28, 28))) # now model.output_shape == (None, 3, 24, 20) model.add(Convolution2D(64, 3, 3, border_mode='same)) model.add(Cropping2D(cropping=((2, 2), (2, 2)))) # now model.output_shape == (None, 64, 20, 16) ``` ''' def __init__(self, cropping=((0, 0), (0, 0)), dim_ordering='default', **kwargs): super(Cropping2D, self).__init__(**kwargs) if dim_ordering == 'default': dim_ordering = K.image_dim_ordering() self.cropping = tuple(cropping) assert len(self.cropping) == 2, 'cropping must be a tuple length of 2' assert len(self.cropping[0]) == 2, 'cropping[0] must be a tuple length of 2' assert len(self.cropping[1]) == 2, 'cropping[1] must be a tuple length of 2' assert dim_ordering in {'tf', 'th'}, 'dim_ordering must be in {tf, th}' self.dim_ordering = dim_ordering self.input_spec = [InputSpec(ndim=4)] def build(self, input_shape): self.input_spec = [InputSpec(shape=input_shape)] def get_output_shape_for(self, input_shape): if self.dim_ordering == 'th': return (input_shape[0], input_shape[1], input_shape[2] - self.cropping[0][0] - self.cropping[0][1], input_shape[3] - self.cropping[1][0] - self.cropping[1][1]) elif self.dim_ordering == 'tf': return (input_shape[0], input_shape[1] - self.cropping[0][0] - self.cropping[0][1], input_shape[2] - self.cropping[1][0] - self.cropping[1][1], input_shape[3]) else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) def call(self, x, mask=None): input_shape = self.input_spec[0].shape if self.dim_ordering == 'th': return x[:, :, self.cropping[0][0]:input_shape[2]-self.cropping[0][1], self.cropping[1][0]:input_shape[3]-self.cropping[1][1]] elif self.dim_ordering == 'tf': return x[:, self.cropping[0][0]:input_shape[1]-self.cropping[0][1], self.cropping[1][0]:input_shape[2]-self.cropping[1][1], :] def get_config(self): config = {'cropping': self.cropping} base_config = super(Cropping2D, self).get_config() return dict(list(base_config.items()) + list(config.items())) class Cropping3D(Layer): '''Cropping layer for 2D input (e.g. picture). # Arguments cropping: tuple of tuple of int (length 3) How many units should be trimmed off at the beginning and end of the 3 cropping dimensions (kernel_dim1, kernel_dim2, kernerl_dim3). dim_ordering: 'th' or 'tf'. In 'th' mode, the channels dimension (the depth) is at index 1, in 'tf' mode is it at index 4. It defaults to the `image_dim_ordering` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "th". # Input shape 5D tensor with shape: (samples, depth, first_axis_to_crop, second_axis_to_crop, third_axis_to_crop) # Output shape 5D tensor with shape: (samples, depth, first_cropped_axis, second_cropped_axis, third_cropped_axis) ''' def __init__(self, cropping=((1, 1), (1, 1), (1, 1)), dim_ordering='default', **kwargs): super(Cropping3D, self).__init__(**kwargs) if dim_ordering == 'default': dim_ordering = K.image_dim_ordering() self.cropping = tuple(cropping) assert len(self.cropping) == 3, 'cropping must be a tuple length of 3' assert len(self.cropping[0]) == 2, 'cropping[0] must be a tuple length of 2' assert len(self.cropping[1]) == 2, 'cropping[1] must be a tuple length of 2' assert len(self.cropping[2]) == 2, 'cropping[2] must be a tuple length of 2' assert dim_ordering in {'tf', 'th'}, 'dim_ordering must be in {tf, th}' self.dim_ordering = dim_ordering self.input_spec = [InputSpec(ndim=5)] def build(self, input_shape): self.input_spec = [InputSpec(shape=input_shape)] def get_output_shape_for(self, input_shape): if self.dim_ordering == 'th': dim1 = input_shape[2] - self.cropping[0][0] - self.cropping[0][1] if input_shape[2] is not None else None dim2 = input_shape[3] - self.cropping[1][0] - self.cropping[1][1] if input_shape[3] is not None else None dim3 = input_shape[4] - self.cropping[2][0] - self.cropping[2][1] if input_shape[4] is not None else None return (input_shape[0], input_shape[1], dim1, dim2, dim3) elif self.dim_ordering == 'tf': dim1 = input_shape[1] - self.cropping[0][0] - self.cropping[0][1] if input_shape[1] is not None else None dim2 = input_shape[2] - self.cropping[1][0] - self.cropping[1][1] if input_shape[2] is not None else None dim3 = input_shape[3] - self.cropping[2][0] - self.cropping[2][1] if input_shape[3] is not None else None return (input_shape[0], dim1, dim2, dim3, input_shape[4]) else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) def call(self, x, mask=None): input_shape = self.input_spec[0].shape if self.dim_ordering == 'th': return x[:, :, self.cropping[0][0]:input_shape[2]-self.cropping[0][1], self.cropping[1][0]:input_shape[3]-self.cropping[1][1], self.cropping[2][0]:input_shape[4]-self.cropping[2][1]] elif self.dim_ordering == 'tf': return x[:, self.cropping[0][0]:input_shape[1]-self.cropping[0][1], self.cropping[1][0]:input_shape[2]-self.cropping[1][1], self.cropping[2][0]:input_shape[3]-self.cropping[2][1], :] def get_config(self): config = {'cropping': self.cropping} base_config = super(Cropping3D, self).get_config() return dict(list(base_config.items()) + list(config.items())) # Aliases Conv1D = Convolution1D Conv2D = Convolution2D Conv3D = Convolution3D Deconv2D = Deconvolution2D AtrousConv2D = AtrousConvolution2D SeparableConv2D = SeparableConvolution2D
mit
julienmoumne/hotshell
examples/nested/nested.hs.js
318
var item = require('hotshell').item item({desc: 'nested', wd: '../docker'}, function () { item({key: 'd', desc: 'docker', cmd: 'hs -f docker.hs.js'}) item({key: 'c', desc: 'docker-compose', cmd: 'hs -f docker-compose.hs.js'}) item({key: 'm', desc: 'docker-machine', cmd: 'hs -f docker-machine.hs.js'}) })
mit
petehouston/laio
app/Providers/ObserverServiceProvider.php
471
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; class ObserverServiceProvider extends ServiceProvider { /** * Bootstrap any necessary services. * * @return void */ public function boot() { // Observe event // For example: // User::observe( new UserObserver ); } /** * Register the service provider. * * @return void */ public function register() { } }
mit
martinusso/xml-signer
tests/XmlSigner/CertificateTest.php
1501
<?php namespace XmlSigner\Tests; use XmlSigner\Certificate; final class CertificateTest extends \PHPUnit\Framework\TestCase { public function testInvalidPrivateKey() { $needle = 'Unable to read certificate, get follow error:'; $content = $this->getContentCertPfx(); $fail = false; try { $cert = Certificate::readPfx($content, 'invalid_password'); } catch (\XmlSigner\Exception\CertificateException $e) { $fail = true; $pos = strpos($e->getMessage(), $needle); $this->assertSame(0, $pos, 'unexpected exception message'); } (!$fail) && $this->fail("No Exceptions were thrown."); } public function testReadPfx() { $dataToSign = 'Data to sign'; $expectedSignature = 'BNlfrfWIdAHDh5aVWByf6s2t0s27+lCB1A7qtsazXQbYDg9qf20zawh46KhHOQGTrU8DEvmbYMRwqgCEvxTxk66XQF/p9ChSeILkre+h+JqyJvVGOgXi81w1Sw04jBbcSZeCl5fhESMXUcSmtVzm7oQCkygqXfCGqvpygEWS7yk='; $content = $this->getContentCertPfx(); $cert = Certificate::readPfx($content, 'associacao'); $this->assertInstanceOf(Certificate::class, $cert); $signature = $cert->sign($dataToSign); $this->assertEquals($expectedSignature, base64_encode($signature)); $verified = $cert->verify($dataToSign, $signature); $this->assertTrue($verified); } private function getContentCertPfx() { return file_get_contents('tests/resources/cert.pfx'); } }
mit
Glifery/Maxplayer
src/Glifery/VkApiBundle/Model/ApiRequest.php
1358
<?php namespace Glifery\VkApiBundle\Model; use Doctrine\Common\Collections\ArrayCollection; class ApiRequest { /** @var string */ private $method; /** @var ArrayCollection */ private $params; public function __construct() { $this->params = new ArrayCollection(); } /** * @param string $method * @return $this */ public function setMethod($method) { $this->method = $method; return $this; } /** * @return string */ public function getMethod() { return $this->method; } /** * @param array $params * @return $this */ public function setParams($params) { $this->params->clear(); foreach ($params as $name => $value) { $this->addParam($name, $value); } return $this; } /** * @return array */ public function getParams() { return $this->params->toArray(); } /** * @param string $name * @param mixed $value * @return $this */ public function addParam($name, $value) { $this->params->set($name, $value); return $this; } /** * @param $name * @return mixed|null */ public function getParam($name) { return $this->params->get($name); } }
mit
snipsco/snipsskills
snipsmanager/templates/setup.py
360
from setuptools import setup setup( name='', version='0.0.1', description='{{description}}', author='{{author}}', author_email='{{email}}', download_url='', license='MIT', install_requires=[], setup_requires=['green'], keywords=['snips'], include_package_data=True, packages=[ '{{project_name}}' ] )
mit
coshx/coshx
spec/views/quotes/index.html.haml_spec.rb
652
require 'spec_helper' describe "quotes/index" do before(:each) do assign(:quotes, [ stub_model(Quote, :text => "Text", :author => "Author", :project_id => 1 ), stub_model(Quote, :text => "Text", :author => "Author", :project_id => 1 ) ]) end it "renders a list of quotes" do render # Run the generator again with the --webrat flag if you want to use webrat matchers assert_select "tr>td", :text => "Text".to_s, :count => 2 assert_select "tr>td", :text => "Author".to_s, :count => 2 assert_select "tr>td", :text => 1.to_s, :count => 2 end end
mit
jorgezaccaro/microapi
koa/wrappers.js
1048
'use strict' /** Wraps route callback handlers to implement the (context, next) signature **/ function callback(handler) { return async (context) => { try { let {body, status} = await handler(context) context.response.status = status context.response.body = body } catch(exception) { if (typeof handler.exceptions === 'function') { let {body, status} = await handler.exceptions(context, exception) context.response.status = status context.response.body = body } else { // DO SOMETHING TO PREVENT EXCEPTIONS FROM BEING SWALLOWED context.response.body = {error: {name: exception.message}} } } } } /** Wraps middleware handlers to implement the (context, next) signature **/ function middleware(handler) { return async (context, next) => { try { await handler(context) await next() } catch(error) { context.status = error.status context.response.body = error.body } } } module.exports = { callback, middleware }
mit
nadiabarache/Cebo-E-papeterie
src/Users/UtilisateurBundle/DataFixtures/ORM/UtilisateursAdressesData.php
1527
<?php namespace Users\utilisateurBundle\DataFixtures\ORM; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\OrderedFixtureInterface; use Doctrine\Common\Persistence\ObjectManager; use EP\EpapeterieBundle\Entity\UtilisateursAdresses; class UtilisateursAdressesData extends AbstractFixture implements OrderedFixtureInterface { public function load(ObjectManager $manager) { $adresse1 = new UtilisateursAdresses(); $adresse1->setUtilisateurs($this->getReference('utilisateur1')); $adresse1->setNom('Catelain'); $adresse1->setPrenom('Benjamin'); $adresse1->setTelephone('0600000000'); $adresse1->setAdresse('3 rue alberta rubosca'); $adresse1->setCp('76600'); $adresse1->setPays('France'); $adresse1->setVille('Le Havre'); $adresse1->setComplement('face à l\'église'); $manager->persist($adresse1); $adresse2 = new UtilisateursAdresses(); $adresse2->setUtilisateurs($this->getReference('utilisateur3')); $adresse2->setNom('premier'); $adresse2->setPrenom('albert'); $adresse2->setTelephone('0600000000'); $adresse2->setAdresse('5 rue rubosca'); $adresse2->setCp('76600'); $adresse2->setPays('France'); $adresse2->setVille('Le Havre'); $adresse2->setComplement('face à la plage'); $manager->persist($adresse2); $manager->flush(); } public function getOrder() { return 6; } }
mit
mark-keast/angular2-seed
src/client/app/form-control-messages/control-messages.component.ts
513
import { ControlMessageModule } from './control-messages.module'; import { Component, Input } from '@angular/core'; import { FormControl } from '@angular/forms'; @Component({ moduleId:module.id, selector:'control-messages', templateUrl:'control-messages.component.html' }) export class ControlMessagesComponent { @Input() public control: FormControl; public get errors(){ if (this.control.errors && this.control.dirty) { return true; } return false; } }
mit
HoBi/BI-PA2
semestral-work/src/menu/MenuItem.cpp
205
#include <ncurses.h> #include <string> #include "MenuItem.hpp" MenuItem::MenuItem (WINDOW* window, const std::string text) : window(window), text(text), ctext(text.c_str()) {} MenuItem::~MenuItem () {}
mit
anugoon1374/WVEF
MM-WebUI/BI.Interface/Areas/HelpPage/ModelDescriptions/ComplexTypeModelDescription.cs
399
using System.Collections.ObjectModel; namespace BI.Interface.Areas.HelpPage.ModelDescriptions { public class ComplexTypeModelDescription : ModelDescription { public ComplexTypeModelDescription() { Properties = new Collection<ParameterDescription>(); } public Collection<ParameterDescription> Properties { get; private set; } } }
mit
Jarinus/osrs-private-server
source/server/src/nl/osrs/model/player/packets/MagicOnItems.java
671
package nl.osrs.model.player.packets; import nl.osrs.model.player.Client; import nl.osrs.model.player.PacketType; /** * Magic on items **/ @SuppressWarnings("all") public class MagicOnItems implements PacketType { @Override public void processPacket(Client c, int packetType, int packetSize) { int slot = c.getInStream().readSignedWord(); int itemId = c.getInStream().readSignedWordA(); int junk = c.getInStream().readSignedWord(); int spellId = c.getInStream().readSignedWordA(); c.getTaskScheduler().stopTasks(); c.getPA().removeAllWindows(); c.usingMagic = true; c.getPA().magicOnItems(slot, itemId, spellId); c.usingMagic = false; } }
mit
markovandooren/jlo
src/main/java/org/aikodi/jlo/model/subobject/DirectSubtypeRelation.java
722
package org.aikodi.jlo.model.subobject; import org.aikodi.chameleon.exception.ChameleonProgrammerException; import org.aikodi.chameleon.oo.type.Type; import org.aikodi.chameleon.oo.type.TypeReference; import org.aikodi.chameleon.oo.type.inheritance.SubtypeRelation; public class DirectSubtypeRelation extends IncorporatingSubtypeRelation { public DirectSubtypeRelation(Type inherited) { _inherited = inherited; } private Type _inherited; @Override public Type superClass() { return _inherited; } @Override public TypeReference superClassReference() { throw new ChameleonProgrammerException(); } protected SubtypeRelation cloneSelf() { return new DirectSubtypeRelation(superClass()); } }
mit
cdnjs/cdnjs
ajax/libs/froala-editor/4.0.3/js/languages/it.js
11281
/*! * froala_editor v4.0.3 (https://www.froala.com/wysiwyg-editor) * License https://froala.com/wysiwyg-editor/terms/ * Copyright 2014-2021 Froala Labs */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('froala-editor')) : typeof define === 'function' && define.amd ? define(['froala-editor'], factory) : (factory(global.FroalaEditor)); }(this, (function (FE) { 'use strict'; FE = FE && FE.hasOwnProperty('default') ? FE['default'] : FE; /** * Italian */ FE.LANGUAGE['it'] = { translation: { // Place holder 'Type something': 'Digita qualcosa', //Missing translations 'Text Color': 'Colore del testo', 'Background Color': 'Colore di sfondo', 'Inline Class': 'Classe inline', 'Default': 'Predefinito', 'Lower Alpha': 'Alfa minuscole', 'Lower Greek': 'Greche minuscole', 'Lower Roman': 'Romane minuscole', 'Upper Alpha': 'Alfa maiuscole', 'Upper Roman': 'Romane maiuscole', 'Circle': 'Cerchio', 'Disc': 'Disco', 'Square': 'Quadrato', 'Double': 'Doppio', 'Download PDF': 'Scarica il PDF', // Basic formatting 'Bold': 'Grassetto', 'Italic': 'Corsivo', 'Underline': 'Sottolineato', 'Strikethrough': 'Barrato', // Main buttons 'Insert': 'Inserisci', 'Delete': 'Cancella', 'Cancel': 'Cancella', 'OK': 'OK', 'Back': 'Indietro', 'Remove': 'Rimuovi', 'More': "Di pi\xF9", 'Update': 'Aggiorna', 'Style': 'Stile', // Font 'Font Family': 'Carattere', 'Font Size': 'Dimensione Carattere', // Colors 'Colors': 'Colori', 'Background': 'Sfondo', 'Text': 'Testo', 'HEX Color': 'Colore Esadecimale', // Paragraphs 'Paragraph Format': 'Formattazione', 'Normal': 'Normale', 'Code': 'Codice', 'Heading 1': 'Intestazione 1', 'Heading 2': 'Intestazione 2', 'Heading 3': 'Intestazione 3', 'Heading 4': 'Intestazione 4', // Style 'Paragraph Style': 'Stile Paragrafo', 'Inline Style': 'Stile in Linea', // Alignment 'Align': 'Allinea', 'Align Left': 'Allinea a Sinistra', 'Align Center': 'Allinea al Cento', 'Align Right': 'Allinea a Destra', 'Align Justify': 'Giustifica', 'None': 'Nessuno', // Lists 'Ordered List': 'Elenchi Numerati', 'Unordered List': 'Elenchi Puntati', // Indent 'Decrease Indent': 'Riduci Rientro', 'Increase Indent': 'Aumenta Rientro', // Links 'Insert Link': 'Inserisci Link', 'Open in new tab': 'Apri in nuova scheda', 'Open Link': 'Apri Link', 'Edit Link': 'Modifica Link', 'Unlink': 'Rimuovi Link', 'Choose Link': 'Scegli Link', // Images 'Insert Image': 'Inserisci Immagine', 'Upload Image': 'Carica Immagine', 'By URL': 'Inserisci URL', 'Browse': 'Sfoglia', 'Drop image': 'Rilascia immagine', 'or click': 'oppure clicca qui', 'Manage Images': 'Gestione Immagini', 'Loading': 'Caricamento', 'Deleting': 'Eliminazione', 'Tags': 'Etichetta', 'Are you sure? Image will be deleted.': "Sei sicuro? L'immagine verr\xE0 cancellata.", 'Replace': 'Sostituisci', 'Uploading': 'Caricamento', 'Loading image': 'Caricamento immagine', 'Display': 'Visualizzazione', 'Inline': 'In Linea', 'Break Text': 'Separa dal Testo', 'Alternative Text': 'Testo Alternativo', 'Change Size': 'Cambia Dimensioni', 'Width': 'Larghezza', 'Height': 'Altezza', 'Something went wrong. Please try again.': 'Qualcosa non ha funzionato. Riprova, per favore.', 'Image Caption': 'Didascalia', 'Advanced Edit': 'Avanzato', // Video 'Insert Video': 'Inserisci Video', 'Embedded Code': 'Codice Incorporato', 'Paste in a video URL': 'Incolla l\'URL del video', 'Drop video': 'Rilascia video', 'Your browser does not support HTML5 video.': 'Il tuo browser non supporta i video html5.', 'Upload Video': 'Carica Video', // Tables 'Insert Table': 'Inserisci Tabella', 'Table Header': 'Intestazione Tabella', 'Remove Table': 'Rimuovi Tabella', 'Table Style': 'Stile Tabella', 'Horizontal Align': 'Allineamento Orizzontale', 'Row': 'Riga', 'Insert row above': 'Inserisci una riga prima', 'Insert row below': 'Inserisci una riga dopo', 'Delete row': 'Cancella riga', 'Column': 'Colonna', 'Insert column before': 'Inserisci una colonna prima', 'Insert column after': 'Inserisci una colonna dopo', 'Delete column': 'Cancella colonna', 'Cell': 'Cella', 'Merge cells': 'Unisci celle', 'Horizontal split': 'Dividi in orizzontale', 'Vertical split': 'Dividi in verticale', 'Cell Background': 'Sfondo Cella', 'Vertical Align': 'Allineamento Verticale', 'Top': 'Alto', 'Middle': 'Centro', 'Bottom': 'Basso', 'Align Top': 'Allinea in Alto', 'Align Middle': 'Allinea al Centro', 'Align Bottom': 'Allinea in Basso', 'Cell Style': 'Stile Cella', // Files 'Upload File': 'Carica File', 'Drop file': 'Rilascia file', // Emoticons 'Emoticons': 'Emoticon', 'Grinning face': 'Sorridente', 'Grinning face with smiling eyes': 'Sorridente con gli occhi sorridenti', 'Face with tears of joy': 'Con lacrime di gioia', 'Smiling face with open mouth': 'Sorridente con la bocca aperta', 'Smiling face with open mouth and smiling eyes': 'Sorridente con la bocca aperta e gli occhi sorridenti', 'Smiling face with open mouth and cold sweat': 'Sorridente con la bocca aperta e sudore freddo', 'Smiling face with open mouth and tightly-closed eyes': 'Sorridente con la bocca aperta e gli occhi stretti', 'Smiling face with halo': 'Sorridente con aureola', 'Smiling face with horns': 'Diavolo sorridente', 'Winking face': 'Ammiccante', 'Smiling face with smiling eyes': 'Sorridente imbarazzato', 'Face savoring delicious food': 'Goloso', 'Relieved face': 'Rassicurato', 'Smiling face with heart-shaped eyes': 'Sorridente con gli occhi a forma di cuore', 'Smiling face with sunglasses': 'Sorridente con gli occhiali da sole', 'Smirking face': 'Compiaciuto', 'Neutral face': 'Neutro', 'Expressionless face': 'Inespressivo', 'Unamused face': 'Annoiato', 'Face with cold sweat': 'Sudare freddo', 'Pensive face': 'Pensieroso', 'Confused face': 'Perplesso', 'Confounded face': 'Confuso', 'Kissing face': 'Bacio', 'Face throwing a kiss': 'Manda un bacio', 'Kissing face with smiling eyes': 'Bacio con gli occhi sorridenti', 'Kissing face with closed eyes': 'Bacio con gli occhi chiusi', 'Face with stuck out tongue': 'Linguaccia', 'Face with stuck out tongue and winking eye': 'Linguaccia ammiccante', 'Face with stuck out tongue and tightly-closed eyes': 'Linguaccia con occhi stretti', 'Disappointed face': 'Deluso', 'Worried face': 'Preoccupato', 'Angry face': 'Arrabbiato', 'Pouting face': 'Imbronciato', 'Crying face': 'Pianto', 'Persevering face': 'Perseverante', 'Face with look of triumph': 'Trionfante', 'Disappointed but relieved face': 'Deluso ma rassicurato', 'Frowning face with open mouth': 'Accigliato con la bocca aperta', 'Anguished face': 'Angosciato', 'Fearful face': 'Pauroso', 'Weary face': 'Stanco', 'Sleepy face': 'Assonnato', 'Tired face': 'Snervato', 'Grimacing face': 'Smorfia', 'Loudly crying face': 'Pianto a gran voce', 'Face with open mouth': 'Bocca aperta', 'Hushed face': 'Silenzioso', 'Face with open mouth and cold sweat': 'Bocca aperta e sudore freddo', 'Face screaming in fear': 'Urlante dalla paura', 'Astonished face': 'Stupito', 'Flushed face': 'Arrossito', 'Sleeping face': 'Addormentato', 'Dizzy face': 'Stordito', 'Face without mouth': 'Senza parole', 'Face with medical mask': 'Malattia infettiva', // Line breaker 'Break': 'Separatore', // Math 'Subscript': 'Pedice', 'Superscript': 'Apice', // Full screen 'Fullscreen': 'Schermo intero', // Horizontal line 'Insert Horizontal Line': 'Inserisci Divisore Orizzontale', // Clear formatting 'Clear Formatting': 'Cancella Formattazione', // Save 'Save': 'Salvare', // Undo, redo 'Undo': 'Annulla', 'Redo': 'Ripeti', // Select all 'Select All': 'Seleziona Tutto', // Code view 'Code View': 'Visualizza Codice', // Quote 'Quote': 'Citazione', 'Increase': 'Aumenta', 'Decrease': 'Diminuisci', // Quick Insert 'Quick Insert': 'Inserimento Rapido', // Spcial Characters 'Special Characters': 'Caratteri Speciali', 'Latin': 'Latino', 'Greek': 'Greco', 'Cyrillic': 'Cirillico', 'Punctuation': 'Punteggiatura', 'Currency': 'Valuta', 'Arrows': 'Frecce', 'Math': 'Matematica', 'Misc': 'Misc', // Print. 'Print': 'Stampa', // Spell Checker. 'Spell Checker': 'Correttore Ortografico', // Help 'Help': 'Aiuto', 'Shortcuts': 'Scorciatoie', 'Inline Editor': 'Editor in Linea', 'Show the editor': 'Mostra Editor', 'Common actions': 'Azioni comuni', 'Copy': 'Copia', 'Cut': 'Taglia', 'Paste': 'Incolla', 'Basic Formatting': 'Formattazione di base', 'Increase quote level': 'Aumenta il livello di citazione', 'Decrease quote level': 'Diminuisci il livello di citazione', 'Image / Video': 'Immagine / Video', 'Resize larger': "Pi\xF9 grande", 'Resize smaller': "Pi\xF9 piccolo", 'Table': 'Tabella', 'Select table cell': 'Seleziona la cella della tabella', 'Extend selection one cell': 'Estendi la selezione di una cella', 'Extend selection one row': 'Estendi la selezione una riga', 'Navigation': 'Navigazione', 'Focus popup / toolbar': 'Metti a fuoco la barra degli strumenti', 'Return focus to previous position': 'Rimetti il fuoco sulla posizione precedente', // Embed.ly 'Embed URL': 'Incorpora URL', 'Paste in a URL to embed': 'Incolla un URL da incorporare', // Word Paste. 'The pasted content is coming from a Microsoft Word document. Do you want to keep the format or clean it up?': 'Il contenuto incollato proviene da un documento di Microsoft Word. Vuoi mantenere la formattazione di Word o pulirlo?', 'Keep': 'Mantieni', 'Clean': 'Pulisci', 'Word Paste Detected': "\xC8 stato rilevato un incolla da Word", // Character Counter 'Characters': 'Caratteri', 'Words': 'Parole', // More Buttons 'More Text': 'Altro Testo', 'More Paragraph': 'Altro Paragrafo', 'More Rich': 'Altro Ricco', 'More Misc': 'Altro Varie' }, direction: 'ltr' }; }))); //# sourceMappingURL=it.js.map
mit
micmc/compta
lib/compta/server/api/compte.py
4506
#!/usr/bin/python # -*- coding: utf8 -*- """ Application to create server for compta """ from compta.server.api.bottle import response, request, abort from json import dumps, loads #from sqlalchemy import desc from sqlalchemy.orm.exc import NoResultFound from sqlalchemy.exc import IntegrityError #from sqlalchemy.sql import func #from compta.db.base import Base from compta.db.compte import Compte from compta.db.compte import Compte from compta.server.api.server import App app = App().server @app.get('/compte') @app.get(r'/compte/<id:int>') @app.get(r'/compte/<nom:re:[a-zA-Z\ ]+>') @app.get(r'/banque/<banque_id:int>/compte') @app.get(r'/banque/<banque_id:int>/compte/<id:int>') @app.get('/banque/<banque_id:int>/compte/<nom:re:[a-zA-Z\ ]+>') def list_compte(db, id=None, nom=None, banque_id=None): """ List compte """ filter = {} if id: filter['id'] = id elif nom: filter['nom'] = nom elif banque_id: filter['banque_id'] = banque_id else: filter = App.get_filter(request.query.filter) sort = App.get_sort(request.query.sort) comptes = db.query(Compte) if filter: for column, value in filter.iteritems(): if not isinstance(value, list): comptes = comptes.filter(getattr(Compte, column) == value) else: comptes = comptes.filter(getattr(Compte, column).in_(value)) if sort: for column in sort: comptes = comptes.order_by(getattr(Compte, column)) else: comptes = comptes.order_by(Compte.nom) try: comptes = comptes.all() except NoResultFound: abort(404, "ID not found") if not comptes: abort(404, "ID not found") list_comptes = [] attributs = App.get_attribut(request.query.attribut) if attributs: for compte in comptes: dict_attributs = {} for attribut in attributs: dict_attributs[attribut] = getattr(compte, attribut) list_comptes.append(dict_attributs) else: for compte in comptes: list_comptes.append({'id': compte.id, 'nom': compte.nom, 'numero': compte.numero, 'cle': compte.cle, 'type': compte.type, 'archive': compte.archive, 'banque_id': compte.banque_id, }) return dumps(list_comptes) @app.post('/jtable/ListCompte') def list_compte_jtable(db): json_list = list_compte(db) data_list = loads(json_list) data = { "Result": "OK", "Records": data_list } return dumps(data) @app.post('/compte') def insert_compte(db): """ Create a compte """ entity = App.check_data(Compte, request.body.readline()) if entity: compte = Compte() for column, value in entity.iteritems(): setattr(compte, column, value) db.add(compte) try: db.commit() except IntegrityError as ex: abort(404, ex.args) response.status = 201 response.headers["Location"] = "/compte/%s" % (compte.id,) compte = loads(list_compte(db, compte.id)) return compte[0] @app.put(r'/compte/<id:int>') def update_compte(db, id=None): """ Update information for a compte """ entity = App.check_data(Compte, request.body.readline()) if entity: try: compte = db.query(Compte).\ filter(Compte.id == id).\ one() except NoResultFound: abort(404, "ID not found") for column, value in entity.iteritems(): if column == 'archive': setattr(compte, "archive", App.convert_value(value) ) else: setattr(compte, column, value) try: db.commit() compte = loads(list_compte(db, compte.id)) return compte[0] except IntegrityError as ex: abort(404, ex.args) @app.delete(r'/compte/<id:int>') def delete_compte(db, id=None): """ Delete a compte """ try: compte = db.query(Compte).\ filter(Compte.id == id).\ one() except NoResultFound: abort(404, "ID not found") db.delete(compte) db.commit() return dumps({'id': id})
mit
renoke/data2pdf
test/test_data2pdf.rb
854
require 'helper' class TestData2pdf < Test::Unit::TestCase should '#command call binary and quiet_option methods' do Data2pdf.expects(:binary).returns('engine') Data2pdf.expects(:quiet_option).returns('-q') (assert_equal 'engine -q foo.html foo.pdf', (Data2pdf.send :command, 'foo.html', 'foo.pdf')) end should '#render return pdf file name if destination is file' do Data2pdf.stubs(:source).returns(['some-file.html', File]) Data2pdf.stubs(:destination).returns(['some-file.pdf', File]) Data2pdf.stubs(:stylesheets).returns(nil) Data2pdf.stubs(:binary).returns('engine') Data2pdf.stubs(:quiet_option).returns('-q') io = IO.popen('ls','w+') IO.stubs(:popen).returns(io) (assert_equal 'some-file.pdf', (Data2pdf.render 'some-file.html', 'some-file.pdf')) end end
mit
rizumu/pinax-documents
pinax/documents/templatetags/documents_tags.py
298
from django.template import Library from ..utils import convert_bytes register = Library() @register.filter def can_share(member, user): if member is None: return False return member.can_share(user) @register.filter def readable_bytes(bytes): return convert_bytes(bytes)
mit
gallarotti/collaborative-minds
client/scripts/services/TestsSvc.js
509
collaborativeMindsApp.service("TestsSvc", function($resource) { return $resource("http://localhost:3000/cards/:listId", {listId:"@id"}, { createMultiple: { method:'POST', isArray:false, url:"http://localhost:3000/cards/tests/createMultiple" }, archiveMultiple: { method:'POST', isArray:false, url:"http://localhost:3000/cards/tests/archiveMultiple" } } ); });
mit
vitaly/facebooker-old
lib/facebooker/rails/controller.rb
6908
require 'facebooker' module Facebooker module Rails module Controller def self.included(controller) controller.extend(ClassMethods) controller.before_filter :set_fbml_format controller.helper_attr :facebook_session_parameters end def facebook_session @facebook_session end def facebook_session_parameters {:fb_sig_session_key=>params[:fb_sig_session_key]} end def set_facebook_session returning session_set = session_already_secured? || secure_with_token! || secure_with_facebook_params! do if session_set capture_facebook_friends_if_available! Session.current = facebook_session end end end def facebook_params @facebook_params ||= verified_facebook_params end private def session_already_secured? (@facebook_session = session[:facebook_session]) && session[:facebook_session].secured? end def secure_with_token! if params['auth_token'] @facebook_session = new_facebook_session @facebook_session.auth_token = params['auth_token'] @facebook_session.secure! session[:facebook_session] = @facebook_session end end def secure_with_facebook_params! return unless request_is_for_a_facebook_canvas? if ['user', 'session_key'].all? {|element| facebook_params[element]} @facebook_session = new_facebook_session @facebook_session.secure_with!(facebook_params['session_key'], facebook_params['user'], facebook_params['expires']) session[:facebook_session] = @facebook_session end end def create_new_facebook_session_and_redirect! session[:facebook_session] = new_facebook_session redirect_to session[:facebook_session].login_url unless @installation_required false end def new_facebook_session Facebooker::Session.create(Facebooker::Session.api_key, Facebooker::Session.secret_key) end def capture_facebook_friends_if_available! return unless request_is_for_a_facebook_canvas? if friends = facebook_params['friends'] facebook_session.user.friends = friends.map do |friend_uid| User.new(friend_uid, facebook_session) end end end def blank?(value) (value == '0' || value.nil? || value == '') end def verified_facebook_params facebook_sig_params = params.inject({}) do |collection, pair| collection[pair.first.sub(/^fb_sig_/, '')] = pair.last if pair.first[0,7] == 'fb_sig_' collection end verify_signature(facebook_sig_params,params['fb_sig']) facebook_sig_params.inject(HashWithIndifferentAccess.new) do |collection, pair| collection[pair.first] = facebook_parameter_conversions[pair.first].call(pair.last) collection end end def earliest_valid_session 48.hours.ago end def verify_signature(facebook_sig_params,expected_signature) raw_string = facebook_sig_params.map{ |*args| args.join('=') }.sort.join actual_sig = Digest::MD5.hexdigest([raw_string, Facebooker::Session.secret_key].join) raise Facebooker::Session::IncorrectSignature if actual_sig != expected_signature raise Facebooker::Session::SignatureTooOld if Time.at(facebook_sig_params['time'].to_f) < earliest_valid_session true end def facebook_parameter_conversions @facebook_parameter_conversions ||= Hash.new do |hash, key| lambda{|value| value} end.merge( 'time' => lambda{|value| Time.at(value.to_f)}, 'in_canvas' => lambda{|value| !blank?(value)}, 'added' => lambda{|value| !blank?(value)}, 'expires' => lambda{|value| blank?(value) ? nil : Time.at(value.to_f)}, 'friends' => lambda{|value| value.split(/,/)} ) end def redirect_to(*args) if request_is_for_a_facebook_canvas? render :text => fbml_redirect_tag(*args) else super end end def fbml_redirect_tag(url) "<fb:redirect url=\"#{url_for(url)}\" />" end def request_is_for_a_facebook_canvas? !params['fb_sig_in_canvas'].blank? end def request_is_facebook_ajax? params["fb_sig_is_mockajax"]=="1" || params["fb_sig_is_ajax"]=="1" end def xml_http_request? request_is_facebook_ajax? || super end def application_is_installed? facebook_params['added'] end def ensure_has_status_update has_extended_permission?("status_update") || application_needs_permission("status_update") end def ensure_has_photo_upload has_extended_permission?("photo_upload") || application_needs_permission("photo_upload") end def ensure_has_create_listing has_extended_permission?("create_listing") || application_needs_permission("create_listing") end def application_needs_permission(perm) redirect_to(facebook_session.permission_url(perm)) end def has_extended_permission?(perm) params["fb_sig_ext_perms"] and params["fb_sig_ext_perms"].include?(perm) end def ensure_authenticated_to_facebook set_facebook_session || create_new_facebook_session_and_redirect! end def ensure_application_is_installed_by_facebook_user @installation_required = true returning ensure_authenticated_to_facebook && application_is_installed? do |authenticated_and_installed| application_is_not_installed_by_facebook_user unless authenticated_and_installed end end def application_is_not_installed_by_facebook_user redirect_to session[:facebook_session].install_url end def set_fbml_format params[:format]="fbml" if request_is_for_a_facebook_canvas? or request_is_facebook_ajax? end module ClassMethods # # Creates a filter which reqires a user to have already authenticated to # Facebook before executing actions. Accepts the same optional options hash which # before_filter and after_filter accept. def ensure_authenticated_to_facebook(options = {}) before_filter :ensure_authenticated_to_facebook, options end def ensure_application_is_installed_by_facebook_user(options = {}) before_filter :ensure_application_is_installed_by_facebook_user, options end end end end end
mit
kidshenlong/warpspeed
Project Files/Assets/Scripts/General/PlayerMotionScript.cs
4745
using UnityEngine; using System.Collections; public class PlayerMotionScript : MonoBehaviour , IPlayerMotionListener { /****************************************************** * Variables ******************************************************/ private static readonly float RAYCAST_DISTANCE = 5f; private static readonly float MAX_ROTATION_ANGLE = 15f; private static readonly float TURN_ROTATION_SPEED = 5f; private Vector3 startRotation; private Transform myTransform; private PlayerTurnMotion currentTurnMotion = PlayerTurnMotion.Center; private Quaternion turnMotion; /****************************************************** * MonoBehaviour methods, Awake ******************************************************/ void Awake() { this.myTransform = transform; startRotation = myTransform.eulerAngles; } /****************************************************** * MonoBehaviour methods, Start ******************************************************/ void Start() { PlayerScript player = transform.parent.parent.GetComponent<PlayerScript>(); player.addMotionListener(this); } /****************************************************** * MonoBehaviour methods, Update ******************************************************/ void Update () { // path normal rotation RaycastHit hit; if (Physics.Raycast(myTransform.position, -Vector3.up, out hit)) { myTransform.rotation = Quaternion.Slerp(myTransform.rotation, (Quaternion.FromToRotation(myTransform.up, hit.normal) * myTransform.rotation), Time.deltaTime * 2f); } else { myTransform.rotation = Quaternion.Slerp(myTransform.rotation, new Quaternion(), Time.deltaTime * 2f); } // turn rotation switch (currentTurnMotion) { case PlayerTurnMotion.Right: myTransform.localRotation = Quaternion.Slerp( myTransform.localRotation, myTransform.localRotation * Quaternion.Euler(Vector3.forward * ((myTransform.localEulerAngles.z > 360 - MAX_ROTATION_ANGLE || myTransform.localEulerAngles.z < MAX_ROTATION_ANGLE ) ? (360 - MAX_ROTATION_ANGLE) - myTransform.localEulerAngles.z : MAX_ROTATION_ANGLE)), Time.deltaTime * TURN_ROTATION_SPEED); break; case PlayerTurnMotion.Left: myTransform.localRotation = Quaternion.Slerp( myTransform.localRotation, myTransform.localRotation * Quaternion.Euler(Vector3.forward * ((myTransform.localEulerAngles.z > MAX_ROTATION_ANGLE) ? MAX_ROTATION_ANGLE - myTransform.localEulerAngles.z : MAX_ROTATION_ANGLE)), Time.deltaTime * TURN_ROTATION_SPEED); break; case PlayerTurnMotion.Center: myTransform.localRotation = Quaternion.Slerp( myTransform.localRotation, Quaternion.Euler(Vector3.zero) * myTransform.localRotation, Time.deltaTime * 5f); break; } } /****************************************************** * Unused IPlayerMotionListener methods ******************************************************/ public void OnAccelrate(){} public void OnIdle(){} public void OnReverse(){} public void OnUpdateTurnLeft(){} public void OnUpdateTurnRight(){} /****************************************************** * IPlayerMotionListener methods, OnTurnLeft ******************************************************/ public void OnTurnLeft() { currentTurnMotion = PlayerTurnMotion.Left; } /****************************************************** * IPlayerMotionListener methods, OnTurnRight ******************************************************/ public void OnTurnRight() { currentTurnMotion = PlayerTurnMotion.Right; } /****************************************************** * IPlayerMotionListener methods, OnCenter ******************************************************/ public void OnCenter() { currentTurnMotion = PlayerTurnMotion.Center; } }
mit
Azure/azure-sdk-for-python
sdk/storage/azure-storage-file-share/tests/perfstress_tests/T1_legacy_tests/upload_from_file.py
1528
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- import os import tempfile import uuid from azure_devtools.perfstress_tests import get_random_bytes from ._test_base import _LegacyShareTest class LegacyUploadFromFileTest(_LegacyShareTest): temp_file = None def __init__(self, arguments): super().__init__(arguments) self.file_name = "sharefiletest-" + str(uuid.uuid4()) async def global_setup(self): await super().global_setup() data = get_random_bytes(self.args.size) with tempfile.NamedTemporaryFile(delete=False) as temp_file: LegacyUploadFromFileTest.temp_file = temp_file.name temp_file.write(data) async def global_cleanup(self): os.remove(LegacyUploadFromFileTest.temp_file) await super().global_cleanup() def run_sync(self): self.service_client.create_file_from_path( share_name=self.share_name, directory_name=None, file_name=self.file_name, local_file_path=LegacyUploadFromFileTest.temp_file, max_connections=self.args.max_concurrency) async def run_async(self): raise NotImplementedError("Async not supported for legacy T1 tests.")
mit
kevinboogaard/Sports_World-Ball_Pit
advancedgames.ballpit.game/src/adgserver.js
2459
/** * @author Kevin Boogaard <{@link http://www.kevinboogaard.com/}> * @author Alex Antonides <{@link http://www.alex-antonides.com/}> * @license {@link https://github.com/kevinboogaard/Sports_World-Ball_Pit/blob/master/LICENSE} * @ignore */ var net = net || { session: null }; net.ADServer = (function () { 'use strict'; /** * @class ADServer * @extends Post * @constructor * @param {String} url */ function ADServer(url) { net.Post.call(this, url); /** * @property {String} _BaseURL * @private * @default environment.BASE_URL; */ this._baseURL = ballpit.BASE_URL; } ADServer.prototype = Object.create(net.Post.prototype); ADServer.prototype.constructor = ADServer; var p = ADServer.prototype; /** * @method Send * @memberof ADServer * @public * @param {Object} params * @param {Function} callback */ p.__send = p.Send; p.Send = function (params, callback) { if (net.sessionID != null) { this.beforeSend = function (request) { request.setRequestHeader("session", net.sessionID); } } this.__send( params, callback ); }; /** * @method _OnComplete * @memberof ADServer * @private * @param {String} Response * @param {String} TextStatus * @param {Object} Request */ p._onComplete = function ( response, textStatus, request ) { var sessionID = response.session; if (sessionID != null) { net.sessionID = sessionID; }; if ( this.callback ) this.callback.call( null, response ); else this.defaultCallback.call( null, response ); }; /** * @method _DefaultCallback * @memberof ADServer * @private * @param {String} Response */ p.__defaultCallback = p.DefaultCallback; p.DefaultCallback = function ( response ) { Debug.Log( "The ADServer response for: " + this._url + " \n Response: " + response ); }; /** * @method _OnError * @memberof ADServer * @private * @param {Object} Xhr * @param {String} TextStatus * @param {String} ErrorThrown */ p.__onError = p.OnError; p.OnError = function ( xhr, textStatus, errorThrown ) { this.__onError(); }; return ADServer; })(); net.GET_HIGHSCORES = new net.ADServer( 'GetHighscores'); net.SAVE_HIGHSCORE = new net.ADServer( 'SaveHighscoreFromPost');
mit
jeka-pc13/rentacar
application/models/Automovel_model.php
5331
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Automovel_model extends CI_Model { public function __construct(){ parent::__construct(); $this->load->database(); } /** * Retorna todos os automoveis da base de dados com as suas tuplas legiveis * * @return array array de objetos, onde cada objeto é um automovel */ public function obterTodosAutomoveis():array{ $select = "autos.id as id, m.nome as modelo, f.nome as fabricante, matricula, c.nome as cor, autos.disponibilidade as disponibilidade"; $this->db->select($select) ->from("automoveis.automoveis autos") ->join("automoveis.cores c", "autos.cor_id = c.id") //Cores ->join("automoveis.modelos m", "autos.modelo_id = m.id")//modelo ->join("automoveis.fabricantes f", "m.fabricante-id = f.id") ->group_by("autos.id"); // ->limit($limit,$offset); return $this->db->get()->result(); } /** * dado um array associativo (com chaves possieveis: modelo, matricula e * fabricante) esta funcao retorna um array de objetos com todos os * automoveis que satizfagam esse filtro * * @param array $search array associativo (com chaves: modelo, * matricula e/ou fabricante) * @param integer $offset The offset * @param integer $limit The limit * * @return array array de objetos resultante da pesquisa na base de dados */ public function obterAutomoveisPorFiltro(array $search = array(), int $offset=0, int $limit=ITEMS_PER_PAGE):array{ if ($search['modelo'] ?? false) { $this->db->like("m.nome",$search['modelo']); } if ($search['matricula'] ?? false) { $this->db->like("matricula",$search['matricula']); } if ($search['fabricante'] ?? false) { $this->db->like('f.nome',$search['fabricante']); } $select = "autos.id as id, m.nome as modelo, f.nome as fabricante, matricula, c.nome as cor, autos.disponibilidade as disponibilidade"; $this->db->select($select) ->from("automoveis.automoveis autos") ->join("automoveis.cores c", "autos.cor_id = c.id") //Cores ->join("automoveis.modelos m", "autos.modelo_id = m.id")//modelo ->join("automoveis.fabricantes f", "m.fabricante_id = f.id") ->where("autos.cremovido = 0") ->order_by("autos.id") ->limit($limit,$offset); //return $this->db->get()->result(); $this->load->library('carro'); return $this->db->get()->custom_result_object('Carro'); } public function getAutomoveisListCount(array $search=array()):int{ if ($search['modelo'] ?? false) { $this->db->like("m.nome",$search['modelo']); } if ($search['matricula'] ?? false) { $this->db->like("matricula",$search['matricula']); } if ($search['fabricante'] ?? false) { $this->db->like('f.nome', $search['fabricante']); } $select = "autos.id as id"; $this->db->select($select) ->from("automoveis.automoveis autos") ->join("automoveis.cores c", "autos.cor_id = c.id") //Cores ->join("automoveis.modelos m", "autos.modelo_id = m.id")//modelo ->join("automoveis.fabricantes f", "m.fabricante_id = f.id") ->where("autos.cremovido = 0") ->group_by("autos.id"); return $this->db->count_all_results(); } /** * retorna todas as matriculas dos carros * * @return <array> array de objetos contendo todas as matriculos */ public function obterMatriculas():array{ $select = "autos.matricula"; $this->db->select($select) ->from("automoveis.automoveis autos") ->where("autos.matricula IS NOT NULL") ->order_by("autos.id"); // ->limit($limit,$offset); return $this->db->get()->result(); } /** * { function_description } * * @param integer $id The identifier * @param array $data array asociativo com os valores a atualiza, * as key possiveis para o array são: * modelo_id, cor_id, disponibilidade, * matricula * * @return <type> ( description_of_the_return_value ) */ public function editarAutomovel(int $id, array $data){ //var_dump($data); //var_dump($id); $this->db->where('id', $id); // remover items do array com chaves como id, cremovido ou algo fora das // keys possiveis $this->db->update('automoveis',$data); return $this->db->affected_rows(); } /** * remove um automovel da base de dados alterando o seu booleano de removido * * @param integer $id The identifier * * @return <type> ( description_of_the_return_value ) */ public function removerAutomovel(int $id){ $this->db->where('id', $id); $this->db->set('cremovido', 1); $this->db->update('automoveis'); return $this->db->affected_rows(); } public function create($data){ //echo "estoy en funcion create"; $automovel = array( 'modelo_id'=>$data['modelo'], 'cor_id'=>$data['cor'], 'disponibilidade'=>$data['estado'], 'matricula'=>strtoupper($data['matricula']) ); $this->db->insert('automoveis', $automovel); return $carto_id = $this->db->insert_id(); } public function getCarroById($id){ $this->db->from("automoveis.automoveis autos") ->where("autos.id",$id); // ->limit($limit,$offset); return $this->db->get()->row(); } }
mit
dotnet/roslyn-analyzers
src/NetAnalyzers/UnitTests/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/IdentifiersShouldNotMatchKeywordsMemberRuleTests.cs
29140
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Testing; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.IdentifiersShouldNotMatchKeywordsAnalyzer, Microsoft.CodeQuality.CSharp.Analyzers.ApiDesignGuidelines.CSharpIdentifiersShouldNotMatchKeywordsFixer>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.IdentifiersShouldNotMatchKeywordsAnalyzer, Microsoft.CodeQuality.VisualBasic.Analyzers.ApiDesignGuidelines.BasicIdentifiersShouldNotMatchKeywordsFixer>; namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests { /// <summary> /// Contains those unit tests for the IdentifiersShouldNotMatchKeywords analyzer that /// pertain to the MemberRule, which applies to the names of type members. /// </summary> public class IdentifiersShouldNotMatchKeywordsMemberRuleTests { [Fact] public async Task CSharpDiagnosticForKeywordNamedPublicVirtualMethodInPublicClassAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C { public virtual void @internal() {} }", GetCSharpResultAt(4, 25, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C.internal()", "internal")); } [Fact] public async Task BasicDiagnosticForKeywordNamedPublicVirtualMethodInPublicClassAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class C Public Overridable Sub internal() End Sub End Class ", GetBasicResultAt(3, 28, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C.internal()", "internal")); } [Fact] public async Task CSharpNoDiagnosticForCaseSensitiveKeywordNamedPublicVirtualMethodInPublicClassWithDifferentCasingAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C { public virtual void @iNtErNaL() {} }"); } [Fact] public async Task BasicNoDiagnosticForCaseSensitiveKeywordNamedPublicVirtualMethodInPublicClassWithDifferentCasingAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class C Public Overridable Sub iNtErNaL() End Sub End Class"); } [Fact] public async Task CSharpDiagnosticForCaseInsensitiveKeywordNamedPublicVirtualMethodInPublicClassAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C { // Matches VB AddHandler keyword: public virtual void aDdHaNdLeR() {} }", GetCSharpResultAt(5, 25, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C.aDdHaNdLeR()", "AddHandler")); } [Fact] public async Task BasicDiagnosticForCaseInsensitiveKeywordNamedPublicVirtualMethodInPublicClassAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class C ' Matches VB AddHandler keyword: Public Overridable Sub [aDdHaNdLeR]() End Sub End Class", GetBasicResultAt(4, 28, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C.aDdHaNdLeR()", "AddHandler")); } [Fact] public async Task CSharpDiagnosticForKeywordNamedProtectedVirtualMethodInPublicClassAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C { protected virtual void @for() {} }", GetCSharpResultAt(4, 28, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C.for()", "for")); } [Fact] public async Task BasicDiagnosticForKeywordNamedProtectedVirtualMethodInPublicClassAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class C Protected Overridable Sub [for]() End Sub End Class", GetBasicResultAt(3, 31, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C.for()", "for")); } [Fact] public async Task CSharpNoDiagnosticForKeywordNamedInternalVirtualMethodInPublicClassAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C { internal virtual void @for() {} }"); } [Fact] public async Task BasicNoDiagnosticForKeywordNamedInternalVirtualMethodInPublicClassAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class C Friend Overridable Sub [for]() End Sub End Class"); } [Fact] public async Task CSharpNoDiagnosticForKeywordNamedPublicNonVirtualMethodInPublicClassAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C { public void @for() {} }"); } [Fact] public async Task BasicNoDiagnosticForKeywordNamedPublicNonVirtualMethodInPublicClassAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class C Public Sub [for]() End Sub End Class"); } [Fact] public async Task CSharpNoDiagnosticForNonKeywordNamedPublicVirtualMethodInPublicClassAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C { public virtual void fort() {} }"); } [Fact] public async Task BasicNoDiagnosticForNonKeywordNamedPublicVirtualMethodInPublicClassAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class C Public Overridable Sub fort() End Sub End Class"); } [Fact] public async Task CSharpNoDiagnosticForKeywordNamedVirtualMethodInInternalClassAsync() { await VerifyCS.VerifyAnalyzerAsync(@" internal class C { public virtual void @for() {} }"); } [Fact] public async Task BasicNoDiagnosticForKeywordNamedVirtualMethodInInternalClassAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Friend Class C Public Overridable Sub [for]() End Sub End Class"); } [Fact] public async Task CSharpDiagnosticForKeywordNamedMethodInPublicInterfaceAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public interface I { void @for(); }", GetCSharpResultAt(4, 10, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "I.for()", "for")); } [Fact] public async Task BasicDiagnosticForKeywordNamedMethodInPublicInterfaceAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Interface I Sub [for]() End Interface", GetBasicResultAt(3, 9, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "I.for()", "for")); } [Fact] public async Task CSharpNoDiagnosticForKeywordNamedMethodOfInternalInterfaceAsync() { await VerifyCS.VerifyAnalyzerAsync(@" internal interface I { void @for(); }"); } [Fact] public async Task BasicNoDiagnosticForKeywordNamedMethodOfInternalInterfaceAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Friend Interface I Sub [for]() End Interface"); } [Fact] public async Task CSharpDiagnosticForKeyWordNamedPublicVirtualPropertyOfPublicClassAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C { private int _for; public virtual int @for { get { return _for; } set { _for = value; } } }", GetCSharpResultAt(5, 24, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C.for", "for")); } [Fact] public async Task BasicDiagnosticForKeyWordNamedPublicVirtualPropertyOfPublicClassAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class C Private _for As Integer Public Overridable Property [Sub] As Integer Get Return _for End Get Set(value As Integer) _for = value End Set End Property End Class", GetBasicResultAt(4, 33, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C.Sub", "Sub")); } [Fact] public async Task CSharpDiagnosticForKeyWordNamedPublicVirtualAutoPropertyOfPublicClassAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C { public virtual int @for { get; set; } }", GetCSharpResultAt(4, 24, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C.for", "for")); } [Fact] public async Task BasicDiagnosticForKeyWordNamedPublicVirtualAutoPropertyOfPublicClassAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class C Public Overridable Property [Sub] As Integer End Class", GetBasicResultAt(3, 33, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C.Sub", "Sub")); } [Fact] public async Task CSharpDiagnosticForKeyWordNamedPublicVirtualReadOnlyPropertyOfPublicClassAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C { private int _for; public virtual int @for { get { return _for; } } }", GetCSharpResultAt(5, 24, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C.for", "for")); } [Fact] public async Task BasicDiagnosticForKeyWordNamedPublicVirtualReadOnlyPropertyOfPublicClassAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class C Private _for As Integer Public Overridable ReadOnly Property [Sub] As Integer Get Return _for End Get End Property End Class", GetBasicResultAt(4, 42, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C.Sub", "Sub")); } [Fact] public async Task CSharpDiagnosticForKeyWordNamedPublicVirtualWriteOnlyPropertyOfPublicClassAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C { private int _for; public virtual int @for { set { _for = value; } } }", GetCSharpResultAt(5, 24, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C.for", "for")); } [Fact] public async Task BasicDiagnosticForKeyWordNamedPublicVirtualWriteOnlyPropertyOfPublicClassAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class C Private _for As Integer Public Overridable WriteOnly Property [Sub] As Integer Set(value As Integer) _for = value End Set End Property End Class", GetBasicResultAt(4, 43, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C.Sub", "Sub")); } [Fact] public async Task CSharpDiagnosticForKeyWordNamedPublicVirtualExpressionBodyPropertyOfPublicClassAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C { private int _for; public virtual int @for => _for; }", GetCSharpResultAt(5, 24, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C.for", "for")); } [Fact] public async Task CSharpNoDiagnosticForOverrideOfKeywordNamedPublicVirtualMethodOfPublicClassAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C { public virtual void @internal() {} } public class D : C { public override void @internal() {} }", // Diagnostic for the virtual in C, but none for the override in D. GetCSharpResultAt(4, 25, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C.internal()", "internal")); } [Fact] public async Task BasicNoDiagnosticForOverrideOfKeywordNamedPublicVirtualMethodOfPublicClassAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class C Public Overridable Sub [internal]() End Sub End Class Public Class D Inherits C Public Overrides Sub [internal]() End Sub End Class", // Diagnostic for the virtual in C, but none for the override in D. GetBasicResultAt(3, 28, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C.internal()", "internal")); } [Fact] public async Task CSharpNoDiagnosticForSealedOverrideOfKeywordNamedPublicVirtualMethodOfPublicClassAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C { public virtual void @internal() {} } public class D : C { public sealed override void @internal() {} }", // Diagnostic for the virtual in C, but none for the sealed override in D. GetCSharpResultAt(4, 25, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C.internal()", "internal")); } [Fact] public async Task BasicNoDiagnosticForSealedOverrideOfKeywordNamedPublicVirtualMethodOfPublicClassAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class C Public Overridable Sub [friend]() End Sub End Class Public Class D Inherits C Public NotOverridable Overrides Sub [friend]() End Sub End Class", // Diagnostic for the virtual in C, but none for the sealed override in D. GetBasicResultAt(3, 28, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C.friend()", "friend")); } [Fact] public async Task CSharpDiagnosticForEachOverloadOfCaseSensitiveKeywordNamedPublicVirtualMethodInPublicClassAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C { public virtual void @internal() {} public virtual void @internal(int n) {} }", GetCSharpResultAt(4, 25, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C.internal()", "internal"), GetCSharpResultAt(5, 25, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C.internal(int)", "internal")); } [Fact] public async Task BasicDiagnosticForEachOverloadOfCaseSensitiveKeywordNamedPublicVirtualMethodInPublicClassAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class C Public Overridable Sub internal() End Sub Public Overridable Sub internal(n As Integer) End Sub End Class", GetBasicResultAt(3, 28, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C.internal()", "internal"), GetBasicResultAt(5, 28, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C.internal(Integer)", "internal")); } [Fact] public async Task CSharpNoDiagnosticForKeywordNamedNewMethodInPublicClassAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C { public virtual void @for() {} } public class D : C { public new void @for() {} }", // Diagnostic for the virtual in C, but none for the new method in D. GetCSharpResultAt(4, 25, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C.for()", "for")); } [Fact] public async Task BasicNoDiagnosticForKeywordNamedNewMethodInPublicClassAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class C Public Overridable Sub [for]() End Sub End Class Public Class D Inherits C Public Shadows Sub [for]() End Sub End Class", // Diagnostic for the virtual in C, but none for the new method in D. GetBasicResultAt(3, 28, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C.for()", "for")); } [Fact] public async Task CSharpDiagnosticForVirtualNewMethodAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C { public virtual void @for() {} } public class D : C { public virtual new void @for() {} }", // Diagnostics for both the virtual in C, and the virtual new method in D. GetCSharpResultAt(4, 25, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C.for()", "for"), GetCSharpResultAt(9, 29, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "D.for()", "for")); } [Fact] public async Task BasicDiagnosticForVirtualNewMethodAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class C Public Overridable Sub [for]() End Sub End Class Public Class D Inherits C Public Overridable Shadows Sub [for]() End Sub End Class", // Diagnostics for both the virtual in C, and the virtual new method in D. GetBasicResultAt(3, 28, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C.for()", "for"), GetBasicResultAt(10, 36, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "D.for()", "for")); } [Fact] public async Task CSharpDiagnosticForKeywordNamedProtectedVirtualMethodInProtectedTypeNestedInPublicClassAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C { protected class D { protected virtual void @protected() {} } }", GetCSharpResultAt(6, 32, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C.D.protected()", "protected")); } [Fact] public async Task BasicDiagnosticForKeywordNamedProtectedVirtualMethodInProtectedTypeNestedInPublicClassAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class C Protected Class D Protected Overridable Sub [Protected]() End Sub End Class End Class", GetBasicResultAt(4, 35, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C.D.Protected()", "Protected")); } [Fact] public async Task CSharpDiagnosticForKeywordNamedPublicVirtualEventInPublicClassAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C { public delegate void Callback(object sender, System.EventArgs e); public virtual event Callback @float; }", // Diagnostics for both the virtual in C, and the virtual new method in D. GetCSharpResultAt(5, 35, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C.float", "float")); } // These tests are just to verify that the formatting of the displayed member name // is consistent with FxCop, for the case where the class is in a namespace. [Fact] public async Task CSharpDiagnosticForVirtualPublicMethodInPublicClassInNamespaceAsync() { await VerifyCS.VerifyAnalyzerAsync(@" namespace N { public class C { public virtual void @for() {} } }", // Don't include the namespace name. GetCSharpResultAt(6, 29, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C.for()", "for")); } [Fact] public async Task BasicDiagnosticForVirtualPublicMethodInPublicClassInNamespaceAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Namespace N Public Class C Public Overridable Sub [for]() End Sub End Class End Namespace", // Don't include the namespace name. GetBasicResultAt(4, 32, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C.for()", "for")); } // These tests are just to verify that the formatting of the displayed member name // is consistent with FxCop, for the case where the class is generic. [Fact] public async Task CSharpDiagnosticForVirtualPublicMethodInPublicGenericClassAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class C<T> where T : class { public virtual void @for() {} }", // Include the type parameter name but not the constraint. GetCSharpResultAt(4, 25, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C<T>.for()", "for")); } [Fact] public async Task BasicDiagnosticForVirtualPublicMethodInPublicGenericClassAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class C(Of T As Class) Public Overridable Sub [for]() End Sub End Class", // Include the type parameter name but not the constraint. GetBasicResultAt(3, 28, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C(Of T).for()", "for")); } [Theory] [InlineData("dotnet_code_quality.analyzed_symbol_kinds = NamedType")] [InlineData("dotnet_code_quality.analyzed_symbol_kinds = NamedType, Property")] [InlineData("dotnet_code_quality.CA1716.analyzed_symbol_kinds = NamedType")] [InlineData("dotnet_code_quality.CA1716.analyzed_symbol_kinds = NamedType, Property")] public async Task UserOptionDoesNotIncludeMethod_NoDiagnosticAsync(string editorConfigText) { await new VerifyCS.Test { TestState = { Sources = { @" public class C { public virtual void @internal() {} } ", }, AnalyzerConfigFiles = { ("/.editorconfig", $@"root = true [*] {editorConfigText} ") }, }, }.RunAsync(); await new VerifyVB.Test { TestState = { Sources = { @" Public Class C Public Overridable Sub internal() End Sub End Class", }, AnalyzerConfigFiles = { ("/.editorconfig", $@"root = true [*] {editorConfigText} ") }, }, }.RunAsync(); } [Theory] [InlineData("dotnet_code_quality.analyzed_symbol_kinds = Method")] [InlineData("dotnet_code_quality.analyzed_symbol_kinds = NamedType, Method")] [InlineData("dotnet_code_quality.CA1716.analyzed_symbol_kinds = Method")] [InlineData("dotnet_code_quality.CA1716.analyzed_symbol_kinds = NamedType, Method")] public async Task UserOptionIncludesMethod_DiagnosticAsync(string editorConfigText) { await new VerifyCS.Test { TestState = { Sources = { @" public class C { public virtual void @internal() {} } ", }, AnalyzerConfigFiles = { ("/.editorconfig", $@"root = true [*] {editorConfigText} ") }, ExpectedDiagnostics = { GetCSharpResultAt(4, 25, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C.internal()", "internal"), }, }, }.RunAsync(); await new VerifyVB.Test { TestState = { Sources = { @" Public Class C Public Overridable Sub internal() End Sub End Class", }, AnalyzerConfigFiles = { ("/.editorconfig", $@"root = true [*] {editorConfigText} ") }, ExpectedDiagnostics = { GetBasicResultAt(3, 28, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C.internal()", "internal"), }, }, }.RunAsync(); } [Theory] [InlineData("dotnet_code_quality.analyzed_symbol_kinds = NamedType")] [InlineData("dotnet_code_quality.analyzed_symbol_kinds = NamedType, Method")] [InlineData("dotnet_code_quality.CA1716.analyzed_symbol_kinds = NamedType")] [InlineData("dotnet_code_quality.CA1716.analyzed_symbol_kinds = NamedType, Method")] public async Task UserOptionDoesNotIncludeProperty_NoDiagnosticAsync(string editorConfigText) { await new VerifyCS.Test { TestState = { Sources = { @" public class C { public virtual int @for { get; set; } } ", }, AnalyzerConfigFiles = { ("/.editorconfig", $@"root = true [*] {editorConfigText} ") }, }, }.RunAsync(); await new VerifyVB.Test { TestState = { Sources = { @" Public Class C Public Overridable Property [Sub] As Integer End Class", }, AnalyzerConfigFiles = { ("/.editorconfig", $@"root = true [*] {editorConfigText} ") }, }, }.RunAsync(); } [Theory] [InlineData("dotnet_code_quality.analyzed_symbol_kinds = Property")] [InlineData("dotnet_code_quality.analyzed_symbol_kinds = NamedType, Property")] [InlineData("dotnet_code_quality.CA1716.analyzed_symbol_kinds = Property")] [InlineData("dotnet_code_quality.CA1716.analyzed_symbol_kinds = NamedType, Property")] public async Task UserOptionIncludesProperty_DiagnosticAsync(string editorConfigText) { await new VerifyCS.Test { TestState = { Sources = { @" public class C { public virtual int @for { get; set; } } ", }, AnalyzerConfigFiles = { ("/.editorconfig", $@"root = true [*] {editorConfigText} ") }, ExpectedDiagnostics = { GetCSharpResultAt(4, 24, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C.for", "for"), }, }, }.RunAsync(); await new VerifyVB.Test { TestState = { Sources = { @" Public Class C Public Overridable Property [Sub] As Integer End Class", }, AnalyzerConfigFiles = { ("/.editorconfig", $@"root = true [*] {editorConfigText} ") }, ExpectedDiagnostics = { GetBasicResultAt(3, 33, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C.Sub", "Sub"), }, }, }.RunAsync(); } [Theory] [InlineData("dotnet_code_quality.analyzed_symbol_kinds = NamedType")] [InlineData("dotnet_code_quality.analyzed_symbol_kinds = NamedType, Property")] [InlineData("dotnet_code_quality.CA1716.analyzed_symbol_kinds = NamedType")] [InlineData("dotnet_code_quality.CA1716.analyzed_symbol_kinds = NamedType, Property")] public async Task UserOptionDoesNotIncludeEvent_NoDiagnosticAsync(string editorConfigText) { await new VerifyCS.Test { TestState = { Sources = { @" public class C { public delegate void Callback(object sender, System.EventArgs e); public virtual event Callback @float; } ", }, AnalyzerConfigFiles = { ("/.editorconfig", $@"root = true [*] {editorConfigText} ") }, }, }.RunAsync(); } [Theory] [InlineData("dotnet_code_quality.analyzed_symbol_kinds = Event")] [InlineData("dotnet_code_quality.analyzed_symbol_kinds = NamedType, Event")] [InlineData("dotnet_code_quality.CA1716.analyzed_symbol_kinds = Event")] [InlineData("dotnet_code_quality.CA1716.analyzed_symbol_kinds = NamedType, Event")] public async Task UserOptionIncludesEvent_DiagnosticAsync(string editorConfigText) { await new VerifyCS.Test { TestState = { Sources = { @" public class C { public delegate void Callback(object sender, System.EventArgs e); public virtual event Callback @float; } ", }, AnalyzerConfigFiles = { ("/.editorconfig", $@"root = true [*] {editorConfigText} ") }, ExpectedDiagnostics = { GetCSharpResultAt(5, 35, IdentifiersShouldNotMatchKeywordsAnalyzer.MemberRule, "C.float", "float"), }, }, }.RunAsync(); } private static DiagnosticResult GetCSharpResultAt(int line, int column, DiagnosticDescriptor rule, params string[] arguments) #pragma warning disable RS0030 // Do not used banned APIs => VerifyCS.Diagnostic(rule) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(arguments); private static DiagnosticResult GetBasicResultAt(int line, int column, DiagnosticDescriptor rule, params string[] arguments) #pragma warning disable RS0030 // Do not used banned APIs => VerifyVB.Diagnostic(rule) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(arguments); } }
mit
asottile/add-trailing-comma
add_trailing_comma/_plugins/literals.py
3244
from __future__ import annotations import ast import functools import sys from typing import Iterable from tokenize_rt import NON_CODING_TOKENS from tokenize_rt import Offset from tokenize_rt import Token from add_trailing_comma._ast_helpers import ast_to_offset from add_trailing_comma._data import register from add_trailing_comma._data import State from add_trailing_comma._data import TokenFunc from add_trailing_comma._token_helpers import find_simple from add_trailing_comma._token_helpers import Fix from add_trailing_comma._token_helpers import fix_brace def _fix_literal( i: int, tokens: list[Token], *, one_el_tuple: bool, ) -> None: fix_brace( tokens, find_simple(i, tokens), add_comma=True, remove_comma=not one_el_tuple, ) @register(ast.Set) def visit_Set( state: State, node: ast.Set, ) -> Iterable[tuple[Offset, TokenFunc]]: func = functools.partial(_fix_literal, one_el_tuple=False) yield ast_to_offset(node), func @register(ast.List) def visit_List( state: State, node: ast.List, ) -> Iterable[tuple[Offset, TokenFunc]]: if node.elts: func = functools.partial(_fix_literal, one_el_tuple=False) yield ast_to_offset(node), func @register(ast.Dict) def visit_Dict( state: State, node: ast.Dict, ) -> Iterable[tuple[Offset, TokenFunc]]: if node.values: func = functools.partial(_fix_literal, one_el_tuple=False) yield ast_to_offset(node), func def _find_tuple(i: int, tokens: list[Token]) -> Fix | None: # tuples are evil, we need to backtrack to find the opening paren i -= 1 while tokens[i].name in NON_CODING_TOKENS: i -= 1 # Sometimes tuples don't even have a paren! # x = 1, 2, 3 if tokens[i].src != '(' and tokens[i].src != '[': return None return find_simple(i, tokens) def _fix_tuple( i: int, tokens: list[Token], *, one_el_tuple: bool, ) -> None: fix_brace( tokens, _find_tuple(i, tokens), add_comma=True, remove_comma=not one_el_tuple, ) def _fix_tuple_py38( i: int, tokens: list[Token], *, one_el_tuple: bool, ) -> None: # pragma: >=3.8 cover fix = find_simple(i, tokens) # for tuples we *must* find a comma, otherwise it is not a tuple if fix is None or not fix.multi_arg: return fix_brace( tokens, fix, add_comma=True, remove_comma=not one_el_tuple, ) @register(ast.Tuple) def visit_Tuple( state: State, node: ast.Tuple, ) -> Iterable[tuple[Offset, TokenFunc]]: if node.elts: is_one_el = len(node.elts) == 1 if ( ast_to_offset(node) == ast_to_offset(node.elts[0]) or # in < py38 tuples lie about offset -- later we must backtrack sys.version_info < (3, 8) ): func = functools.partial(_fix_tuple, one_el_tuple=is_one_el) yield ast_to_offset(node), func else: # pragma: >=3.8 cover func = functools.partial(_fix_tuple_py38, one_el_tuple=is_one_el) yield ast_to_offset(node), func
mit